target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
src/desktop/apps/order/client.js | xtina-starr/force | import { buildClientApp } from "reaction/Artsy/Router/client"
import { data as sd } from "sharify"
import { routes } from "reaction/Apps/Order/routes"
import mediator from "desktop/lib/mediator.coffee"
import React from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import User from "desktop/models/user.coffee"
import Artwork from "desktop/models/artwork.coffee"
import ArtworkInquiry from "desktop/models/artwork_inquiry.coffee"
import openInquiryQuestionnaireFor from "desktop/components/inquiry_questionnaire/index.coffee"
mediator.on("openOrdersContactArtsyModal", options => {
const artworkId = options.artworkId
if (artworkId) {
const user = User.instantiate()
const inquiry = new ArtworkInquiry({ notification_delay: 600 })
const artwork = new Artwork({ id: artworkId })
artwork.fetch().then(() => {
openInquiryQuestionnaireFor({
user,
artwork,
inquiry,
ask_specialist: true,
})
})
}
})
// Track page views for order checkout flow: shipping, payment and review.
// These events are triggered from Reaction.
const orderCheckoutFlowEvents = [
"order:shipping",
"order:payment",
"order:review",
"order:status",
]
orderCheckoutFlowEvents.map(eventName => {
mediator.on(eventName, () => {
window.analytics.page(
{ path: window.location.pathname },
{ integrations: { Marketo: false } }
)
// Reset timers that track time on page since we're tracking each order
// checkout view as a separate page.
typeof window.desktopPageTimeTrackers !== "undefined" &&
window.desktopPageTimeTrackers.forEach(tracker => {
// No need to reset the tracker if we're on the same page.
if (window.location.pathname !== tracker.path)
tracker.reset(window.location.pathname)
})
})
})
buildClientApp({
routes,
context: {
user: sd.CURRENT_USER,
mediator,
},
history: {
options: {
useBeforeUnload: true,
},
},
})
.then(({ ClientApp }) => {
ReactDOM.hydrate(
<ClientApp />,
document.getElementById("react-root")
)
})
.catch(error => {
console.error(error)
})
if (module.hot) {
module.hot.accept()
}
|
src/components/app/MasterWindow.js | metasfresh/metasfresh-webui-frontend | import { Hints, Steps } from 'intro.js-react';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { discardNewRow, discardNewDocument, getTab } from '../../api';
import BlankPage from '../BlankPage';
import Container from '../Container';
import Window from '../Window';
import Overlay from '../app/Overlay';
import { introHints, introSteps } from '../intro/intro';
/**
* @file Class based component.
* @module MasterWindow
* @extends Component
*/
export default class MasterWindow extends Component {
state = {
newRow: false,
modalTitle: null,
isDeleted: false,
dropzoneFocused: false,
introEnabled: null,
hintsEnabled: null,
introSteps: null,
introHints: null,
};
componentDidMount() {
const { master } = this.props;
const isDocumentNotSaved = !master.saveStatus.saved;
if (isDocumentNotSaved) {
this.initEventListeners();
}
}
componentDidUpdate(prevProps) {
const { master, me } = this.props;
const isDocumentNotSaved = !master.saveStatus.saved;
const isDocumentSaved = master.saveStatus.saved;
if (
me &&
master &&
master.docId &&
master.layout &&
master.layout.windowId &&
this.state.introEnabled === null
) {
let docIntroSteps, docIntroHints;
const windowIntroSteps = introSteps[master.layout.windowId];
if (windowIntroSteps) {
docIntroSteps = [];
if (windowIntroSteps['all']) {
docIntroSteps = docIntroSteps.concat(windowIntroSteps['all']);
}
if (master.docId && windowIntroSteps[master.docId]) {
docIntroSteps = docIntroSteps.concat(windowIntroSteps[master.docId]);
}
}
if (Array.isArray(introHints['default'])) {
docIntroHints = introHints['default'];
}
const windowIntroHints = introHints[master.layout.windowId];
if (windowIntroHints) {
docIntroHints = [];
if (windowIntroHints['all']) {
docIntroHints = docIntroHints.concat(windowIntroHints['all']);
}
if (master.docId && windowIntroHints[master.docId]) {
docIntroHints = docIntroHints.concat(windowIntroHints[master.docId]);
}
}
this.setState({
introEnabled: docIntroSteps && docIntroSteps.length > 0,
hintsEnabled: docIntroHints && docIntroHints.length > 0,
introSteps: docIntroSteps,
introHints: docIntroHints,
});
}
if (prevProps.master.saveStatus.saved && isDocumentNotSaved) {
this.initEventListeners();
}
if (!prevProps.master.saveStatus.saved && isDocumentSaved) {
this.removeEventListeners();
}
}
componentWillUnmount() {
const {
master,
push,
location: { pathname },
params: { windowType, docId: documentId },
} = this.props;
const { isDeleted } = this.state;
const isDocumentNotSaved =
!master.saveStatus.saved && master.saveStatus.saved !== undefined;
this.removeEventListeners();
if (isDocumentNotSaved && !isDeleted) {
const result = window.confirm('Do you really want to leave?');
if (result) {
discardNewDocument({ windowType, documentId });
} else {
push(pathname);
}
}
}
/**
* @method confirm
* @summary ToDo: Describe the method.
*/
confirm = (e) => {
e.returnValue = '';
};
/**
* @method initEventListeners
* @summary ToDo: Describe the method.
*/
initEventListeners = () => {
if (!navigator.userAgent.includes('Cypress')) {
// try workaround https://github.com/cypress-io/cypress/issues/1235#issuecomment-411839157 for our "hanging" problem
window.addEventListener('beforeunload', this.confirm);
}
};
/**
* @method removeEventListeners
* @summary ToDo: Describe the method.
*/
removeEventListeners = () => {
window.removeEventListener('beforeunload', this.confirm);
};
/**
* @method closeModalCallback
* @summary ToDo: Describe the method.
*/
closeModalCallback = ({
isNew,
windowType,
documentId,
tabId,
rowId,
} = {}) => {
if (isNew) {
return discardNewRow({ windowType, documentId, tabId, rowId });
}
};
/**
* @method handleDropFile
* @summary ToDo: Describe the method.
*/
handleDropFile = (files) => {
const file = files instanceof Array ? files[0] : files;
if (!(file instanceof File)) {
return Promise.reject();
}
const {
attachFileAction,
master: {
data,
layout: { type },
},
} = this.props;
const dataId = data ? data.ID.value : -1;
let fd = new FormData();
fd.append('file', file);
return attachFileAction(type, dataId, fd);
};
/**
* @method handleDragStart
* @summary ToDo: Describe the method.
*/
handleDragStart = () => {
this.setState(
{
dropzoneFocused: true,
},
() => {
this.setState({
dropzoneFocused: false,
});
}
);
};
/**
* @method handleRejectDropped
* @summary ToDo: Describe the method.
*/
handleRejectDropped = (droppedFiles) => {
const { addNotification } = this.props;
const dropped =
droppedFiles instanceof Array ? droppedFiles[0] : droppedFiles;
addNotification(
'Attachment',
`Dropped item ['${dropped.type}'] could not be attached`,
5000,
'error'
);
};
/**
* @method setModalTitle
* @summary ToDo: Describe the method.
*/
setModalTitle = (title) => {
this.setState({ modalTitle: title });
};
/**
* @method handleDeletedStatus
* @summary ToDo: Describe the method.
*/
handleDeletedStatus = (param) => {
this.setState({ isDeleted: param });
};
/**
* @method sort
* @summary ToDo: Describe the method.
*/
sort = (asc, field, startPage, page, tabId) => {
const {
addRowData,
sortTab,
master,
params: { windowType },
} = this.props;
const orderBy = (asc ? '+' : '-') + field;
const dataId = master.docId;
sortTab('master', tabId, field, asc);
getTab(tabId, windowType, dataId, orderBy).then((res) => {
addRowData({ [tabId]: res }, 'master');
});
};
/**
* @method handleIntroExit
* @summary ToDo: Describe the method.
*/
handleIntroExit = () => {
this.setState({ introEnabled: false });
};
render() {
const {
master,
modal,
breadcrumb,
params,
rawModal,
pluginModal,
overlay,
allowShortcut,
includedView,
processStatus,
enableTutorial,
} = this.props;
const {
dropzoneFocused,
newRow,
modalTitle,
introEnabled,
hintsEnabled,
introSteps,
introHints,
} = this.state;
const { docActionElement, documentSummaryElement } = master.layout;
const dataId = master.docId;
const docNoData = master.data.DocumentNo;
let activeTab;
if (master.layout) {
activeTab = master.layout.activeTab;
}
const docStatusData = {
status: master.data.DocStatus || -1,
action: master.data.DocAction || -1,
displayed: true,
};
const docSummaryData =
documentSummaryElement &&
master.data[documentSummaryElement.fields[0].field];
// valid status for unsaved items with errors does not
// have initialValue set, but does have the error message
const initialValidStatus =
master.validStatus.initialValue !== undefined
? master.validStatus.initialValue
: master.validStatus.valid;
const isDocumentNotSaved =
dataId !== 'notfound' &&
master.saveStatus.saved !== undefined &&
!master.saveStatus.saved &&
!initialValidStatus;
return (
<Container
entity="window"
dropzoneFocused={dropzoneFocused}
docStatusData={docStatusData}
docSummaryData={docSummaryData}
modal={modal}
dataId={dataId}
breadcrumb={breadcrumb}
docNoData={docNoData}
isDocumentNotSaved={isDocumentNotSaved}
rawModal={rawModal}
pluginModal={pluginModal}
modalTitle={modalTitle}
includedView={includedView}
processStatus={processStatus}
activeTab={activeTab}
closeModalCallback={this.closeModalCallback}
setModalTitle={this.setModalTitle}
docActionElem={docActionElement}
windowType={params.windowType}
docId={params.docId}
showSidelist
showIndicator={!modal.visible}
handleDeletedStatus={this.handleDeletedStatus}
>
<Overlay data={overlay.data} showOverlay={overlay.visible} />
{dataId === 'notfound' ? (
<BlankPage what="Document" />
) : (
<Window
key="window"
data={master.data}
layout={master.layout}
rowData={master.rowData}
tabsInfo={master.includedTabsInfo}
sort={this.sort}
dataId={dataId}
isModal={false}
newRow={newRow}
allowShortcut={allowShortcut}
handleDragStart={this.handleDragStart}
handleDropFile={this.handleDropFile}
handleRejectDropped={this.handleRejectDropped}
/>
)}
{enableTutorial && introSteps && introSteps.length > 0 && (
<Steps
enabled={introEnabled}
steps={introSteps}
initialStep={0}
onExit={this.handleIntroExit}
/>
)}
{enableTutorial && introHints && introHints.length > 0 && (
<Hints enabled={hintsEnabled} hints={introHints} />
)}
</Container>
);
}
}
/**
* definition almost identical to /containers/MasterWindow
*/
MasterWindow.propTypes = {
modal: PropTypes.object.isRequired,
master: PropTypes.object.isRequired,
breadcrumb: PropTypes.array.isRequired,
rawModal: PropTypes.object.isRequired,
indicator: PropTypes.string.isRequired,
me: PropTypes.object.isRequired,
pluginModal: PropTypes.object,
overlay: PropTypes.object,
allowShortcut: PropTypes.bool,
params: PropTypes.any,
includedView: PropTypes.any,
processStatus: PropTypes.any,
enableTutorial: PropTypes.any,
location: PropTypes.any,
addNotification: PropTypes.func,
addRowData: PropTypes.func,
attachFileAction: PropTypes.func,
sortTab: PropTypes.func,
push: PropTypes.func,
};
|
src/docs/examples/TextInputStyledComponents/ExampleOptional.js | patchygreen/ps-react-patchygreen | import React from 'react';
import TextInputStyledComponents from "ps-react/TextInputStyledComponents";
/** Optional TextBox */
export default class ExampleOptional extends React.Component {
render() {
return (
<TextInputStyledComponents
htmlId='example-optional'
label='First Name'
name='firstname'
onChange={() => {}}
/>
)
}
} |
_gatsby/src/components/Contact/SocialIcons.js | YannickDot/yannickdot.github.io | import React from 'react'
// import { config } from 'config'
import { rhythm } from '../../utils/typography'
const social = [
{
name: 'Email',
url: 'mailto:[email protected]',
icon: 'fa-envelope-o'
},
{
name: 'Twitter',
icon: 'fa-twitter',
url: 'https://twitter.com/yannickdot'
},
{
name: 'Github',
icon: 'fa-github',
url: 'https://github.com/YannickDot'
},
{
name: 'Instagram',
icon: 'fa-instagram',
url: 'https://www.instagram.com/yannickspark/'
},
{
name: 'Medium',
icon: 'fa-medium',
url: 'https://medium.com/@yannickdot'
}
]
const SocialIcons = ({ size, width }) => {
const st = {
fontSize: size,
width: width,
marginBottom: 0
}
return (
<ul className="social-icons" style={st}>
{social.map(account => {
return (
<li key={account.url}>
<a
href={account.url}
target="_blank"
key={account.icon}
alt={account.name}>
<i className={`fa ${account.icon}`} aria-hidden="true" />
</a>
</li>
)
})}
</ul>
)
}
export default SocialIcons
|
ajax/libs/yui/3.9.0pr2/event-focus/event-focus-debug.js | JimBobSquarePants/cdnjs | YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@', {"requires": ["event-synthetic"]});
|
src/views/components/user-card/index.spec.js | zerubeus/sawt | import React from 'react';
import { shallow } from 'enzyme';
import { User } from '../../../core/users';
import UserCard from './index';
describe('views', () => {
describe('UserCard', () => {
let props;
let user;
beforeEach(() => {
user = new User({
id: 123,
followingsCount: 20,
followersCount: 40,
likesCount: 60,
trackCount: 80,
username: 'username'
});
props = {user};
});
function getWrapper() {
return shallow(
<UserCard {...props} />
);
}
it('should display username', () => {
expect(getWrapper().find('h1').text()).toBe(user.username);
});
it('should display trackCount label linked to user-tracks route', () => {
let label = getWrapper().find('.user-stats__label').at(0);
expect(label.prop('to')).toBe(`/users/${user.id}/tracks`);
});
it('should display FormattedInteger for trackCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(0);
expect(formattedInteger.prop('value')).toBe(user.trackCount);
});
it('should display likesCount label linked to user-likes route', () => {
let label = getWrapper().find('.user-stats__label').at(1);
expect(label.prop('to')).toBe(`/users/${user.id}/likes`);
});
it('should display FormattedInteger for likesCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(1);
expect(formattedInteger.prop('value')).toBe(user.likesCount);
});
it('should display followersCount label', () => {
let label = getWrapper().find('.user-stats__label').at(2);
expect(label.length).toBe(1);
});
it('should display FormattedInteger for followersCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(2);
expect(formattedInteger.prop('value')).toBe(user.followersCount);
});
it('should display followingsCount label', () => {
let label = getWrapper().find('.user-stats__label').at(3);
expect(label.length).toBe(1);
});
it('should display FormattedInteger for followingsCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(3);
expect(formattedInteger.prop('value')).toBe(user.followingsCount);
});
});
});
|
app/js/todo/form.js | pengux/electron-react-starter | import React from 'react';
import TodoActions from './actions';
export default React.createClass({
create(e) {
e.preventDefault();
var task = this.refs.newTask.value;
TodoActions.create({"name": task});
},
render() {
return (
<form onSubmit={this.create}>
<label>
Add task
<input type="text" ref="newTask" />
</label>
</form>
);
}
});
|
tp-3/juan-pablo-gonzalez/src/shared/components/columnsSelector/components/columnList/ColumnList.js | jpgonzalezquinteros/sovos-reactivo-2017 | import React from 'react';
import PropTypes from 'prop-types';
import { VisibleIcon, HiddenIcon } from '../../../svgIcons/SvgIcons'; // eslint-disable-line import/no-extraneous-dependencies
import SovosTooltip from '../../../../../shared/components/sovos-tooltip/SovosTooltip';
import { violet } from '../../../../../theme/PhoenixColors';
import ColumnListItem from './components/ColumnListItem';
import { ItemTypes, DragSourceComponent, WithDragDropContext } from '../../../../../shared/components/dragAndDrop';
const ColumnList = ({ visibleColumns, hiddenColumns, onShowColumn, onHideColumn, onDrop }) => {
let switchInfo = {};
const onDragAndDrop = (dragInfo) => {
switchInfo = {
origin: {
isEnabled: dragInfo.origin,
position: dragInfo.key
},
target: {
isEnabled: dragInfo.container,
position: dragInfo.target
}
};
};
const iconStyle = { height: 16, width: 16 };
const getColumnItem = (column, index, visible) => (
<div className="column-selector__column-row" key={ column.key }>
<div>
<SovosTooltip id={ `col-${index}` } label={ column.label }>
<DragSourceComponent
id={ index }
onEndDrag={ () => { onDrop(switchInfo); } }
itemType={ ItemTypes.DNDCOLUMNSELECTOR }
elementInfo={ { isVisible: visible } }
cantDrag={ visibleColumns.length === 1 }
>
<ColumnListItem
column={ column }
visible={ visible }
onShowColumn={ onShowColumn }
onHideColumn={ onHideColumn }
onDragAndDrop={ onDragAndDrop }
/>
</DragSourceComponent>
</SovosTooltip>
</div>
<div className="column-selector__icon-container">
{
visible ?
<VisibleIcon style={ iconStyle } color={ violet } onTouchTap={ () => { onHideColumn(column); } } /> :
<HiddenIcon style={ iconStyle } color="#7d7d7d" onTouchTap={ () => { onShowColumn(column); } } />
}
</div>
</div>
);
return (
<div className="column-selector__columns-container">
<div className="column-selector__column-group">
{ visibleColumns.map((columnName, index) => getColumnItem(columnName, index, true)) }
</div>
<hr />
<div className="column-selector__column-group">
{ hiddenColumns.map((columnName, index) => getColumnItem(columnName, index, false)) }
</div>
</div>
);
};
ColumnList.propTypes = {
visibleColumns: PropTypes.arrayOf(PropTypes.object).isRequired,
hiddenColumns: PropTypes.arrayOf(PropTypes.object),
onHideColumn: PropTypes.func.isRequired,
onShowColumn: PropTypes.func.isRequired,
onDrop: PropTypes.func.isRequired
};
ColumnList.defaultProps = {
hiddenColumns: [],
};
export default WithDragDropContext(ColumnList);
|
demo/src/index.js | joshwcomeau/react-collection-helpers | import React from 'react';
import { render } from 'react-dom';
import App from './components/App';
const Demo = () => <App />;
// eslint-disable-next-line no-undef
render(<Demo />, document.querySelector('#demo'));
|
ajax/libs/muicss/0.4.9/react/mui-react.min.js | Amomo/cdnjs | !function(e){var t=e.babelHelpers={};t["typeof"]="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},t.jsx=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,r,n,l){var o=t&&t.defaultProps,s=arguments.length-3;if(r||0===s||(r={}),r&&o)for(var a in o)void 0===r[a]&&(r[a]=o[a]);else r||(r=o||{});if(1===s)r.children=l;else if(s>1){for(var i=Array(s),u=0;s>u;u++)i[u]=arguments[u+3];r.children=i}return{$$typeof:e,type:t,key:void 0===n?null:""+n,ref:null,props:r,_owner:null}}}(),t.asyncToGenerator=function(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,r){function n(l,o){try{var s=t[l](o),a=s.value}catch(i){return void r(i)}return s.done?void e(a):Promise.resolve(a).then(function(e){return n("next",e)},function(e){return n("throw",e)})}return n("next")})}},t.classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),t.defineEnumerableProperties=function(e,t){for(var r in t){var n=t[r];n.configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,r,n)}return e},t.defaults=function(e,t){for(var r=Object.getOwnPropertyNames(t),n=0;n<r.length;n++){var l=r[n],o=Object.getOwnPropertyDescriptor(t,l);o&&o.configurable&&void 0===e[l]&&Object.defineProperty(e,l,o)}return e},t.defineProperty=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},t["extends"]=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.get=function r(e,t,n){null===e&&(e=Function.prototype);var l=Object.getOwnPropertyDescriptor(e,t);if(void 0===l){var o=Object.getPrototypeOf(e);return null===o?void 0:r(o,t,n)}if("value"in l)return l.value;var s=l.get;if(void 0!==s)return s.call(n)},t.inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},t["instanceof"]=function(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?t[Symbol.hasInstance](e):e instanceof t},t.interopRequireDefault=function(e){return e&&e.__esModule?e:{"default":e}},t.interopRequireWildcard=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t},t.newArrowCheck=function(e,t){if(e!==t)throw new TypeError("Cannot instantiate an arrow function")},t.objectDestructuringEmpty=function(e){if(null==e)throw new TypeError("Cannot destructure undefined")},t.objectWithoutProperties=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r},t.possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},t.selfGlobal="undefined"==typeof e?self:e,t.set=function n(e,t,r,l){var o=Object.getOwnPropertyDescriptor(e,t);if(void 0===o){var s=Object.getPrototypeOf(e);null!==s&&n(s,t,r,l)}else if("value"in o&&o.writable)o.value=r;else{var a=o.set;void 0!==a&&a.call(l,r)}return r},t.slicedToArray=function(){function e(e,t){var r=[],n=!0,l=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(i){l=!0,o=i}finally{try{!n&&a["return"]&&a["return"]()}finally{if(l)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),t.slicedToArrayLoose=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e)){for(var r,n=[],l=e[Symbol.iterator]();!(r=l.next()).done&&(n.push(r.value),!t||n.length!==t););return n}throw new TypeError("Invalid attempt to destructure non-iterable instance")},t.taggedTemplateLiteral=function(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))},t.taggedTemplateLiteralLoose=function(e,t){return e.raw=t,e},t.temporalRef=function(e,t,r){if(e===r)throw new ReferenceError(t+" is not defined - temporal dead zone");return e},t.temporalUndefined={},t.toArray=function(e){return Array.isArray(e)?e:Array.from(e)},t.toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}}("undefined"==typeof global?self:global),function e(t,r,n){function l(s,a){if(!r[s]){if(!t[s]){var i="function"==typeof require&&require;if(!a&&i)return i(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=r[s]={exports:{}};t[s][0].call(u.exports,function(e){var r=t[s][1][e];return l(r?r:e)},u,u.exports,e,t,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s<n.length;s++)l(n[s]);return l}({1:[function(e,t,r){"use strict";!function(t){if(!t._muiReactLoaded){t._muiReactLoaded=!0;var r=t.mui=t.mui||[],n=r.react={};n.Appbar=e("src/react/appbar"),n.Button=e("src/react/button"),n.Caret=e("src/react/caret"),n.Checkbox=e("src/react/checkbox"),n.Col=e("src/react/col"),n.Container=e("src/react/container"),n.Divider=e("src/react/divider"),n.Dropdown=e("src/react/dropdown"),n.DropdownItem=e("src/react/dropdown-item"),n.Form=e("src/react/form"),n.Input=e("src/react/input"),n.Option=e("src/react/option"),n.Panel=e("src/react/panel"),n.Radio=e("src/react/radio"),n.Row=e("src/react/row"),n.Select=e("src/react/select"),n.Tab=e("src/react/tab"),n.Tabs=e("src/react/tabs"),n.Textarea=e("src/react/textarea")}}(window)},{"src/react/appbar":11,"src/react/button":12,"src/react/caret":13,"src/react/checkbox":14,"src/react/col":15,"src/react/container":16,"src/react/divider":17,"src/react/dropdown":19,"src/react/dropdown-item":18,"src/react/form":20,"src/react/input":21,"src/react/option":22,"src/react/panel":23,"src/react/radio":24,"src/react/row":25,"src/react/select":26,"src/react/tab":27,"src/react/tabs":28,"src/react/textarea":29}],2:[function(e,t,r){"use strict";t.exports={debug:!0}},{}],3:[function(e,t,r){"use strict";function n(e,t,r){var n,i,u,c,p=document.documentElement.clientHeight,d=t*s+2*a,f=Math.min(d,p);i=a+s-(l+o),i-=r*s,u=-1*e.getBoundingClientRect().top,c=p-f+u,n=Math.min(Math.max(i,u),c);var b,h,v=0;return d>p&&(b=a+(r+1)*s-(-1*n+l+o),h=t*s+2*a-f,v=Math.min(b,h)),{height:f+"px",top:n+"px",scrollTop:v}}var l=15,o=32,s=42,a=8;t.exports={getMenuPositionalCSS:n}},{}],4:[function(e,t,r){"use strict";function n(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)r=l[o].trim(),-1===n.indexOf(" "+r+" ")&&(n+=r+" ");e.setAttribute("class",n.trim())}}function l(e,t,r){if(void 0===t)return getComputedStyle(e);var n=s(t);{if("object"!==n){"string"===n&&void 0!==r&&(e.style[v(t)]=r);var l=getComputedStyle(e),o="array"===s(t);if(!o)return y(e,t,l);for(var a,i={},u=0;u<t.length;u++)a=t[u],i[a]=y(e,a,l);return i}for(var a in t)e.style[v(a)]=t[a]}}function o(e,t){return t&&e.getAttribute?h(e).indexOf(" "+t+" ")>-1:!1}function s(e){if(void 0===e)return"undefined";var t=Object.prototype.toString.call(e);if(0===t.indexOf("[object "))return t.slice(8,-1).toLowerCase();throw new Error("MUI: Could not understand type: "+t)}function a(e,t,r,n){n=void 0===n?!1:n,e.addEventListener(t,r,n);var l=e._muiEventCache=e._muiEventCache||{};l[t]=l[t]||[],l[t].push([r,n])}function i(e,t,r,n){n=void 0===n?!1:n;var l,o,s=e._muiEventCache=e._muiEventCache||{},a=s[t]||[];for(o=a.length;o--;)l=a[o],(void 0===r||l[0]===r&&l[1]===n)&&(a.splice(o,1),e.removeEventListener(t,l[0],l[1]))}function u(e,t,r,n){a(e,t,function l(n){r&&r.apply(this,arguments),i(e,t,l)},n)}function c(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}return e.scrollLeft}e===r?r.scrollTo(t,p(r)):e.scrollLeft=t}function p(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageYOffset||n.scrollTop)-(n.clientTop||0)}return e.scrollTop}e===r?r.scrollTo(c(r),t):e.scrollTop=t}function d(e){var t=window,r=e.getBoundingClientRect(),n=p(t),l=c(t);return{top:r.top+n,left:r.left+l,height:r.height,width:r.width}}function f(e){var t=!1,r=!0,n=document,l=n.defaultView,o=n.documentElement,s=n.addEventListener?"addEventListener":"attachEvent",a=n.addEventListener?"removeEventListener":"detachEvent",i=n.addEventListener?"":"on",u=function d(r){"readystatechange"==r.type&&"complete"!=n.readyState||(("load"==r.type?l:n)[a](i+r.type,d,!1),!t&&(t=!0)&&e.call(l,r.type||r))},c=function f(){try{o.doScroll("left")}catch(e){return void setTimeout(f,50)}u("poll")};if("complete"==n.readyState)e.call(l,"lazy");else{if(n.createEventObject&&o.doScroll){try{r=!l.frameElement}catch(p){}r&&c()}n[s](i+"DOMContentLoaded",u,!1),n[s](i+"readystatechange",u,!1),l[s](i+"load",u,!1)}}function b(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)for(r=l[o].trim();n.indexOf(" "+r+" ")>=0;)n=n.replace(" "+r+" "," ");e.setAttribute("class",n.trim())}}function h(e){var t=(e.getAttribute("class")||"").replace(/[\n\t]/g,"");return" "+t+" "}function v(e){return e.replace(C,function(e,t,r,n){return n?r.toUpperCase():r}).replace(g,"Moz$1")}function y(e,t,r){var n;return n=r.getPropertyValue(t),""!==n||e.ownerDocument||(n=e.style[v(t)]),n}var m,C=/([\:\-\_]+(.))/g,g=/^moz([A-Z])/;m={multiple:!0,selected:!0,checked:!0,disabled:!0,readonly:!0,required:!0,open:!0},t.exports={addClass:n,css:l,hasClass:o,off:i,offset:d,on:a,one:u,ready:f,removeClass:b,type:s,scrollLeft:c,scrollTop:p}},{}],5:[function(e,t,r){"use strict";function n(){var e=window;if(v.debug&&"undefined"!=typeof e.console)try{e.console.log.apply(e.console,arguments)}catch(t){var r=Array.prototype.slice.call(arguments);e.console.log(r.join("\n"))}}function l(e){var t,r=document;t=r.head||r.getElementsByTagName("head")[0]||r.documentElement;var n=r.createElement("style");return n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(r.createTextNode(e)),t.insertBefore(n,t.firstChild),n}function o(e,t){if(!t)throw new Error("MUI: "+e);"undefined"!=typeof console&&console.error("MUI Warning: "+e)}function s(e){if(m.push(e),void 0===m._initialized){var t=document;y.on(t,"animationstart",a),y.on(t,"mozAnimationStart",a),y.on(t,"webkitAnimationStart",a),m._initialized=!0}}function a(e){if("mui-node-inserted"===e.animationName)for(var t=e.target,r=m.length-1;r>=0;r--)m[r](t)}function i(e){var t="";for(var r in e)t+=e[r]?r+" ":"";return t.trim()}function u(){if(void 0!==h)return h;var e=document.createElement("x");return e.style.cssText="pointer-events:auto",h="auto"===e.style.pointerEvents}function c(e,t){return function(){e[t].apply(e,arguments)}}function p(e,t,r,n,l){var o,s=document.createEvent("HTMLEvents"),r=void 0!==r?r:!0,n=void 0!==n?n:!0;if(s.initEvent(t,r,n),l)for(o in l)s[o]=l[o];return e&&e.dispatchEvent(s),s}function d(){if(C+=1,1===C){var e=window,t=document;b={left:y.scrollLeft(e),top:y.scrollTop(e)},y.addClass(t.body,g),e.scrollTo(b.left,b.top)}}function f(){if(0!==C&&(C-=1,0===C)){var e=window,t=document;y.removeClass(t.body,g),e.scrollTo(b.left,b.top)}}var b,h,v=e("../config"),y=e("./jqLite"),m=[],C=0,g="mui-body--scroll-lock";t.exports={callback:c,classNames:i,disableScrollLock:f,dispatchEvent:p,enableScrollLock:d,log:n,loadStyle:l,onNodeInserted:s,raiseError:o,supportsPointerEvents:u}},{"../config":2,"./jqLite":4}],6:[function(e,t,r){"use strict";var n="You provided a `value` prop to a form field without an `OnChange` handler. Please see React documentation on controlled components";t.exports={controlledMessage:n}},{}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/jqLite"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/util"),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u="mui-btn",c="mui-ripple-effect",p={color:1,variant:1,size:1},d=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={ripples:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this.refs.buttonEl;e._muiDropdown=!0,e._muiRipple=!0}},{key:"onClick",value:function(e){var t=this.props.onClick;t&&t(e)}},{key:"onMouseDown",value:function(e){var t=s.offset(this.refs.buttonEl),r=t.height;"fab"===this.props.variant&&(r/=2);var n=this.state.ripples,l=Date.now();n[l]={xPos:e.pageX-t.left,yPos:e.pageY-t.top,diameter:r,teardownFn:this.teardownRipple.bind(this,l)},this.setState({ripples:n})}},{key:"onTouchStart",value:function(e){}},{key:"teardownRipple",value:function(e){var t=this.state.ripples;delete t[e],this.setState({ripples:t})}},{key:"render",value:function(){var e=u,t=void 0,r=void 0,n=this.state.ripples;for(t in p)r=this.props[t],"default"!==r&&(e+=" "+u+"--"+r);return l["default"].createElement("button",babelHelpers["extends"]({},this.props,{ref:"buttonEl",className:e+" "+this.props.className,onClick:this.onClick.bind(this),onMouseDown:this.onMouseDown.bind(this)}),this.props.children,Object.keys(n).map(function(e,t){var r=n[e];return l["default"].createElement(f,{key:e,xPos:r.xPos,yPos:r.yPos,diameter:r.diameter,onTeardown:r.teardownFn})}))}}]),t}(l["default"].Component);d.propTypes={color:i.oneOf(["default","primary","danger","dark","accent"]),disabled:i.bool,size:i.oneOf(["default","small","large"]),type:i.oneOf(["submit","button"]),variant:i.oneOf(["default","flat","raised","fab"]),onClick:i.func},d.defaultProps={className:"",color:"default",disabled:!1,size:"default",type:null,variant:"default",onClick:null};var f=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this,t=setTimeout(function(){var t=e.props.onTeardown;t&&t()},2e3);this.setState({teardownTimer:t})}},{key:"componentWillUnmount",value:function(){clearTimeout(this.state.teardownTimer)}},{key:"render",value:function(){var e=this.props.diameter,t=e/2,r={height:e,width:e,top:this.props.yPos-t||0,left:this.props.xPos-t||0};return l["default"].createElement("div",{className:c,style:r})}}]),t}(l["default"].Component);f.propTypes={xPos:i.number,yPos:i.number,diameter:i.number,onTeardown:i.func},f.defaultProps={xPos:0,yPos:0,diameter:0,onTeardown:null},r["default"]=d,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("span",babelHelpers["extends"]({},t,{className:"mui-caret "+this.props.className}))}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return null}}]),t}(l["default"].Component);s.propTypes={value:o.any,label:o.string,onActive:o.func},s.defaultProps={value:null,label:"",onActive:null},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TextField=void 0;var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=e("./_helpers"),i=l["default"].PropTypes,u=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e)),n=e.value,l=n||e.defaultValue;r.state={innerValue:l,isDirty:Boolean(l)},null!==n&&null===e.onChange&&s.raiseError(a.controlledMessage,!0);var o=s.callback;return r.onChangeCB=o(r,"onChange"),r.onFocusCB=o(r,"onFocus"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.inputEl._muiTextfield=!0}},{key:"onChange",value:function(e){this.setState({innerValue:e.target.value});var t=this.props.onChange;t&&t(e)}},{key:"onFocus",value:function(e){this.setState({isDirty:!0})}},{key:"triggerFocus",value:function(){this.refs.inputEl.focus()}},{key:"render",value:function(){var e={},t=Boolean(this.state.innerValue),r=void 0;e["mui--is-empty"]=!t,e["mui--is-not-empty"]=t,e["mui--is-dirty"]=this.state.isDirty,e["mui--is-invalid"]=this.props.invalid,e=s.classNames(e);var n=this.props,o=(n.children,babelHelpers.objectWithoutProperties(n,["children"]));return r="textarea"===this.props.type?l["default"].createElement("textarea",babelHelpers["extends"]({},o,{ref:"inputEl",className:e,rows:this.props.rows,placeholder:this.props.hint,value:this.props.value,defaultValue:this.props.defaultValue,autoFocus:this.props.autoFocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required})):l["default"].createElement("input",babelHelpers["extends"]({},o,{ref:"inputEl",className:e,type:this.props.type,value:this.props.value,defaultValue:this.props.defaultValue,placeholder:this.props.hint,autoFocus:this.props.autofocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required}))}}]),t}(l["default"].Component);u.propTypes={hint:i.string,value:i.string,type:i.string,autoFocus:i.bool,onChange:i.func},u.defaultProps={hint:null,type:null,value:null,autoFocus:!1,onChange:null};var c=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={style:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this;setTimeout(function(){var t=".15s ease-out",r=void 0;r={transition:t,WebkitTransition:t,MozTransition:t,OTransition:t,msTransform:t},e.setState({style:r})},150)}},{key:"render",value:function(){return l["default"].createElement("label",{style:this.state.style,onClick:this.props.onClick},this.props.text)}}]),t}(l["default"].Component);c.defaultProps={text:"",onClick:null};var p=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){s.supportsPointerEvents()===!1&&(e.target.style.cursor="text",this.refs.inputEl.triggerFocus())}},{key:"render",value:function(){var e={},t=void 0;return this.props.label.length&&(t=l["default"].createElement(c,{text:this.props.label,onClick:this.onClickCB})),e["mui-textfield"]=!0,e["mui-textfield--float-label"]=this.props.floatingLabel,e=s.classNames(e),l["default"].createElement("div",{className:e},l["default"].createElement(u,babelHelpers["extends"]({ref:"inputEl"},this.props)),t)}}]),t}(l["default"].Component);p.propTypes={label:i.string,floatingLabel:i.bool},p.defaultProps={label:"",floatingLabel:!1},r.TextField=p},{"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-appbar "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],12:[function(e,t,r){t.exports=e(7)},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],13:[function(e,t,r){t.exports=e(8)},{react:"CwoHg3"}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=(babelHelpers.interopRequireWildcard(o),e("./_helpers"),l["default"].PropTypes),a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-checkbox "+this.props.className}),l["default"].createElement("label",null,l["default"].createElement("input",{ref:"inputEl",type:"checkbox",name:this.props.name,value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled,onChange:this.props.onChange}),this.props.label))}}]),t}(l["default"].Component);a.propTypes={name:s.string,label:s.string,value:s.string,checked:s.bool,defaultChecked:s.bool,disabled:s.bool,onChange:s.func},a.defaultProps={className:"",name:null,label:null,value:null,checked:null,defaultChecked:null,disabled:!1,onChange:null},r["default"]=a,t.exports=r["default"]},{"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=["xs","sm","md","lg","xl"],i=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"defaultProps",value:function(){var e={className:""},t=void 0,r=void 0;for(t=a.length-1;t>-1;t--)r=a[t],e[r]=null,e[r+"-offset"]=null;return e}},{key:"render",value:function(){var e={},t=void 0,r=void 0,n=void 0,o=void 0;for(t=a.length-1;t>-1;t--)r=a[t],o="mui-col-"+r,n=this.props[r],n&&(e[o+"-"+n]=!0),n=this.props[r+"-offset"],n&&(e[o+"-offset-"+n]=!0);return e=s.classNames(e),l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="mui-container";return this.props.fluid&&(e+="-fluid"),l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.propTypes={fluid:l["default"].PropTypes.bool},o.defaultProps={className:"",fluid:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],17:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-divider "+this.props.className}))}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=l["default"].PropTypes,i=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){this.props.onClick&&this.props.onClick(this,e)}},{key:"render",value:function(){var e=this.props,t=e.children,r=(e.onClick,babelHelpers.objectWithoutProperties(e,["children","onClick"]));return l["default"].createElement("li",r,l["default"].createElement("a",{href:this.props.link,"data-mui-value":this.props.value,onClick:this.onClickCB},t))}}]),t}(l["default"].Component);i.propTypes={link:a.string,onClick:a.func},i.defaultProps={link:null,value:null,onClick:null},r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./button"),s=babelHelpers.interopRequireDefault(o),a=e("./caret"),i=babelHelpers.interopRequireDefault(a),u=e("../js/lib/jqLite"),c=babelHelpers.interopRequireWildcard(u),p=e("../js/lib/util"),d=babelHelpers.interopRequireWildcard(p),f=l["default"].PropTypes,b="mui-dropdown",h="mui-dropdown__menu",v="mui--is-open",y="mui-dropdown__menu--right",m=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={opened:!1,menuTop:0};var n=d.callback;return r.selectCB=n(r,"select"),r.onClickCB=n(r,"onClick"),r.onOutsideClickCB=n(r,"onOutsideClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){document.addEventListener("click",this.onOutsideClickCB)}},{key:"componentWillUnmount",value:function(){document.removeEventListener("click",this.onOutsideClickCB)}},{key:"onClick",value:function(e){if(0===e.button&&!this.props.disabled&&!e.defaultPrevented){this.toggle();var t=this.props.onClick;t&&t(e)}}},{key:"toggle",value:function(){return this.props.children?void(this.state.opened?this.close():this.open()):d.raiseError("Dropdown menu element not found")}},{key:"open",value:function(){var e=this.refs.wrapperEl.getBoundingClientRect(),t=void 0;t=this.refs.button.refs.buttonEl.getBoundingClientRect(),this.setState({opened:!0,menuTop:t.top-e.top+t.height})}},{key:"close",value:function(){this.setState({opened:!1})}},{key:"select",value:function(e){this.props.onSelect&&"A"===e.target.tagName&&this.props.onSelect(e.target.getAttribute("data-mui-value")),e.defaultPrevented||this.close()}},{key:"onOutsideClick",value:function(e){var t=this.refs.wrapperEl.contains(e.target);t||this.close()}},{key:"render",value:function(){var e=void 0,t=void 0,r=void 0;if(r="string"===c.type(this.props.label)?l["default"].createElement("span",null,this.props.label," ",l["default"].createElement(i["default"],null)):this.props.label,e=l["default"].createElement(s["default"],{ref:"button",type:"button",onClick:this.onClickCB,color:this.props.color,variant:this.props.variant,size:this.props.size,disabled:this.props.disabled},r),this.state.opened){var n={};n[h]=!0,n[v]=this.state.opened,n[y]="right"===this.props.alignMenu,n=d.classNames(n),t=l["default"].createElement("ul",{ref:"menuEl",className:n,style:{top:this.state.menuTop},onClick:this.selectCB},this.props.children)}var o=this.props,a=(o.ref,o.className),u=(o.children,o.onClick,babelHelpers.objectWithoutProperties(o,["ref","className","children","onClick"]));return l["default"].createElement("div",babelHelpers["extends"]({},u,{ref:"wrapperEl",className:b+" "+a}),e,t)}}]),t}(l["default"].Component);m.propTypes={color:f.oneOf(["default","primary","danger","dark","accent"]),variant:f.oneOf(["default","flat","raised","fab"]),size:f.oneOf(["default","small","large"]),label:f.oneOfType([f.string,f.element]),alignMenu:f.oneOf(["left","right"]),onClick:f.func,onSelect:f.func,disabled:f.bool},m.defaultProps={className:"",color:"default",variant:"default",size:"default",label:"",alignMenu:"left",onClick:null,onSelect:null,disabled:!1},r["default"]=m,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,"./button":7,"./caret":8,react:"CwoHg3"}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="";return this.props.inline&&(e="mui-form--inline"),l["default"].createElement("form",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.propTypes={inline:l["default"].PropTypes.bool},o.defaultProps={className:"",inline:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./text-field"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={type:s.oneOf(["text","email","url","tel","password"])},a.defaultProps={type:"text"},r["default"]=a,t.exports=r["default"]},{"./text-field":10,react:"CwoHg3"}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=(babelHelpers.interopRequireWildcard(o),e("../js/lib/jqLite")),a=(babelHelpers.interopRequireWildcard(s),e("../js/lib/util")),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments));
}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("option",babelHelpers["extends"]({},t,{value:this.props.value}),this.props.label)}}]),t}(l["default"].Component);u.propTypes={value:i.string,label:i.string},u.defaultProps={value:null,label:null},r["default"]=u,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-panel "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],24:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-radio "+this.props.className}),l["default"].createElement("label",null,l["default"].createElement("input",{ref:"inputEl",type:"radio",name:this.props.name,value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled,onChange:this.props.onChange}),this.props.label))}}]),t}(l["default"].Component);s.propTypes={name:o.string,label:o.string,value:o.string,checked:o.bool,defaultChecked:o.bool,disabled:o.bool,onChange:o.func},s.defaultProps={className:"",name:null,label:null,value:null,checked:null,defaultChecked:null,disabled:!1,onChange:null},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=(babelHelpers.interopRequireWildcard(o),function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-row "+this.props.className}),this.props.children)}}]),t}(l["default"].Component));s.defaultProps={className:""},r["default"]=s,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],26:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/jqLite"),i=babelHelpers.interopRequireWildcard(a),u=e("../js/lib/util"),c=babelHelpers.interopRequireWildcard(u),p=e("./_helpers"),d=l["default"].PropTypes,f=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={value:null,showMenu:!1},e.readOnly===!1&&null!==e.value&&null===e.onChange&&c.raiseError(p.controlledMessage,!0),r.state.value=e.value;var n=c.callback;return r.hideMenuCB=n(r,"hideMenu"),r.onInnerChangeCB=n(r,"onInnerChange"),r.onInnerClickCB=n(r,"onInnerClick"),r.onInnerFocusCB=n(r,"onInnerFocus"),r.onInnerMouseDownCB=n(r,"onInnerMouseDown"),r.onKeydownCB=n(r,"onKeydown"),r.onMenuChangeCB=n(r,"onMenuChange"),r.onOuterFocusCB=n(r,"onOuterFocus"),r.onOuterBlurCB=n(r,"onOuterBlur"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.selectEl._muiSelect=!0,this.refs.wrapperEl.tabIndex=-1,this.props.autoFocus&&this.refs.wrapperEl.focus()}},{key:"componentWillReceiveProps",value:function(e){this.setState({value:e.value})}},{key:"onInnerMouseDown",value:function(e){0===e.button&&this.props.useDefault!==!0&&e.preventDefault()}},{key:"onInnerChange",value:function(e){var t=e.target.value;this.setState({value:t});var r=this.props.onChange;r&&r(t)}},{key:"onInnerClick",value:function(e){0===e.button&&this.showMenu()}},{key:"onInnerFocus",value:function(e){var t=this;this.props.useDefault!==!0&&setTimeout(function(){t.refs.wrapperEl.focus()},0)}},{key:"onOuterFocus",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;return t._muiOrigIndex=t.tabIndex,t.tabIndex=-1,t.disabled?this.refs.wrapperEl.blur():void i.on(document,"keydown",this.onKeydownCB)}}},{key:"onOuterBlur",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;t.tabIndex=t._muiOrigIndex,i.off(document,"keydown",this.onKeydownCB)}}},{key:"onKeydown",value:function(e){32!==e.keyCode&&38!==e.keyCode&&40!==e.keyCode||(e.preventDefault(),this.refs.selectEl.disabled!==!0&&this.showMenu())}},{key:"showMenu",value:function(){this.props.useDefault!==!0&&(c.enableScrollLock(),i.on(window,"resize",this.hideMenuCB),i.on(document,"click",this.hideMenuCB),this.setState({showMenu:!0}))}},{key:"hideMenu",value:function(){c.disableScrollLock(),i.off(window,"resize",this.hideMenuCB),i.off(document,"click",this.hideMenuCB),this.setState({showMenu:!1}),this.refs.selectEl.focus()}},{key:"onMenuChange",value:function(e){if(this.props.readOnly!==!0){this.setState({value:e});var t=this.props.onChange;t&&t(e)}}},{key:"render",value:function(){var e=void 0;this.state.showMenu&&(e=l["default"].createElement(b,{optionEls:this.refs.selectEl.children,wrapperEl:this.refs.wrapperEl,onChange:this.onMenuChangeCB,onClose:this.hideMenuCB}));var t=this.props,r=(t.children,t.onChange,babelHelpers.objectWithoutProperties(t,["children","onChange"]));return l["default"].createElement("div",babelHelpers["extends"]({},r,{ref:"wrapperEl",className:"mui-select "+this.props.className,onFocus:this.onOuterFocusCB,onBlur:this.onOuterBlurCB}),l["default"].createElement("select",{ref:"selectEl",name:this.props.name,value:this.state.value,defaultValue:this.props.defaultValue,disabled:this.props.disabled,multiple:this.props.multiple,readOnly:this.props.readOnly,required:this.props.required,onChange:this.onInnerChangeCB,onMouseDown:this.onInnerMouseDownCB,onClick:this.onInnerClickCB,onFocus:this.onInnerFocusCB},this.props.children),e)}}]),t}(l["default"].Component);f.propTypes={name:d.string,value:d.string,defaultValue:d.string,autoFocus:d.bool,disabled:d.bool,multiple:d.bool,readOnly:d.bool,required:d.bool,useDefault:d.bool,onChange:d.func},f.defaultProps={className:"",name:null,value:null,defaultValue:null,autoFocus:!1,disabled:!1,multiple:!1,readOnly:!1,required:!1,useDefault:!1,onChange:null};var b=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={origIndex:null,currentIndex:null},r.onKeydownCB=c.callback(r,"onKeydown"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){var e=this.props.optionEls,t=e.length,r=0,n=void 0;for(n=t-1;n>-1;n--)e[n].selected&&(r=n);this.setState({origIndex:r,currentIndex:r})}},{key:"componentDidMount",value:function(){setTimeout(function(){var e=document.activeElement;"body"!==e.nodeName.toLowerCase()&&e.blur()},0);var e=s.getMenuPositionalCSS(this.props.wrapperEl,this.props.optionEls.length,this.state.currentIndex),t=this.refs.wrapperEl;i.css(t,e),i.scrollTop(t,e.scrollTop),i.on(document,"keydown",this.onKeydownCB)}},{key:"componentWillUnmount",value:function(){i.off(document,"keydown",this.onKeydownCB)}},{key:"onClick",value:function(e,t){t.stopPropagation(),this.selectAndDestroy(e)}},{key:"onKeydown",value:function(e){var t=e.keyCode;return 9===t?this.destroy():(27!==t&&40!==t&&38!==t&&13!==t||e.preventDefault(),void(27===t?this.destroy():40===t?this.increment():38===t?this.decrement():13===t&&this.selectAndDestroy()))}},{key:"increment",value:function(){this.state.currentIndex!==this.props.optionEls.length-1&&this.setState({currentIndex:this.state.currentIndex+1})}},{key:"decrement",value:function(){0!==this.state.currentIndex&&this.setState({currentIndex:this.state.currentIndex-1})}},{key:"selectAndDestroy",value:function(e){e=void 0===e?this.state.currentIndex:e,e!==this.state.origIndex&&this.props.onChange(this.props.optionEls[e].value),this.destroy()}},{key:"destroy",value:function(){this.props.onClose()}},{key:"render",value:function(){var e=[],t=this.props.optionEls,r=t.length,n=void 0,o=void 0;for(o=0;r>o;o++)n=o===this.state.currentIndex?"mui--is-selected":"",e.push(l["default"].createElement("div",{key:o,className:n,onClick:this.onClick.bind(this,o)},t[o].textContent));return l["default"].createElement("div",{ref:"wrapperEl",className:"mui-select__menu"},e)}}]),t}(l["default"].Component);b.defaultProps={optionEls:[],wrapperEl:null,onChange:null,onClose:null},r["default"]=f,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],27:[function(e,t,r){t.exports=e(9)},{react:"CwoHg3"}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./tab"),s=babelHelpers.interopRequireDefault(o),a=e("../js/lib/util"),i=babelHelpers.interopRequireWildcard(a),u=l["default"].PropTypes,c="mui-tabs__bar",p="mui-tabs__bar--justified",d="mui-tabs__pane",f="mui--is-active",b=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={currentSelectedIndex:e.initialSelectedIndex},r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e,t,r){e!==this.state.currentSelectedIndex&&(this.setState({currentSelectedIndex:e}),t.props.onActive&&t.props.onActive(t),this.props.onChange&&this.props.onChange(e,t.props.value,t,r))}},{key:"render",value:function(){var e=this.props,t=e.children,r=babelHelpers.objectWithoutProperties(e,["children"]),n=[],o=[],a=t.length,u=this.state.currentSelectedIndex%a,b=void 0,h=void 0,v=void 0,y=void 0;for(y=0;a>y;y++)h=t[y],h.type!==s["default"]&&i.raiseError("Expecting MUITab React Element"),b=y===u,n.push(l["default"].createElement("li",{key:y,className:b?f:""},l["default"].createElement("a",{onClick:this.onClick.bind(this,y,h)},h.props.label))),v=d+" ",b&&(v+=f),o.push(l["default"].createElement("div",{key:y,className:v},h.props.children));return v=c,this.props.justified&&(v+=" "+p),l["default"].createElement("div",r,l["default"].createElement("ul",{className:v},n),o)}}]),t}(l["default"].Component);b.propTypes={initialSelectedIndex:u.number,justified:u.bool,onChange:u.func},b.defaultProps={className:"",initialSelectedIndex:0,justified:!1,onChange:null},r["default"]=b,t.exports=r["default"]},{"../js/lib/util":5,"./tab":9,react:"CwoHg3"}],29:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./text-field"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={rows:s.number},a.defaultProps={type:"textarea",rows:2},r["default"]=a,t.exports=r["default"]},{"./text-field":10,react:"CwoHg3"}]},{},[1]); |
src/routes/Counter/components/Counter.js | dima-bu/b2b.core | import React from 'react';
export const Counter = (props) => (
<div style={{margin: '0 auto'}} >
<h2>Counter: {props.counter}</h2>
<button className='btn btn-default' onClick={props.increment}>
Increment
</button>
{' '}
<button className='btn btn-default' onClick={props.doubleAsync}>
Double (Async)
</button>
</div>
);
Counter.propTypes = {
counter : React.PropTypes.number.isRequired,
doubleAsync : React.PropTypes.func.isRequired,
increment : React.PropTypes.func.isRequired
};
export default Counter;
|
examples/todo/js/components/TodoApp.js | michaelchum/relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* 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
* FACEBOOK 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.
*/
import AddTodoMutation from '../mutations/AddTodoMutation';
import TodoListFooter from './TodoListFooter';
import TodoTextInput from './TodoTextInput';
import React from 'react';
import Relay from 'react-relay';
class TodoApp extends React.Component {
_handleTextInputSave = (text) => {
Relay.Store.commitUpdate(
new AddTodoMutation({text, viewer: this.props.viewer})
);
}
render() {
var hasTodos = this.props.viewer.totalCount > 0;
return (
<div>
<section className="todoapp">
<header className="header">
<h1>
todos
</h1>
<TodoTextInput
autoFocus={true}
className="new-todo"
onSave={this._handleTextInputSave}
placeholder="What needs to be done?"
/>
</header>
{this.props.children}
{hasTodos &&
<TodoListFooter
todos={this.props.viewer.todos}
viewer={this.props.viewer}
/>
}
</section>
<footer className="info">
<p>
Double-click to edit a todo
</p>
<p>
Created by the <a href="https://facebook.github.io/relay/">
Relay team
</a>
</p>
<p>
Part of <a href="http://todomvc.com">TodoMVC</a>
</p>
</footer>
</div>
);
}
}
export default Relay.createContainer(TodoApp, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
totalCount,
${AddTodoMutation.getFragment('viewer')},
${TodoListFooter.getFragment('viewer')},
}
`,
},
});
|
app/assets/scripts/components/results-panel.js | worldbank-cdrp/disaster-risk-explorer | import React from 'react'
import multiDownload from 'multi-download'
import { showModalCalc, newCalcId } from '../actions'
import { graphCols, calcDropItems } from '../constants'
import { getMapId } from '../utils/map-id'
import { shortenNumber } from '../utils/format'
import { t } from '../utils/i18n'
import c from 'classnames'
import BarChart from './charts/bar-chart'
const Results = React.createClass({
propTypes: {
dispatch: React.PropTypes.func,
dataSelection: React.PropTypes.object,
queryParams: React.PropTypes.object,
data: React.PropTypes.object,
mapType: React.PropTypes.string
},
deleteThis: function () {
return (
<section className='results'>
</section>
)
},
render: function () {
let d = this.props.data
if (d === null) {
return this.deleteThis()
}
let adminName
d.id.length === 2
? adminName = t(d.id)
: adminName = `${t(d.id)}, ${t(d.id.substring(0, 2))}`
const risk = this.props.dataSelection.risk.getActive().value
const metric = this.props.dataSelection.metric.getActive().key
const admin = this.props.dataSelection.admin.getActive().key
const mapType = this.props.mapType
let yTitle = t('Billions (US$)')
let xTitle = t('Return Period')
let valDenominator = 1000000000
if (admin === 'admin1') {
yTitle = t('Millions (US$)')
valDenominator = 1000000
}
if (mapType === 'relative') {
yTitle = t('US Dollars ($)')
valDenominator = 1
}
const rps = graphCols[getMapId(this.props.dataSelection).slice(0, 5)]
const suffix = mapType === 'relative' && metric === 'loss' ? '_R' : ''
let data
if (rps) {
data = rps.map((rp) => {
const value = d[`LS_${risk}_${rp}${suffix}`] ? d[`LS_${risk}_${rp}${suffix}`] : 0
return {value: Number((value / valDenominator).toFixed(2)), name: rp}
})
}
let margin = {
top: 16,
left: 50,
right: 16,
bottom: 56
}
var hasData = false
var countryActive = d.id.substring(0, 2)
var calcButtonLabel = 'No building data for this region'
calcDropItems.countryName.forEach(o => {
if (o.key === d.id) {
hasData = true
}
})
calcDropItems.districtName[countryActive].forEach(o => {
if (o.key === d.id) {
hasData = true
}
})
if (hasData) {
calcButtonLabel = 'Launch cost and benefit calculator'
}
const barChartInfo = () => {
return (
<div>
<div className='results__divider results__divider--first'></div>
<h3 className='subtitle results__subtitle results__subtitle--secondary'>{t('loss')}</h3>
<dl className='stats'>
<div>
<dt className='stat__attribute'>{t('Average Annual Loss')}</dt>
<dd className='stat__value'>
{isNaN(d[`LS_${risk}_AAL`]) ? 'data unavailable' : '$' + shortenNumber(d[`LS_${risk}_AAL`], 2, false)}
</dd>
</div>
<dd className='stat__value stat__value--chart stat__value--last'>
<BarChart
data={data}
margin={margin}
yTitle={yTitle}
xTitle={xTitle}
/>
</dd>
</dl>
</div>
)
}
const placeholder = () => {
return <div className='results__placeholder'></div>
}
return (
<div>
<section className='results'>
<div className='results__space'>
<h2 className='results__title'>{adminName}</h2>
<div className='results__container'>
<h3 className='subtitle results__subtitle'>{t('Exposure')}</h3>
<dl className='stats'>
<dt className='stat__attribute'>{t('GDP')}</dt>
<dd className='stat__value'>$ {!d.EX_GD ? ' -' : shortenNumber(d.EX_GD, 2, false)}</dd>
<dt className='stat__attribute'>{t('Building Stock Exposure')}</dt>
<dd className='stat__value'>$ {!d.EX_BS ? ' -' : shortenNumber(d.EX_BS, 2, false)}</dd>
</dl>
{data ? barChartInfo() : placeholder() }
<button className='button button_results' onClick={this.handleDownload}><i className='collecticon collecticon-download' />{t('Download Country Profile PDF')}</button>
</div>
</div>
<button onClick={() =>
this.props.dispatch(showModalCalc()) &&
this.props.dispatch(newCalcId(d.id))
} className={c('button', 'button__map', 'button--full', {'button-full-disabled': hasData === false})}><span className='results__calc-hover'><i className={c('collecticon', 'collecticon-expand-top-left', {'hidden': hasData === false})} />{t(calcButtonLabel)}</span></button>
</section>
</div>
)
},
handleDownload: function () {
multiDownload([`assets/data/pdfs/${this.props.data.id}.pdf`])
}
})
export default Results
|
ajax/libs/rxjs/2.3.14/rx.all.compat.js | BitsyCode/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
Rx.iterator = $iterator$;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return {}.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (err) {
var self = this;
this.queue.push(function () {
self.observer.onError(err);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver() {
__super__.apply(this, arguments);
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
if (!subject.isDisposed) {
subject.onNext(value);
subject.onCompleted();
}
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next;
try {
next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = !!list.charAt ? list.charAt(i) : list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () {
return enumerableOf(argsOrArray(arguments, 0)).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
return enumerableOf(argsOrArray(arguments, 0)).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && observer.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
activeCount === 0 && observer.onCompleted();
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && observer.onCompleted();
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
group.length === 1 && observer.onCompleted();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0), first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; }
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(this.subscribe.bind(this));
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (onError) {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
}
observer.onError(err);
}, function () {
if (onCompleted) {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
}
observer.onCompleted();
});
});
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
!hasValue && hasSeed && observer.onNext(seed);
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && observer.onNext(q.shift());
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableOf([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new Error(argumentOutOfRange); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >=0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(Array.isArray(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (typeof selector === 'function' && typeof resultSelector === 'function') {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(Array.isArray(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (typeof selector === 'function' && typeof resultSelector === 'function') {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
running && observer.onNext(x);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining-- > 0) {
observer.onNext(x);
remaining === 0 && observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (e) {
observer.onError(e);
return;
}
shouldRun && observer.onNext(value);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (observer) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
observer.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
observer.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, observer.onError.bind(observer), function () {
observer.onNext(list);
observer.onCompleted();
});
});
}
function firstOnly(x) {
if (x.length === 0) {
throw new Error(sequenceContainsNoElements);
}
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var seed, hasSeed, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
hasSeed = true;
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var seed, hasSeed;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @example
* var result = source.any();
* var result = source.any(function (x) { return x > 3; });
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = observableProto.any = function (predicate, thisArg) {
var source = this;
return predicate ?
source.where(predicate, thisArg).any() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
*
* 1 - res = source.all(function (value) { return value.length > 3; });
* @memberOf Observable#
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = observableProto.all = function (predicate, thisArg) {
return this.where(function (v) {
return !predicate(v);
}, thisArg).any().select(function (b) {
return !b;
});
};
/**
* Determines whether an observable sequence contains a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value from the given index.
*/
observableProto.contains = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (observer) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
observer.onNext(false);
observer.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
observer.onNext(true);
observer.onCompleted();
}
},
observer.onError.bind(observer),
function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).count() :
this.aggregate(0, function (count) {
return count + 1;
});
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
observer.onNext(-1);
observer.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
observer.onNext(i);
observer.onCompleted();
}
i++;
},
observer.onError.bind(observer),
function () {
observer.onNext(-1);
observer.onCompleted();
});
});
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @example
* var res = source.sum();
* var res = source.sum(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.aggregate(0, function (prev, curr) {
return prev + curr;
});
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) {
return comparer(x, y) * -1;
});
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.select(keySelector, thisArg).average() :
this.scan({sum: 0, count: 0 }, function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}).finalValue().map(function (s) {
if (s.count === 0) {
throw new Error('The input sequence was empty');
}
return s.sum / s.count;
});
};
function sequenceEqualArray(first, second, comparer) {
return new AnonymousObservable(function (observer) {
var count = 0, len = second.length;
return first.subscribe(function (value) {
var equal = false;
try {
count < len && (equal = comparer(value, second[count++]));
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
}, observer.onError.bind(observer), function () {
observer.onNext(count === len);
observer.onCompleted();
});
});
}
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
if (Array.isArray(second)) {
return sequenceEqualArray(first, second, comparer);
}
return new AnonymousObservable(function (observer) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (doner) {
observer.onNext(false);
observer.onCompleted();
} else {
ql.push(x);
}
}, observer.onError.bind(observer), function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (doner) {
observer.onNext(true);
observer.onCompleted();
}
}
});
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
observer.onError(exception);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (donel) {
observer.onNext(false);
observer.onCompleted();
} else {
qr.push(x);
}
}, observer.onError.bind(observer), function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (donel) {
observer.onNext(true);
observer.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
});
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var i = index;
return source.subscribe(function (x) {
if (i === 0) {
observer.onNext(x);
observer.onCompleted();
}
i--;
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(argumentOutOfRange));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
observer.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @example
* var res = res = source.single();
* var res = res = source.single(function (x) { return x === 42; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
observer.onNext(x);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = res = source.firstOrDefault();
* var res = res = source.firstOrDefault(function (x) { return x > 3; });
* var res = source.firstOrDefault(function (x) { return x > 3; }, 0);
* var res = source.firstOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @example
* var res = source.last();
* var res = source.last(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = source.lastOrDefault();
* var res = source.lastOrDefault(function (x) { return x > 3; });
* var res = source.lastOrDefault(function (x) { return x > 3; }, 0);
* var res = source.lastOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
return new AnonymousObservable(function (observer) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, x, i, source);
} catch(e) {
observer.onError(e);
return;
}
if (shouldRun) {
observer.onNext(yieldIndex ? i : x);
observer.onCompleted();
} else {
i++;
}
}, observer.onError.bind(observer), function () {
observer.onNext(yieldIndex ? -1 : undefined);
observer.onCompleted();
});
});
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
if (!!root.Set) {
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var s = new root.Set();
return source.subscribe(
s.add.bind(s),
observer.onError.bind(observer),
function () {
observer.onNext(s);
observer.onCompleted();
});
});
};
}
if (!!root.Map) {
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
m.set(key, element);
},
observer.onError.bind(observer),
function () {
observer.onNext(m);
observer.onCompleted();
});
});
};
}
var fnString = 'function',
throwString = 'throw';
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res){
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn){
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
function isObject(val) {
return val && val.constructor === Object;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
var args = slice.call(arguments),
len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : error;
gen = fn.apply(this, args);
} else {
done = done || error;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) res = slice.call(arguments, 1);
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function(){
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
/**
* Takes a function with a callback and turns it into a thunk.
* @param {Function} A function with a callback such as fs.readFile
* @returns {Function} A function, when executed will continue the state machine.
*/
Rx.denodify = function (fn) {
return function (){
var args = slice.call(arguments),
results,
called,
callback;
args.push(function(){
results = arguments;
if (callback && !called) {
called = true;
cb.apply(this, results);
}
});
fn.apply(this, args);
return function (fn){
callback = fn;
if (results && !called) {
called = true;
fn.apply(this, results);
}
}
}
};
function error(err) {
if (!err) { return; }
timeoutScheduler.schedule(function(){
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
*
* @example
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.exception = error;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, subject.subscribe.bind(subject));
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof obj === 'string') { return stringHashFn(valueOf); }
}
if (obj.getHashCode) { return obj.getHashCode(); }
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new Error('out of range'); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
return this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch(exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
});
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBounaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
});
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
});
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
});
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
});
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeObservable().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
this.onError(notification.exception);
return;
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
observer.onNext.bind(observer),
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
observer.onError(err);
},
observer.onCompleted.bind(observer)
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && observer.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { observer.onNext(next.value); }
}
observer.onCompleted();
});
});
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { res.push(next.value); }
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, observer.onCompleted.bind(observer)),
source.subscribe(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
});
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function notImplemented() {
throw new Error('Not implemented');
}
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new Error(argumentOutOfRange); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this));
|
ajax/libs/vkui/4.28.0/components/AppRoot/AppRootPortal.min.js | cdnjs/cdnjs | import{createScopedElement}from"../../lib/jsxRuntime";import*as React from"react";import{createPortal}from"react-dom";import{AppRootContext}from"./AppRootContext";import{AppearanceProvider}from"../AppearanceProvider/AppearanceProvider";import{useAppearance}from"../../hooks/useAppearance";var AppRootPortal=function(e){var o=e.children,r=e.className,t=e.forcePortal,a=React.useContext(AppRootContext),p=a.portalRoot,e=a.mode,a=useAppearance(),t=null!==t&&void 0!==t?t:"full"!==e;return p&&t?createPortal(createScopedElement(AppearanceProvider,{appearance:a},createScopedElement("div",{className:r},o)),p):createScopedElement(React.Fragment,null,o)};export{AppRootPortal}; |
examples/with-jsxstyle/src/client.js | jaredpalmer/razzle | import App from "./App";
import { BrowserRouter } from "react-router-dom";
import React from "react";
import { hydrate } from "react-dom";
hydrate(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
if (module.hot) {
module.hot.accept();
}
|
bower_components/jquery/src/event.js | jaketrent/ajghost | define([
"./core",
"./var/strundefined",
"./var/rnotwhite",
"./var/hasOwn",
"./var/slice",
"./event/support",
"./core/init",
"./data/accepts",
"./selector"
], function( jQuery, strundefined, rnotwhite, hasOwn, slice, support ) {
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined && (
// Support: IE < 9
src.returnValue === false ||
// Support: Android < 4.0
src.getPreventDefault && src.getPreventDefault() ) ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
return jQuery;
});
|
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/local-activity.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsLocalActivity = (props) => (
<SvgIcon {...props}>
<path d="M20 12c0-1.1.9-2 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2zm-4.42 4.8L12 14.5l-3.58 2.3 1.08-4.12-3.29-2.69 4.24-.25L12 5.8l1.54 3.95 4.24.25-3.29 2.69 1.09 4.11z"/>
</SvgIcon>
);
MapsLocalActivity.displayName = 'MapsLocalActivity';
MapsLocalActivity.muiName = 'SvgIcon';
export default MapsLocalActivity;
|
ThemesList.js | i55ac/ZhiHuDaily-React-Native | 'use strict';
var React = require('react-native');
var {
AsyncStorage,
Platform,
ListView,
Image,
StyleSheet,
Text,
View,
TouchableNativeFeedback,
TouchableHighlight,
} = React
var API_THEMES = 'http://news-at.zhihu.com/api/4/themes';
var ThemesList = React.createClass({
getInitialState: function() {
var dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
return {
isLoading: false,
dataSource: dataSource,
};
},
componentDidMount: function() {
this.fetchThemes();
},
fetchThemes: function() {
fetch(API_THEMES)
.then((response) => response.json())
.catch((error) => {
this.setState({
isLoading: false,
dataSource: this.state.dataSource,
});
})
.then((responseData) => {
var themes = [];
if (responseData.subscribed) {
var len = responseData.subscribed.length;
var theme
for (var i = 0; i < len.length; i++) {
theme = responseData.subscribed[i];
theme.subscribed = true;
themes.push(theme);
}
}
if (responseData.others) {
themes = themes.concat(responseData.others);
}
this.setState({
isLoading: false,
dataSource: this.state.dataSource.cloneWithRows(themes),
});
})
.done();
},
renderHeader: function() {
var TouchableElement = TouchableHighlight;
if (Platform.OS === 'android') {
TouchableElement = TouchableNativeFeedback;
}
return(
<View style={styles.header}>
<View style={styles.userInfo}>
<TouchableElement>
<View style={{flexDirection: 'row', alignItems: 'center', padding: 16}}>
<Image
source={require('image!comment_avatar')}
style={{width: 40, height: 40, marginLeft: 8, marginRight: 8}} />
<Text style={styles.menuText}>
请登录
</Text>
</View>
</TouchableElement>
<View style={styles.row}>
<TouchableElement>
<View style={styles.menuContainer}>
<Image
source={require('image!ic_favorites_white')}
style={{width: 30, height: 30}} />
<Text style={styles.menuText}>
我的收藏
</Text>
</View>
</TouchableElement>
<TouchableElement>
<View style={styles.menuContainer}>
<Image
source={require('image!ic_download_white')}
style={{width: 30, height: 30}} />
<Text style={styles.menuText}>
离线下载
</Text>
</View>
</TouchableElement>
</View>
</View>
<TouchableElement onPress={() => this.props.onSelectItem(null)}>
<View style={styles.themeItem}>
<Image
source={require('image!home')}
style={{width: 30, height: 30, marginLeft: 10}} />
<Text style={styles.homeTheme}>
首页
</Text>
</View>
</TouchableElement>
</View>
);
},
renderRow: function(
theme: Object,
sectionID: number | string,
rowID: number | string,
highlightRowFunc: (sectionID: ?number | string, rowID: ?number | string) => void,
) {
var TouchableElement = TouchableHighlight;
if (Platform.OS === 'android') {
TouchableElement = TouchableNativeFeedback;
}
var icon = theme.subscribed ? require('image!ic_menu_arrow') : require('image!ic_menu_follow');
return (
<View>
<TouchableElement
onPress={() => this.props.onSelectItem(theme)}
onShowUnderlay={highlightRowFunc}
onHideUnderlay={highlightRowFunc}>
<View style={styles.themeItem}>
<Text style={styles.themeName}>
{theme.name}
</Text>
<Image source={icon} style={styles.themeIndicate}/>
</View>
</TouchableElement>
</View>
);
},
render: function() {
return (
<View style={styles.container} {...this.props}>
<ListView
ref="themeslistview"
dataSource={this.state.dataSource}
renderRow={this.renderRow}
automaticallyAdjustContentInsets={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps={true}
showsVerticalScrollIndicator={false}
renderHeader={this.renderHeader}
style={{flex:1, backgroundColor: 'white'}}
/>
</View>
);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAFAFA',
},
header: {
flex: 1,
flexDirection: 'column',
},
userInfo: {
flex: 1,
backgroundColor: '#00a2ed',
},
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
menuContainer: {
flex:1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
padding: 8,
},
menuText: {
fontSize: 14,
color: 'white',
},
homeTheme: {
fontSize: 16,
marginLeft: 16,
color: '#00a2ed'
},
themeItem: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
padding: 10,
},
themeName: {
flex: 1,
fontSize: 16,
marginLeft: 16,
},
themeIndicate: {
marginRight: 16,
width: 16,
height: 16,
},
separator: {
height: 1,
backgroundColor: '#eeeeee',
},
scrollSpinner: {
marginVertical: 20,
},
rowSeparator: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
height: 1,
marginLeft: 4,
},
rowSeparatorHide: {
opacity: 0.0,
},
});
module.exports = ThemesList;
|
src/app/films/NewFilm/Uploader/Uploader.js | JoeKarlsson1/bechdel-test | import '@uppy/core/dist/style.css';
import '@uppy/dashboard/dist/style.css';
import React, { Component } from 'react';
import { Uppy } from '@uppy/core';
import { Dashboard, DragDrop, ProgressBar } from '@uppy/react';
import XHRUpload from '@uppy/xhr-upload';
import ErrorBoundary from '../../../shared/ErrorBoundary/ErrorBoundary';
console.log(XHRUpload);
class Uploader extends Component {
constructor(props) {
super(props);
this.uppy = new Uppy({
id: 'uppy',
meta: { type: 'script' },
restrictions: {
maxNumberOfFiles: 10,
maxFileSize: 1000000,
minNumberOfFiles: 1,
allowedFileTypes: ['text/plain/*'],
},
thumbnailGeneration: true,
autoProceed: true,
debug: true,
}).use(XHRUpload, {
endpoint: '/api/film',
fieldName: 'script',
method: 'post',
formData: true,
limit: 10,
getResponseData: xhr => {
let response = JSON.parse(xhr.response);
response = response['0'];
console.log('response', response);
window.location = `/film/${response._id}`;
return {
url: xhr.responseXML.querySelector('Location').textContent,
};
},
});
}
componentWillUnmount() {
this.uppy.close();
}
render() {
return (
<ErrorBoundary>
<Dashboard uppy={this.uppy} />
<DragDrop
uppy={this.uppy}
locale={{
strings: {
chooseFile: 'Boop a file',
orDragDrop: 'or yoink it here',
},
}}
/>
<h2>Progress Bar</h2>
<ProgressBar uppy={this.uppy} hideAfterFinish={false} />
</ErrorBoundary>
);
}
}
export default Uploader;
|
website/layout/AutodocsLayout.js | dimoge/react-native | /**
* Copyright (c) 2015-present, 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.
*
* @providesModule AutodocsLayout
*/
var DocsSidebar = require('DocsSidebar');
var H = require('Header');
var Header = require('Header');
var Marked = require('Marked');
var Prism = require('Prism');
var React = require('React');
var Site = require('Site');
var slugify = require('slugify');
var styleReferencePattern = /^[^.]+\.propTypes\.style$/;
function renderType(type) {
if (type.name === 'enum') {
if (typeof type.value === 'string') {
return type.value;
}
return 'enum(' + type.value.map((v) => v.value).join(', ') + ')';
}
if (type.name === 'shape') {
return '{' + Object.keys(type.value).map((key => key + ': ' + renderType(type.value[key]))).join(', ') + '}';
}
if (type.name == 'union') {
return type.value.map(renderType).join(', ');
}
if (type.name === 'arrayOf') {
return '[' + renderType(type.value) + ']';
}
if (type.name === 'instanceOf') {
return type.value;
}
if (type.name === 'custom') {
if (styleReferencePattern.test(type.raw)) {
var name = type.raw.substring(0, type.raw.indexOf('.'));
return <a href={slugify(name) + '.html#style'}>{name}#style</a>
}
if (type.raw === 'EdgeInsetsPropType') {
return '{top: number, left: number, bottom: number, right: number}';
}
return type.raw;
}
if (type.name === 'stylesheet') {
return 'style';
}
if (type.name === 'func') {
return 'function';
}
return type.name;
}
var ComponentDoc = React.createClass({
renderProp: function(name, prop) {
return (
<div className="prop" key={name}>
<Header level={4} className="propTitle" toSlug={name}>
{prop.platforms && prop.platforms.map(platform =>
<span className="platform">{platform}</span>
)}
{name}
{' '}
{prop.type && <span className="propType">
{renderType(prop.type)}
</span>}
</Header>
{prop.type && prop.type.name === 'stylesheet' &&
this.renderStylesheetProps(prop.type.value)}
{prop.description && <Marked>{prop.description}</Marked>}
</div>
);
},
renderCompose: function(name) {
return (
<div className="prop" key={name}>
<Header level={4} className="propTitle" toSlug={name}>
<a href={slugify(name) + '.html#props'}>{name} props...</a>
</Header>
</div>
);
},
renderStylesheetProps: function(stylesheetName) {
var style = this.props.content.styles[stylesheetName];
return (
<div className="compactProps">
{(style.composes || []).map((name) => {
var link;
if (name === 'LayoutPropTypes') {
name = 'Flexbox';
link =
<a href={slugify(name) + '.html#proptypes'}>{name}...</a>;
} else if (name === 'TransformPropTypes') {
name = 'Transforms';
link =
<a href={slugify(name) + '.html#proptypes'}>{name}...</a>;
} else {
name = name.replace('StylePropTypes', '');
link =
<a href={slugify(name) + '.html#style'}>{name}#style...</a>;
}
return (
<div className="prop" key={name}>
<h6 className="propTitle">{link}</h6>
</div>
);
})}
{Object.keys(style.props).map((name) =>
<div className="prop" key={name}>
<h6 className="propTitle">
{name}
{' '}
{style.props[name].type && <span className="propType">
{renderType(style.props[name].type)}
</span>}
</h6>
</div>
)}
</div>
);
},
renderProps: function(props, composes) {
return (
<div className="props">
{(composes || []).map((name) =>
this.renderCompose(name)
)}
{Object.keys(props)
.sort((nameA, nameB) => {
var a = props[nameA];
var b = props[nameB];
if (a.platforms && !b.platforms) {
return 1;
}
if (b.platforms && !a.platforms) {
return -1;
}
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
})
.map((name) =>
this.renderProp(name, props[name])
)}
</div>
);
},
extractPlatformFromProps: function(props) {
for (var key in props) {
var prop = props[key];
var description = prop.description || '';
var platforms = description.match(/\@platform (.+)/);
platforms = platforms && platforms[1].replace(/ /g, '').split(',');
description = description.replace(/\@platform (.+)/, '');
prop.description = description;
prop.platforms = platforms;
}
},
render: function() {
var content = this.props.content;
this.extractPlatformFromProps(content.props);
return (
<div>
<Marked>
{content.description}
</Marked>
<HeaderWithGithub
title="Props"
path={content.filepath}
/>
{this.renderProps(content.props, content.composes)}
</div>
);
}
});
var APIDoc = React.createClass({
removeCommentsFromDocblock: function(docblock) {
return docblock
.trim('\n ')
.replace(/^\/\*+/, '')
.replace(/\*\/$/, '')
.split('\n')
.map(function(line) {
return line.trim().replace(/^\* ?/, '');
})
.join('\n');
},
renderTypehintRec: function(typehint) {
if (typehint.type === 'simple') {
return typehint.value;
}
if (typehint.type === 'generic') {
return this.renderTypehintRec(typehint.value[0]) + '<' + this.renderTypehintRec(typehint.value[1]) + '>';
}
return JSON.stringify(typehint);
},
renderTypehint: function(typehint) {
try {
var typehint = JSON.parse(typehint);
} catch(e) {
return typehint;
}
return this.renderTypehintRec(typehint);
},
renderMethod: function(method) {
return (
<div className="prop" key={method.name}>
<Header level={4} className="propTitle" toSlug={method.name}>
{method.modifiers.length && <span className="propType">
{method.modifiers.join(' ') + ' '}
</span> || ''}
{method.name}
<span className="propType">
({method.params
.map((param) => {
var res = param.name;
if (param.typehint) {
res += ': ' + this.renderTypehint(param.typehint);
}
return res;
})
.join(', ')})
</span>
</Header>
{method.docblock && <Marked>
{this.removeCommentsFromDocblock(method.docblock)}
</Marked>}
</div>
);
},
renderMethods: function(methods) {
if (!methods.length) {
return null;
}
return (
<span>
<H level={3}>Methods</H>
<div className="props">
{methods.filter((method) => {
return method.name[0] !== '_';
}).map(this.renderMethod)}
</div>
</span>
);
},
renderProperty: function(property) {
return (
<div className="prop" key={property.name}>
<Header level={4} className="propTitle" toSlug={property.name}>
{property.name}
{property.type &&
<span className="propType">
{': ' + renderType(property.type)}
</span>
}
</Header>
{property.docblock && <Marked>
{this.removeCommentsFromDocblock(property.docblock)}
</Marked>}
</div>
);
},
renderProperties: function(properties) {
if (!properties || !properties.length) {
return null;
}
return (
<span>
<H level={3}>Properties</H>
<div className="props">
{properties.filter((property) => {
return property.name[0] !== '_';
}).map(this.renderProperty)}
</div>
</span>
);
},
renderClasses: function(classes) {
if (!classes || !classes.length) {
return null;
}
return (
<span>
<div>
{classes.filter((cls) => {
return cls.name[0] !== '_' && cls.ownerProperty[0] !== '_';
}).map((cls) => {
return (
<span key={cls.name}>
<Header level={2} toSlug={cls.name}>
class {cls.name}
</Header>
<ul>
{cls.docblock && <Marked>
{this.removeCommentsFromDocblock(cls.docblock)}
</Marked>}
{this.renderMethods(cls.methods)}
{this.renderProperties(cls.properties)}
</ul>
</span>
);
})}
</div>
</span>
);
},
render: function() {
var content = this.props.content;
if (!content.methods) {
throw new Error(
'No component methods found for ' + content.componentName
);
}
return (
<div>
<Marked>
{this.removeCommentsFromDocblock(content.docblock)}
</Marked>
{this.renderMethods(content.methods)}
{this.renderProperties(content.properties)}
{this.renderClasses(content.classes)}
</div>
);
}
});
var HeaderWithGithub = React.createClass({
renderRunnableLink: function() {
if (this.props.metadata && this.props.metadata.runnable) {
return (
<a
className="run-example"
target="_blank"
href={'https://rnplay.org/apps/l3Zi2g?route='+this.props.metadata.title+'&file=' + this.props.metadata.title+ "Example.js"}>
Run this example
</a>
);
}
},
render: function() {
return (
<H level={3} toSlug={this.props.title}>
<a
className="edit-github"
href={'https://github.com/facebook/react-native/blob/master/' + this.props.path}>
Edit on GitHub
</a>
{this.renderRunnableLink()}
{this.props.title}
</H>
);
}
});
var Autodocs = React.createClass({
renderFullDescription: function(docs) {
if (!docs.fullDescription) {
return;
}
return (
<div>
<HeaderWithGithub
title="Description"
path={'docs/' + docs.componentName + '.md'}
/>
<Marked>
{docs.fullDescription}
</Marked>
</div>
);
},
renderExample: function(docs, metadata) {
if (!docs.example) {
return;
}
return (
<div>
<HeaderWithGithub
title="Examples"
path={docs.example.path}
metadata={metadata}
/>
<Prism>
{docs.example.content.replace(/^[\s\S]*?\*\//, '').trim()}
</Prism>
</div>
);
},
render: function() {
var metadata = this.props.metadata;
var docs = JSON.parse(this.props.children);
var content = docs.type === 'component' || docs.type === 'style' ?
<ComponentDoc content={docs} /> :
<APIDoc content={docs} apiName={metadata.title} />;
return (
<Site section="docs" title={metadata.title}>
<section className="content wrap documentationContent">
<DocsSidebar metadata={metadata} />
<div className="inner-content">
<a id="content" />
<h1>{metadata.title}</h1>
{content}
{this.renderFullDescription(docs)}
{this.renderExample(docs, metadata)}
<div className="docs-prevnext">
{metadata.previous && <a className="docs-prev" href={metadata.previous + '.html#content'}>← Prev</a>}
{metadata.next && <a className="docs-next" href={metadata.next + '.html#content'}>Next →</a>}
</div>
</div>
</section>
</Site>
);
}
});
module.exports = Autodocs;
|
cms/static/xmodule_js/common_static/js/vendor/analytics.js | syjeon/new_edx | ;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module.exports) {
module.exports = {};
module.client = module.component = true;
module.call(this, module.exports, require.relative(resolved), module);
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("avetisk-defaults/index.js", function(exports, require, module){
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
});
require.register("component-clone/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
});
require.register("component-cookie/index.js", function(exports, require, module){
/**
* Encode.
*/
var encode = encodeURIComponent;
/**
* Decode.
*/
var decode = decodeURIComponent;
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toUTCString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
});
require.register("component-each/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
});
require.register("component-event/index.js", function(exports, require, module){
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
});
require.register("component-inherit/index.js", function(exports, require, module){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
});
require.register("component-object/index.js", function(exports, require, module){
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
});
require.register("component-trim/index.js", function(exports, require, module){
exports = module.exports = trim;
function trim(str){
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
return str.replace(/^\s*/, '');
};
exports.right = function(str){
return str.replace(/\s*$/, '');
};
});
require.register("component-querystring/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var trim = require('trim');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
obj[parts[0]] = null == parts[1]
? ''
: decodeURIComponent(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
};
});
require.register("component-type/index.js", function(exports, require, module){
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Function]': return 'function';
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object String]': return 'string';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val && val.nodeType === 1) return 'element';
if (val === Object(val)) return 'object';
return typeof val;
};
});
require.register("component-url/index.js", function(exports, require, module){
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host || location.host,
port: ('0' === a.port || '' === a.port) ? location.port : a.port,
hash: a.hash,
hostname: a.hostname || location.hostname,
pathname: a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname,
protocol: !a.protocol || ':' == a.protocol ? location.protocol : a.protocol,
search: a.search,
query: a.search.slice(1)
};
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
return 0 == url.indexOf('//') || !!~url.indexOf('://');
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return !exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname !== location.hostname
|| url.port !== location.port
|| url.protocol !== location.protocol;
};
});
require.register("segmentio-after/index.js", function(exports, require, module){
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
});
require.register("segmentio-alias/index.js", function(exports, require, module){
module.exports = function alias (object, aliases) {
// For each of our aliases, rename our object's keys.
for (var oldKey in aliases) {
var newKey = aliases[oldKey];
if (object[oldKey] !== undefined) {
object[newKey] = object[oldKey];
delete object[oldKey];
}
}
};
});
require.register("component-bind/index.js", function(exports, require, module){
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = [].slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
});
require.register("segmentio-bind-all/index.js", function(exports, require, module){
var bind = require('bind')
, type = require('type');
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
});
require.register("segmentio-canonical/index.js", function(exports, require, module){
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
});
require.register("segmentio-extend/index.js", function(exports, require, module){
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
});
require.register("segmentio-is-email/index.js", function(exports, require, module){
module.exports = function isEmail (string) {
return (/.+\@.+\..+/).test(string);
};
});
require.register("segmentio-is-meta/index.js", function(exports, require, module){
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
});
require.register("component-json-fallback/index.js", function(exports, require, module){
/*
json2.js
2011-10-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON = {};
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
module.exports = JSON
});
require.register("segmentio-json/index.js", function(exports, require, module){
module.exports = 'undefined' == typeof JSON
? require('json-fallback')
: JSON;
});
require.register("segmentio-load-date/index.js", function(exports, require, module){
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
});
require.register("segmentio-load-script/index.js", function(exports, require, module){
var type = require('type');
module.exports = function loadScript (options, callback) {
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if (type(options) === 'string') options = { src : options };
var https = document.location.protocol === 'https:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
// If we have a callback, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if (callback && type(callback) === 'function') {
if (script.addEventListener) {
script.addEventListener('load', callback, false);
} else if (script.attachEvent) {
script.attachEvent('onreadystatechange', function () {
if (/complete|loaded/.test(script.readyState)) callback();
});
}
}
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
});
require.register("segmentio-new-date/index.js", function(exports, require, module){
var type = require('type');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native one.
*
* @param {Date|String|Number} input
*/
module.exports = function newDate (input) {
// Convert input from seconds to milliseconds.
input = toMilliseconds(input);
// By default, delegate to Date, which will return `Invalid Date`s if wrong.
var date = new Date(input);
// If we have a string that the Date constructor couldn't parse, convert it.
if (isNaN(date.getTime()) && 'string' === type(input)) {
var milliseconds = toMilliseconds(parseInt(input, 10));
date = new Date(milliseconds);
}
return date;
};
/**
* If the number passed in is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param seconds
*/
function toMilliseconds (seconds) {
if ('number' === type(seconds) && seconds < 31557600000) return seconds * 1000;
return seconds;
}
});
require.register("segmentio-on-body/index.js", function(exports, require, module){
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
});
require.register("segmentio-store.js/store.js", function(exports, require, module){
var json = require('json')
, store = {}
, win = window
, doc = win.document
, localStorageName = 'localStorage'
, namespace = '__storejs__'
, storage;
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return json.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return json.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
module.exports = store;
});
require.register("segmentio-top-domain/index.js", function(exports, require, module){
var url = require('url');
// Official Grammar: http://tools.ietf.org/html/rfc883#page-56
// Look for tlds with up to 2-6 characters.
module.exports = function (urlStr) {
var host = url.parse(urlStr).hostname
, topLevel = host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i);
return topLevel ? topLevel[0] : host;
};
});
require.register("timoxley-next-tick/index.js", function(exports, require, module){
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
});
require.register("yields-prevent/index.js", function(exports, require, module){
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
});
require.register("analytics/src/index.js", function(exports, require, module){
// Analytics.js
//
// (c) 2013 Segment.io Inc.
// Analytics.js may be freely distributed under the MIT license.
var Analytics = require('./analytics')
, providers = require('./providers');
module.exports = new Analytics(providers);
});
require.register("analytics/src/analytics.js", function(exports, require, module){
var after = require('after')
, bind = require('event').bind
, clone = require('clone')
, cookie = require('./cookie')
, each = require('each')
, extend = require('extend')
, isEmail = require('is-email')
, isMeta = require('is-meta')
, localStore = require('./localStore')
, newDate = require('new-date')
, size = require('object').length
, preventDefault = require('prevent')
, Provider = require('./provider')
, providers = require('./providers')
, querystring = require('querystring')
, type = require('type')
, url = require('url')
, user = require('./user')
, utils = require('./utils');
module.exports = Analytics;
/**
* Analytics.
*
* @param {Object} Providers - Provider classes that the user can initialize.
*/
function Analytics (Providers) {
var self = this;
this.VERSION = '0.11.9';
each(Providers, function (Provider) {
self.addProvider(Provider);
});
// Wrap `onload` with our own that will cache the loaded state of the page.
var oldonload = window.onload;
window.onload = function () {
self.loaded = true;
if ('function' === type(oldonload)) oldonload();
};
}
/**
* Extend the Analytics prototype.
*/
extend(Analytics.prototype, {
// Whether `onload` has fired.
loaded : false,
// Whether `analytics` has been initialized.
initialized : false,
// Whether all of our analytics providers are ready to accept calls. Give it a
// real jank name since we already use `analytics.ready` for the method.
readied : false,
// A queue for ready callbacks to run when our `readied` state becomes `true`.
callbacks : [],
// Milliseconds to wait for requests to clear before leaving the current page.
timeout : 300,
// A reference to the current user object.
user : user,
// The default Provider.
Provider : Provider,
// Providers that can be initialized. Add using `this.addProvider`.
_providers : {},
// The currently initialized providers.
providers : [],
/**
* Add a provider to `_providers` to be initialized later.
*
* @param {String} name - The name of the provider.
* @param {Function} Provider - The provider's class.
*/
addProvider : function (Provider) {
this._providers[Provider.prototype.name] = Provider;
},
/**
* Initialize
*
* Call `initialize` to setup analytics.js before identifying or
* tracking any users or events. For example:
*
* analytics.initialize({
* 'Google Analytics' : 'UA-XXXXXXX-X',
* 'Segment.io' : 'XXXXXXXXXXX',
* 'KISSmetrics' : 'XXXXXXXXXXX'
* });
*
* @param {Object} providers - a dictionary of the providers you want to
* enable. The keys are the names of the providers and their values are either
* an api key, or dictionary of extra settings (including the api key).
*
* @param {Object} options (optional) - extra settings to initialize with.
*/
initialize : function (providers, options) {
options || (options = {});
var self = this;
// Reset our state.
this.providers = [];
this.initialized = false;
this.readied = false;
// Set the storage options
cookie.options(options.cookie);
localStore.options(options.localStorage);
// Set the options for loading and saving the user
user.options(options.user);
user.load();
// Create a ready method that will call all of our ready callbacks after all
// of our providers have been initialized and loaded. We'll pass the
// function into each provider's initialize method, so they can callback
// after they've loaded successfully.
var ready = after(size(providers), function () {
self.readied = true;
var callback;
while(callback = self.callbacks.shift()) {
callback();
}
});
// Initialize a new instance of each provider with their `options`, and
// copy the provider into `this.providers`.
each(providers, function (key, options) {
var Provider = self._providers[key];
if (!Provider) return;
self.providers.push(new Provider(options, ready, self));
});
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var query = url.parse(window.location.href).query;
var queries = querystring.parse(query);
if (queries.ajs_uid) this.identify(queries.ajs_uid);
if (queries.ajs_event) this.track(queries.ajs_event);
// Update the initialized state that other methods rely on.
this.initialized = true;
},
/**
* Ready
*
* Add a callback that will get called when all of the analytics services you
* initialize are ready to be called. It's like jQuery's `ready` except for
* analytics instead of the DOM.
*
* If we're already ready, it will callback immediately.
*
* @param {Function} callback - The callback to attach.
*/
ready : function (callback) {
if (type(callback) !== 'function') return;
if (this.readied) return callback();
this.callbacks.push(callback);
},
/**
* Identify
*
* Identifying a user ties all of their actions to an ID you recognize
* and records properties about a user. For example:
*
* analytics.identify('4d3ed089fb60ab534684b7e0', {
* name : 'Achilles',
* email : '[email protected]',
* age : 23
* });
*
* @param {String} userId (optional) - The ID you recognize the user by.
* Ideally this isn't an email, because that might change in the future.
*
* @param {Object} traits (optional) - A dictionary of traits you know about
* the user. Things like `name`, `age`, etc.
*
* @param {Object} options (optional) - Settings for the identify call.
*
* @param {Function} callback (optional) - A function to call after a small
* timeout, giving the identify call time to make requests.
*/
identify : function (userId, traits, options, callback) {
if (!this.initialized) return;
// Allow for optional arguments.
if (type(options) === 'function') {
callback = options;
options = undefined;
}
if (type(traits) === 'function') {
callback = traits;
traits = undefined;
}
if (type(userId) === 'object') {
if (traits && type(traits) === 'function') callback = traits;
traits = userId;
userId = undefined;
}
// Use our cookied ID if they didn't provide one.
if (userId === undefined || user === null) userId = user.id();
// Update the cookie with the new userId and traits.
var alias = user.update(userId, traits);
// Clone `traits` before we manipulate it, so we don't do anything uncouth
// and take the user.traits() so anonymous users carry over traits.
traits = cleanTraits(userId, clone(user.traits()));
// Call `identify` on all of our enabled providers that support it.
each(this.providers, function (provider) {
if (provider.identify && isEnabled(provider, options)) {
var args = [userId, clone(traits), clone(options)];
if (provider.ready) {
provider.identify.apply(provider, args);
} else {
provider.enqueue('identify', args);
}
}
});
// If we should alias, go ahead and do it.
// if (alias) this.alias(userId);
if (callback && type(callback) === 'function') {
setTimeout(callback, this.timeout);
}
},
/**
* Group
*
* Groups multiple users together under one "account" or "team" or "company".
* Acts on the currently identified user, so you need to call identify before
* calling group. For example:
*
* analytics.identify('4d3ed089fb60ab534684b7e0', {
* name : 'Achilles',
* email : '[email protected]',
* age : 23
* });
*
* analytics.group('5we93je3889fb60a937dk033', {
* name : 'Acme Co.',
* numberOfEmployees : 42,
* location : 'San Francisco'
* });
*
* @param {String} groupId - The ID you recognize the group by.
*
* @param {Object} properties (optional) - A dictionary of properties you know
* about the group. Things like `numberOfEmployees`, `location`, etc.
*
* @param {Object} options (optional) - Settings for the group call.
*
* @param {Function} callback (optional) - A function to call after a small
* timeout, giving the group call time to make requests.
*/
group : function (groupId, properties, options, callback) {
if (!this.initialized) return;
// Allow for optional arguments.
if (type(options) === 'function') {
callback = options;
options = undefined;
}
if (type(properties) === 'function') {
callback = properties;
properties = undefined;
}
// Clone `properties` before we manipulate it, so we don't do anything bad,
// and back it by an empty object so that providers can assume it exists.
properties = clone(properties) || {};
// Convert dates from more types of input into Date objects.
if (properties.created) properties.created = newDate(properties.created);
// Call `group` on all of our enabled providers that support it.
each(this.providers, function (provider) {
if (provider.group && isEnabled(provider, options)) {
var args = [groupId, clone(properties), clone(options)];
if (provider.ready) {
provider.group.apply(provider, args);
} else {
provider.enqueue('group', args);
}
}
});
// If we have a callback, call it after a small timeout.
if (callback && type(callback) === 'function') {
setTimeout(callback, this.timeout);
}
},
/**
* Track
*
* Record an event (or action) that your user has triggered. For example:
*
* analytics.track('Added a Friend', {
* level : 'hard',
* volume : 11
* });
*
* @param {String} event - The name of your event.
*
* @param {Object} properties (optional) - A dictionary of properties of the
* event. `properties` are all camelCase (we'll automatically conver them to
* the proper case each provider needs).
*
* @param {Object} options (optional) - Settings for the track call.
*
* @param {Function} callback - A function to call after a small
* timeout, giving the identify time to make requests.
*/
track : function (event, properties, options, callback) {
if (!this.initialized) return;
// Allow for optional arguments.
if (type(options) === 'function') {
callback = options;
options = undefined;
}
if (type(properties) === 'function') {
callback = properties;
properties = undefined;
}
// Call `track` on all of our enabled providers that support it.
each(this.providers, function (provider) {
if (provider.track && isEnabled(provider, options)) {
var args = [event, clone(properties), clone(options)];
if (provider.ready) {
provider.track.apply(provider, args);
} else {
provider.enqueue('track', args);
}
}
});
if (callback && type(callback) === 'function') {
setTimeout(callback, this.timeout);
}
},
/**
* Track Link
*
* A helper for tracking outbound links that would normally navigate away from
* the page before the track requests were made. It works by wrapping the
* calls in a short timeout, giving the requests time to fire.
*
* @param {Element|Array} links - The link element or array of link elements
* to bind to. (Allowing arrays makes it easy to pass in jQuery objects.)
*
* @param {String|Function} event - Passed directly to `track`. Or in the case
* that it's a function, it will be called with the link element as the first
* argument.
*
* @param {Object|Function} properties (optional) - Passed directly to
* `track`. Or in the case that it's a function, it will be called with the
* link element as the first argument.
*/
trackLink : function (links, event, properties) {
if (!links) return;
// Turn a single link into an array so that we're always handling
// arrays, which allows for passing jQuery objects.
if ('element' === type(links)) links = [links];
var self = this
, eventFunction = 'function' === type(event)
, propertiesFunction = 'function' === type(properties);
each(links, function (el) {
bind(el, 'click', function (e) {
// Allow for `event` or `properties` to be a function. And pass it the
// link element that was clicked.
var newEvent = eventFunction ? event(el) : event;
var newProperties = propertiesFunction ? properties(el) : properties;
self.track(newEvent, newProperties);
// To justify us preventing the default behavior we must:
//
// * Have an `href` to use.
// * Not have a `target="_blank"` attribute.
// * Not have any special keys pressed, because they might be trying to
// open in a new tab, or window, or download.
//
// This might not cover all cases, but we'd rather throw out an event
// than miss a case that breaks the user experience.
if (el.href && el.target !== '_blank' && !isMeta(e)) {
preventDefault(e);
// Navigate to the url after just enough of a timeout.
setTimeout(function () {
window.location.href = el.href;
}, self.timeout);
}
});
});
},
/**
* Track Form
*
* Similar to `trackClick`, this is a helper for tracking form submissions
* that would normally navigate away from the page before a track request can
* be sent. It works by preventing the default submit event, sending our
* track requests, and then submitting the form programmatically.
*
* @param {Element|Array} forms - The form element or array of form elements
* to bind to. (Allowing arrays makes it easy to pass in jQuery objects.)
*
* @param {String|Function} event - Passed directly to `track`. Or in the case
* that it's a function, it will be called with the form element as the first
* argument.
*
* @param {Object|Function} properties (optional) - Passed directly to
* `track`. Or in the case that it's a function, it will be called with the
* form element as the first argument.
*/
trackForm : function (form, event, properties) {
if (!form) return;
// Turn a single element into an array so that we're always handling arrays,
// which allows for passing jQuery objects.
if ('element' === type(form)) form = [form];
var self = this
, eventFunction = 'function' === type(event)
, propertiesFunction = 'function' === type(properties);
each(form, function (el) {
var handler = function (e) {
// Allow for `event` or `properties` to be a function. And pass it the
// form element that was submitted.
var newEvent = eventFunction ? event(el) : event;
var newProperties = propertiesFunction ? properties(el) : properties;
self.track(newEvent, newProperties);
preventDefault(e);
// Submit the form after a timeout, giving the event time to fire.
setTimeout(function () {
el.submit();
}, self.timeout);
};
// Support the form being submitted via jQuery instead of for real. This
// doesn't happen automatically because `el.submit()` doesn't actually
// fire submit handlers, which is what jQuery uses internally. >_<
var dom = window.jQuery || window.Zepto;
if (dom) {
dom(el).submit(handler);
} else {
bind(el, 'submit', handler);
}
});
},
/**
* Pageview
*
* Simulate a pageview in single-page applications, where real pageviews don't
* occur. This isn't support by all providers.
*
* @param {String} url (optional) - The path of the page (eg. '/login'). Most
* providers will default to the current pages URL, so you don't need this.
*
* @param {Object} options (optional) - Settings for the pageview call.
*
*/
pageview : function (url,options) {
if (!this.initialized) return;
// Call `pageview` on all of our enabled providers that support it.
each(this.providers, function (provider) {
if (provider.pageview && isEnabled(provider, options)) {
var args = [url];
if (provider.ready) {
provider.pageview.apply(provider, args);
} else {
provider.enqueue('pageview', args);
}
}
});
},
/**
* Alias
*
* Merges two previously unassociate user identities. This comes in handy if
* the same user visits from two different devices and you want to combine
* their analytics history.
*
* Some providers don't support merging users.
*
* @param {String} newId - The new ID you want to recognize the user by.
*
* @param {String} originalId (optional) - The original ID that the user was
* recognized by. This defaults to the current identified user's ID if there
* is one. In most cases you don't need to pass in the `originalId`.
*/
alias : function (newId, originalId, options) {
if (!this.initialized) return;
if (type(originalId) === 'object') {
options = originalId;
originalId = undefined;
}
// Call `alias` on all of our enabled providers that support it.
each(this.providers, function (provider) {
if (provider.alias && isEnabled(provider, options)) {
var args = [newId, originalId];
if (provider.ready) {
provider.alias.apply(provider, args);
} else {
provider.enqueue('alias', args);
}
}
});
},
/**
* Log
*
* Log an error to analytics providers that support it, like Sentry.
*
* @param {Error|String} error - The error or string to log.
* @param {Object} properties - Properties about the error.
* @param {Object} options (optional) - Settings for the log call.
*/
log : function (error, properties, options) {
if (!this.initialized) return;
each(this.providers, function (provider) {
if (provider.log && isEnabled(provider, options)) {
var args = [error, properties, options];
if (provider.ready) {
provider.log.apply(provider, args);
} else {
provider.enqueue('log', args);
}
}
});
}
});
/**
* Backwards compatibility.
*/
// Alias `trackClick` and `trackSubmit`.
Analytics.prototype.trackClick = Analytics.prototype.trackLink;
Analytics.prototype.trackSubmit = Analytics.prototype.trackForm;
/**
* Determine whether a provider is enabled or not based on the options object.
*
* @param {Object} provider - the current provider.
* @param {Object} options - the current call's options.
*
* @return {Boolean} - wether the provider is enabled.
*/
var isEnabled = function (provider, options) {
var enabled = true;
if (!options || !options.providers) return enabled;
// Default to the 'all' or 'All' setting.
var map = options.providers;
if (map.all !== undefined) enabled = map.all;
if (map.All !== undefined) enabled = map.All;
// Look for this provider's specific setting.
var name = provider.name;
if (map[name] !== undefined) enabled = map[name];
return enabled;
};
/**
* Clean up traits, default some useful things both so the user doesn't have to
* and so we don't have to do it on a provider-basis.
*
* @param {Object} traits The traits object.
* @return {Object} The new traits object.
*/
var cleanTraits = function (userId, traits) {
// Add the `email` trait if it doesn't exist and the `userId` is an email.
if (!traits.email && isEmail(userId)) traits.email = userId;
// Create the `name` trait if it doesn't exist and `firstName` and `lastName`
// are both supplied.
if (!traits.name && traits.firstName && traits.lastName) {
traits.name = traits.firstName + ' ' + traits.lastName;
}
// Convert dates from more types of input into Date objects.
if (traits.created) traits.created = newDate(traits.created);
if (traits.company && traits.company.created) {
traits.company.created = newDate(traits.company.created);
}
return traits;
};
});
require.register("analytics/src/cookie.js", function(exports, require, module){
var bindAll = require('bind-all')
, cookie = require('cookie')
, clone = require('clone')
, defaults = require('defaults')
, json = require('json')
, topDomain = require('top-domain');
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
var domain = '.' + topDomain(window.location.href);
// localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html
if (domain === '.localhost') domain = '';
defaults(options, {
maxage : 31536000000, // default to a year
path : '/',
domain : domain
});
this._options = options;
};
/**
* Set a value in our cookie
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from the cookie
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Export singleton cookie
*/
module.exports = bindAll(new Cookie());
module.exports.Cookie = Cookie;
});
require.register("analytics/src/localStore.js", function(exports, require, module){
var bindAll = require('bind-all')
, defaults = require('defaults')
, store = require('store');
function Store (options) {
this.options(options);
}
/**
* Sets the options for the store
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Sets a value in local storage
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Gets a value from local storage
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Removes a value from local storage
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Singleton exports
*/
module.exports = bindAll(new Store());
});
require.register("analytics/src/provider.js", function(exports, require, module){
var each = require('each')
, extend = require('extend')
, type = require('type');
module.exports = Provider;
/**
* Provider
*
* @param {Object} options - settings to initialize the Provider with. This will
* be merged with the Provider's own defaults.
*
* @param {Function} ready - a ready callback, to be called when the provider is
* ready to handle analytics calls.
*/
function Provider (options, ready, analytics) {
var self = this;
// Store the reference to the global `analytics` object.
this.analytics = analytics;
// Make a queue of `{ method : 'identify', args : [] }` to unload once ready.
this.queue = [];
this.ready = false;
// Allow for `options` to only be a string if the provider has specified
// a default `key`, in which case convert `options` into a dictionary. Also
// allow for it to be `true`, like in Optimizely's case where there is no need
// for any default key.
if (type(options) !== 'object') {
if (options === true) {
options = {};
} else if (this.key) {
var key = options;
options = {};
options[this.key] = key;
} else {
throw new Error('Couldnt resolve options.');
}
}
// Extend the passed-in options with our defaults.
this.options = extend({}, this.defaults, options);
// Wrap our ready function, so that it ready from our internal queue first
// and then marks us as ready.
var dequeue = function () {
each(self.queue, function (call) {
var method = call.method
, args = call.args;
self[method].apply(self, args);
});
self.ready = true;
self.queue = [];
ready();
};
// Call our initialize method.
this.initialize.call(this, this.options, dequeue);
}
/**
* Inheritance helper.
*
* Modeled after Backbone's `extend` method:
* https://github.com/documentcloud/backbone/blob/master/backbone.js#L1464
*/
Provider.extend = function (properties) {
var parent = this;
var child = function () { return parent.apply(this, arguments); };
var Surrogate = function () { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
extend(child.prototype, properties);
return child;
};
/**
* Augment Provider's prototype.
*/
extend(Provider.prototype, {
/**
* Default settings for the provider.
*/
options : {},
/**
* The single required API key for the provider. This lets us support a terse
* initialization syntax:
*
* analytics.initialize({
* 'Provider' : 'XXXXXXX'
* });
*
* Only add this if the provider has a _single_ required key.
*/
key : undefined,
/**
* Initialize our provider.
*
* @param {Object} options - the settings for the provider.
* @param {Function} ready - a ready callback to call when we're ready to
* start accept analytics method calls.
*/
initialize : function (options, ready) {
ready();
},
/**
* Adds an item to the our internal pre-ready queue.
*
* @param {String} method - the analytics method to call (eg. 'track').
* @param {Object} args - the arguments to pass to the method.
*/
enqueue : function (method, args) {
this.queue.push({
method : method,
args : args
});
}
});
});
require.register("analytics/src/user.js", function(exports, require, module){
var bindAll = require('bind-all')
, clone = require('clone')
, cookie = require('./cookie')
, defaults = require('defaults')
, extend = require('extend')
, localStore = require('./localStore');
function User (options) {
this._id = null;
this._traits = {};
this.options(options);
}
/**
* Sets the options for the user
*
* @param {Object} options
* @field {Object} cookie
* @field {Object} localStorage
* @field {Boolean} persist (true)
*/
User.prototype.options = function (options) {
options || (options = {});
defaults(options, {
persist : true
});
this.cookie(options.cookie);
this.localStorage(options.localStorage);
this.persist = options.persist;
};
/**
* Get or set cookie options
*
* @param {Object} options
*/
User.prototype.cookie = function (options) {
if (arguments.length === 0) return this.cookieOptions;
options || (options = {});
defaults(options, {
key : 'ajs_user_id',
oldKey : 'ajs_user'
});
this.cookieOptions = options;
};
/**
* Get or set local storage options
*
* @param {Object} options
*/
User.prototype.localStorage = function (options) {
if (arguments.length === 0) return this.localStorageOptions;
options || (options = {});
defaults(options, {
key : 'ajs_user_traits'
});
this.localStorageOptions = options;
};
/**
* Get or set the user id
*
* @param {String} id
*/
User.prototype.id = function (id) {
if (arguments.length === 0) return this._id;
this._id = id;
};
/**
* Get or set the user traits
*
* @param {Object} traits
*/
User.prototype.traits = function (traits) {
if (arguments.length === 0) return clone(this._traits);
traits || (traits = {});
this._traits = traits;
};
/**
* Updates the current stored user with id and traits.
*
* @param {String} userId - the new user ID.
* @param {Object} traits - any new traits.
* @return {Boolean} whether alias should be called.
*/
User.prototype.update = function (userId, traits) {
// Make an alias call if there was no previous userId, there is one
// now, and we are using a cookie between page loads.
var alias = !this.id() && userId && this.persist;
traits || (traits = {});
// If there is a current user and the new user isn't the same,
// we want to just replace their traits. Otherwise extend.
if (this.id() && userId && this.id() !== userId) this.traits(traits);
else this.traits(extend(this.traits(), traits));
if (userId) this.id(userId);
this.save();
return alias;
};
/**
* Save the user to localstorage and cookie
*
* @return {Boolean} saved
*/
User.prototype.save = function () {
if (!this.persist) return false;
cookie.set(this.cookie().key, this.id());
localStore.set(this.localStorage().key, this.traits());
return true;
};
/**
* Loads a saved user, and set its information
*
* @return {Object} user
*/
User.prototype.load = function () {
if (this.loadOldCookie()) return this.toJSON();
var id = cookie.get(this.cookie().key)
, traits = localStore.get(this.localStorage().key);
this.id(id);
this.traits(traits);
return this.toJSON();
};
/**
* Clears the user, and removes the stored version
*
*/
User.prototype.clear = function () {
cookie.remove(this.cookie().key);
localStore.remove(this.localStorage().key);
this.id(null);
this.traits({});
};
/**
* Load the old user from the cookie. Should be phased
* out at some point
*
* @return {Boolean} loaded
*/
User.prototype.loadOldCookie = function () {
var user = cookie.get(this.cookie().oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this.cookie().oldKey);
return true;
};
/**
* Get the user info
*
* @return {Object}
*/
User.prototype.toJSON = function () {
return {
id : this.id(),
traits : this.traits()
};
};
/**
* Export the new user as a singleton.
*/
module.exports = bindAll(new User());
});
require.register("analytics/src/utils.js", function(exports, require, module){
// A helper to track events based on the 'anjs' url parameter
exports.getUrlParameter = function (urlSearchParameter, paramKey) {
var params = urlSearchParameter.replace('?', '').split('&');
for (var i = 0; i < params.length; i += 1) {
var param = params[i].split('=');
if (param.length === 2 && param[0] === paramKey) {
return decodeURIComponent(param[1]);
}
}
};
});
require.register("analytics/src/providers/adroll.js", function(exports, require, module){
// https://www.adroll.com/dashboard
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'AdRoll',
defaults : {
// Adroll requires two options: `advId` and `pixId`.
advId : null,
pixId : null
},
initialize : function (options, ready) {
window.adroll_adv_id = options.advId;
window.adroll_pix_id = options.pixId;
window.__adroll_loaded = true;
load({
http : 'http://a.adroll.com/j/roundtrip.js',
https : 'https://s.adroll.com/j/roundtrip.js'
}, ready);
}
});
});
require.register("analytics/src/providers/amplitude.js", function(exports, require, module){
// https://github.com/amplitude/Amplitude-Javascript
var Provider = require('../provider')
, alias = require('alias')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Amplitude',
key : 'apiKey',
defaults : {
// Amplitude's required API key.
apiKey : null,
// Whether to track pageviews to Amplitude.
pageview : false
},
initialize : function (options, ready) {
// Create the Amplitude global and queuer methods.
(function(e,t){var r=e.amplitude||{};
r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}
var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"];
for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);
// Load the Amplitude script and initialize with the API key.
load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js');
window.amplitude.init(options.apiKey);
// Amplitude creates a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
if (userId) window.amplitude.setUserId(userId);
if (traits) window.amplitude.setGlobalUserProperties(traits);
},
track : function (event, properties) {
window.amplitude.logEvent(event, properties);
},
pageview : function (url) {
if (!this.options.pageview) return;
var properties = {
url : url || document.location.href,
name : document.title
};
this.track('Loaded a Page', properties);
}
});
});
require.register("analytics/src/providers/bitdeli.js", function(exports, require, module){
// https://bitdeli.com/docs
// https://bitdeli.com/docs/javascript-api.html
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Bitdeli',
defaults : {
// BitDeli requires two options: `inputId` and `authToken`.
inputId : null,
authToken : null,
// Whether or not to track an initial pageview when the page first
// loads. You might not want this if you're using a single-page app.
initialPageview : true
},
initialize : function (options, ready) {
window._bdq = window._bdq || [];
window._bdq.push(["setAccount", options.inputId, options.authToken]);
if (options.initialPageview) this.pageview();
load('//d2flrkr957qc5j.cloudfront.net/bitdeli.min.js');
// Bitdeli just uses a queue, so it's ready right away.
ready();
},
// Bitdeli uses two separate methods: `identify` for storing the `userId`
// and `set` for storing `traits`.
identify : function (userId, traits) {
if (userId) window._bdq.push(['identify', userId]);
if (traits) window._bdq.push(['set', traits]);
},
track : function (event, properties) {
window._bdq.push(['track', event, properties]);
},
// If `url` is undefined, Bitdeli uses the current page URL instead.
pageview : function (url) {
window._bdq.push(['trackPageview', url]);
}
});
});
require.register("analytics/src/providers/bugherd.js", function(exports, require, module){
// http://support.bugherd.com/home
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'BugHerd',
key : 'apiKey',
defaults : {
apiKey : null,
// Optionally hide the feedback tab if you want to build your own.
// http://support.bugherd.com/entries/21497629-Create-your-own-Send-Feedback-tab
showFeedbackTab : true
},
initialize : function (options, ready) {
if (!options.showFeedbackTab) {
window.BugHerdConfig = { "feedback" : { "hide" : true } };
}
load('//www.bugherd.com/sidebarv2.js?apikey=' + options.apiKey, ready);
}
});
});
require.register("analytics/src/providers/chartbeat.js", function(exports, require, module){
// http://chartbeat.com/docs/adding_the_code/
// http://chartbeat.com/docs/configuration_variables/
// http://chartbeat.com/docs/handling_virtual_page_changes/
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Chartbeat',
defaults : {
// Chartbeat requires two options: `domain` and `uid`. All other
// configuration options are passed straight in!
domain : null,
uid : null
},
initialize : function (options, ready) {
// Since all the custom options just get passed through, update the
// Chartbeat `_sf_async_config` variable with options.
window._sf_async_config = options;
// Chartbeat's javascript should only load after the body
// is available, see https://github.com/segmentio/analytics.js/issues/107
var loadChartbeat = function () {
// We loop until the body is available.
if (!document.body) return setTimeout(loadChartbeat, 5);
// Use the stored date from when chartbeat was loaded.
window._sf_endpt = (new Date()).getTime();
// Load the Chartbeat javascript.
load({
https : 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js',
http : 'http://static.chartbeat.com/js/chartbeat.js'
}, ready);
};
loadChartbeat();
},
pageview : function (url) {
// In case the Chartbeat library hasn't loaded yet.
if (!window.pSUPERFLY) return;
// Requires a path, so default to the current one.
window.pSUPERFLY.virtualPage(url || window.location.pathname);
}
});
});
require.register("analytics/src/providers/clicktale.js", function(exports, require, module){
// http://wiki.clicktale.com/Article/JavaScript_API
var date = require('load-date')
, Provider = require('../provider')
, load = require('load-script')
, onBody = require('on-body');
module.exports = Provider.extend({
name : 'ClickTale',
key : 'projectId',
defaults : {
// If you sign up for a free account, this is the default http (non-ssl) CDN URL
// that you get. If you sign up for a premium account, you get a different
// custom CDN URL, so we have to leave it as an option.
httpCdnUrl : 'http://s.clicktale.net/WRe0.js',
// SSL support is only for premium accounts. Each premium account seems to have
// a different custom secure CDN URL, so we have to leave it as an option.
httpsCdnUrl : null,
// The Project ID is loaded in after the ClickTale CDN javascript has loaded.
projectId : null,
// The recording ratio specifies what fraction of people to screen-record.
// ClickTale has a special calculator in their setup flow that tells you
// what number to set for this.
recordingRatio : 0.01,
// The Partition ID determines where ClickTale stores the data according to
// http://wiki.clicktale.com/Article/JavaScript_API
partitionId : null
},
initialize : function (options, ready) {
// If we're on https:// but don't have a secure library, return early.
if (document.location.protocol === 'https:' && !options.httpsCdnUrl) return;
// ClickTale wants this at the "top" of the page. The analytics.js snippet
// sets this date synchronously now, and makes it available via load-date.
window.WRInitTime = date.getTime();
// Add the required ClickTale div to the body.
onBody(function (body) {
var div = document.createElement('div');
div.setAttribute('id', 'ClickTaleDiv');
div.setAttribute('style', 'display: none;');
body.appendChild(div);
});
var onloaded = function () {
window.ClickTale(
options.projectId,
options.recordingRatio,
options.partitionId
);
ready();
};
// If no SSL library is provided and we're on SSL then we can't load
// anything (always true for non-premium accounts).
load({
http : options.httpCdnUrl,
https : options.httpsCdnUrl
}, onloaded);
},
identify : function (userId, traits) {
// We set the userId as the ClickTale UID.
if (window.ClickTaleSetUID) window.ClickTaleSetUID(userId);
// We iterate over all the traits and set them as key-value field pairs.
if (window.ClickTaleField) {
for (var traitKey in traits) {
window.ClickTaleField(traitKey, traits[traitKey]);
}
}
},
track : function (event, properties) {
// ClickTaleEvent is an alias for ClickTaleTag
if (window.ClickTaleEvent) window.ClickTaleEvent(event);
}
});
});
require.register("analytics/src/providers/clicky.js", function(exports, require, module){
// http://clicky.com/help/customization/manual?new-domain
// http://clicky.com/help/customization/manual?new-domain#/help/customization#session
var Provider = require('../provider')
, user = require('../user')
, extend = require('extend')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Clicky',
key : 'siteId',
defaults : {
siteId : null
},
initialize : function (options, ready) {
window.clicky_site_ids = window.clicky_site_ids || [];
window.clicky_site_ids.push(options.siteId);
var userId = user.id()
, traits = user.traits()
, session = {};
if (userId) session.id = userId;
extend(session, traits);
window.clicky_custom = { session : session };
load('//static.getclicky.com/js', ready);
},
track : function (event, properties) {
window.clicky.log(window.location.href, event);
}
});
});
require.register("analytics/src/providers/comscore.js", function(exports, require, module){
// http://direct.comscore.com/clients/help/FAQ.aspx#faqTagging
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'comScore',
key : 'c2',
defaults : {
c1 : '2',
c2 : null
},
// Pass the entire options object directly into comScore.
initialize : function (options, ready) {
window._comscore = window._comscore || [];
window._comscore.push(options);
load({
http : 'http://b.scorecardresearch.com/beacon.js',
https : 'https://sb.scorecardresearch.com/beacon.js'
}, ready);
}
});
});
require.register("analytics/src/providers/crazyegg.js", function(exports, require, module){
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'CrazyEgg',
key : 'accountNumber',
defaults : {
accountNumber : null
},
initialize : function (options, ready) {
var accountPath = options.accountNumber.slice(0,4) + '/' + options.accountNumber.slice(4);
load('//dnn506yrbagrg.cloudfront.net/pages/scripts/'+accountPath+'.js?'+Math.floor(new Date().getTime()/3600000), ready);
}
});
});
require.register("analytics/src/providers/customerio.js", function(exports, require, module){
// http://customer.io/docs/api/javascript.html
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Customer.io',
key : 'siteId',
defaults : {
siteId : null
},
initialize : function (options, ready) {
var _cio = window._cio = window._cio || [];
(function() {
var a,b,c;
a = function (f) {
return function () {
_cio.push([f].concat(Array.prototype.slice.call(arguments,0)));
};
};
b = ['identify', 'track'];
for (c = 0; c < b.length; c++) {
_cio[b[c]] = a(b[c]);
}
})();
// Load the Customer.io script and add the required `id` and `data-site-id`.
var script = load('https://assets.customer.io/assets/track.js');
script.id = 'cio-tracker';
script.setAttribute('data-site-id', options.siteId);
// Since Customer.io creates their required methods in their snippet, we
// don't need to wait to be ready.
ready();
},
identify : function (userId, traits) {
// Don't do anything if we just have traits, because Customer.io
// requires a `userId`.
if (!userId) return;
// Customer.io takes the `userId` as part of the traits object.
traits.id = userId;
// Swap the `created` trait to the `created_at` that Customer.io needs
// and convert it from milliseconds to seconds.
if (traits.created) {
traits.created_at = Math.floor(traits.created/1000);
delete traits.created;
}
window._cio.identify(traits);
},
track : function (event, properties) {
window._cio.track(event, properties);
}
});
});
require.register("analytics/src/providers/errorception.js", function(exports, require, module){
// http://errorception.com/
var Provider = require('../provider')
, extend = require('extend')
, load = require('load-script')
, type = require('type');
module.exports = Provider.extend({
name : 'Errorception',
key : 'projectId',
defaults : {
projectId : null,
// Whether to store metadata about the user on `identify` calls, using
// the [Errorception `meta` API](http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html).
meta : true
},
initialize : function (options, ready) {
window._errs = window._errs || [options.projectId];
load('//d15qhc0lu1ghnk.cloudfront.net/beacon.js');
// Attach the window `onerror` event.
var oldOnError = window.onerror;
window.onerror = function () {
window._errs.push(arguments);
// Chain the old onerror handler after we finish our work.
if ('function' === type(oldOnError)) {
oldOnError.apply(this, arguments);
}
};
// Errorception makes a queue, so it's ready immediately.
ready();
},
// Add the traits to the Errorception meta object.
identify : function (userId, traits) {
if (!this.options.meta) return;
// If the custom metadata object hasn't ever been made, make it.
window._errs.meta || (window._errs.meta = {});
// Add `userId` to traits.
traits.id = userId;
// Add all of the traits as metadata.
extend(window._errs.meta, traits);
}
});
});
require.register("analytics/src/providers/foxmetrics.js", function(exports, require, module){
// http://foxmetrics.com/documentation/apijavascript
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'FoxMetrics',
key : 'appId',
defaults : {
appId : null
},
initialize : function (options, ready) {
var _fxm = window._fxm || {};
window._fxm = _fxm.events || [];
load('//d35tca7vmefkrc.cloudfront.net/scripts/' + options.appId + '.js');
// FoxMetrics makes a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
// A `userId` is required for profile updates.
if (!userId) return;
// FoxMetrics needs the first and last name seperately. Fallback to
// splitting the `name` trait if we don't have what we need.
var firstName = traits.firstName
, lastName = traits.lastName;
if (!firstName && traits.name) firstName = traits.name.split(' ')[0];
if (!lastName && traits.name) lastName = traits.name.split(' ')[1];
window._fxm.push([
'_fxm.visitor.profile',
userId, // user id
firstName, // first name
lastName, // last name
traits.email, // email
traits.address, // address
undefined, // social
undefined, // partners
traits // attributes
]);
},
track : function (event, properties) {
window._fxm.push([
event, // event name
properties.category, // category
properties // properties
]);
},
pageview : function (url) {
window._fxm.push([
'_fxm.pages.view',
undefined, // title
undefined, // name
undefined, // category
url, // url
undefined // referrer
]);
}
});
});
require.register("analytics/src/providers/gauges.js", function(exports, require, module){
// http://get.gaug.es/documentation/tracking/
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Gauges',
key : 'siteId',
defaults : {
siteId : null
},
initialize : function (options, ready) {
window._gauges = window._gauges || [];
var script = load('//secure.gaug.es/track.js');
// Gauges needs a few attributes on its script element.
script.id = 'gauges-tracker';
script.setAttribute('data-site-id', options.siteId);
// Gauges make a queue so it's ready immediately.
ready();
},
pageview : function (url) {
window._gauges.push(['track']);
}
});
});
require.register("analytics/src/providers/get-satisfaction.js", function(exports, require, module){
// You have to be signed in to access the snippet code:
// https://console.getsatisfaction.com/start/101022?signup=true#engage
var Provider = require('../provider')
, load = require('load-script')
, onBody = require('on-body');
module.exports = Provider.extend({
name : 'Get Satisfaction',
key : 'widgetId',
defaults : {
widgetId : null
},
initialize : function (options, ready) {
// Get Satisfaction requires a div that will become their widget tab. Append
// it once `document.body` exists.
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + options.widgetId;
onBody(function (body) {
body.appendChild(div);
});
// Usually they load their snippet synchronously, so we need to wait for it
// to come back before initializing the tab.
load('https://loader.engage.gsfn.us/loader.js', function () {
if (window.GSFN !== undefined) {
window.GSFN.loadWidget(options.widgetId, { containerId : id });
}
ready();
});
}
});
});
require.register("analytics/src/providers/google-analytics.js", function(exports, require, module){
// https://developers.google.com/analytics/devguides/collection/gajs/
var Provider = require('../provider')
, load = require('load-script')
, type = require('type')
, url = require('url')
, canonical = require('canonical');
module.exports = Provider.extend({
name : 'Google Analytics',
key : 'trackingId',
defaults : {
// Whether to anonymize the IP address collected for the user.
anonymizeIp : false,
// An optional domain setting, to restrict where events can originate from.
domain : null,
// Whether to enable GOogle's DoubleClick remarketing feature.
doubleClick : false,
// Whether to use Google Analytics's Enhanced Link Attribution feature:
// http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
enhancedLinkAttribution : false,
// A domain to ignore for referrers. Maps to _addIgnoredRef
ignoreReferrer : null,
// Whether or not to track and initial pageview when initialized.
initialPageview : true,
// The setting to use for Google Analytics's Site Speed Sample Rate feature:
// https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
siteSpeedSampleRate : null,
// Your Google Analytics Tracking ID.
trackingId : null,
// Whether you're using the new Universal Analytics or not.
universalClient: false
},
initialize : function (options, ready) {
if (options.universalClient) this.initializeUniversal(options, ready);
else this.initializeClassic(options, ready);
},
initializeClassic: function (options, ready) {
window._gaq = window._gaq || [];
window._gaq.push(['_setAccount', options.trackingId]);
// Apply a bunch of optional settings.
if (options.domain) {
window._gaq.push(['_setDomainName', options.domain]);
}
if (options.enhancedLinkAttribution) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
window._gaq.push(['_require', 'inpage_linkid', pluginUrl]);
}
if (type(options.siteSpeedSampleRate) === 'number') {
window._gaq.push(['_setSiteSpeedSampleRate', options.siteSpeedSampleRate]);
}
if (options.anonymizeIp) {
window._gaq.push(['_gat._anonymizeIp']);
}
if (options.ignoreReferrer) {
window._gaq.push(['_addIgnoredRef', options.ignoreReferrer]);
}
if (options.initialPageview) {
var path, canon = canonical();
if (canon) path = url.parse(canon).pathname;
this.pageview(path);
}
// URLs change if DoubleClick is on. Even though Google Analytics makes a
// queue, the `_gat` object isn't available until the library loads.
if (options.doubleClick) {
load('//stats.g.doubleclick.net/dc.js', ready);
} else {
load({
http : 'http://www.google-analytics.com/ga.js',
https : 'https://ssl.google-analytics.com/ga.js'
}, ready);
}
},
initializeUniversal: function (options, ready) {
// GA-universal lets you set your own queue name
var global = this.global = 'ga';
// and needs to know about this queue name in this special object
// so that future plugins can also operate on the object
window['GoogleAnalyticsObject'] = global;
// setup the global variable
window[global] = window[global] || function () {
(window[global].q = window[global].q || []).push(arguments);
};
// GA also needs to know the current time (all from their snippet)
window[global].l = 1 * new Date();
var createOpts = {};
// Apply a bunch of optional settings.
if (options.domain)
createOpts.cookieDomain = options.domain || 'none';
if (type(options.siteSpeedSampleRate) === 'number')
createOpts.siteSpeedSampleRate = options.siteSpeedSampleRate;
if (options.anonymizeIp)
ga('set', 'anonymizeIp', true);
ga('create', options.trackingId, createOpts);
if (options.initialPageview) {
var path, canon = canonical();
if (canon) path = url.parse(canon).pathname;
this.pageview(path);
}
load('//www.google-analytics.com/analytics.js');
// Google makes a queue so it's ready immediately.
ready();
},
track : function (event, properties) {
properties || (properties = {});
var value;
// Since value is a common property name, ensure it is a number and Google
// requires that it be an integer.
if (type(properties.value) === 'number') value = Math.round(properties.value);
// Try to check for a `category` and `label`. A `category` is required,
// so if it's not there we use `'All'` as a default. We can safely push
// undefined if the special properties don't exist. Try using revenue
// first, but fall back to a generic `value` as well.
if (this.options.universalClient) {
var opts = {};
if (properties.noninteraction) opts.nonInteraction = properties.noninteraction;
window[this.global](
'send',
'event',
properties.category || 'All',
event,
properties.label,
Math.round(properties.revenue) || value,
opts
);
} else {
window._gaq.push([
'_trackEvent',
properties.category || 'All',
event,
properties.label,
Math.round(properties.revenue) || value,
properties.noninteraction
]);
}
},
pageview : function (url) {
if (this.options.universalClient) {
window[this.global]('send', 'pageview', url);
} else {
window._gaq.push(['_trackPageview', url]);
}
}
});
});
require.register("analytics/src/providers/gosquared.js", function(exports, require, module){
// http://www.gosquared.com/support
// https://www.gosquared.com/customer/portal/articles/612063-tracker-functions
var Provider = require('../provider')
, user = require('../user')
, load = require('load-script')
, onBody = require('on-body');
module.exports = Provider.extend({
name : 'GoSquared',
key : 'siteToken',
defaults : {
siteToken : null
},
initialize : function (options, ready) {
// GoSquared assumes a body in their script, so we need this wrapper.
onBody(function () {
var GoSquared = window.GoSquared = {};
GoSquared.acct = options.siteToken;
GoSquared.q = [];
window._gstc_lt =+ (new Date());
GoSquared.VisitorName = user.id();
GoSquared.Visitor = user.traits();
load('//d1l6p2sc9645hc.cloudfront.net/tracker.js');
// GoSquared makes a queue, so it's ready immediately.
ready();
});
},
identify : function (userId, traits) {
// TODO figure out if this will actually work. Seems like GoSquared will
// never know these values are updated.
if (userId) window.GoSquared.UserName = userId;
if (traits) window.GoSquared.Visitor = traits;
},
track : function (event, properties) {
// GoSquared sets a `gs_evt_name` property with a value of the event
// name, so it relies on properties being an object.
window.GoSquared.q.push(['TrackEvent', event, properties || {}]);
},
pageview : function (url) {
window.GoSquared.q.push(['TrackView', url]);
}
});
});
require.register("analytics/src/providers/heap.js", function(exports, require, module){
// https://heapanalytics.com/docs
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Heap',
key : 'apiKey',
defaults : {
apiKey : null
},
initialize : function (options, ready) {
window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var b=document.createElement("script");b.type="text/javascript",b.async=!0,b.src=("https:"===document.location.protocol?"https:":"http:")+"//d36lvucg9kzous.cloudfront.net";var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c);var d=function(a){return function(){heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)heap[e[f]]=d(e[f])};
window.heap.load(options.apiKey);
// heap creates its own queue, so we're ready right away
ready();
},
identify : function (userId, traits) {
window.heap.identify(traits);
},
track : function (event, properties) {
window.heap.track(event, properties);
}
});
});
require.register("analytics/src/providers/hittail.js", function(exports, require, module){
// http://www.hittail.com
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'HitTail',
key : 'siteId',
defaults : {
siteId : null
},
initialize : function (options, ready) {
load('//' + options.siteId + '.hittail.com/mlt.js', ready);
}
});
});
require.register("analytics/src/providers/hubspot.js", function(exports, require, module){
// http://hubspot.clarify-it.com/d/4m62hl
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'HubSpot',
key : 'portalId',
defaults : {
portalId : null
},
initialize : function (options, ready) {
// HubSpot checks in their snippet to make sure another script with
// `hs-analytics` isn't already in the DOM. Seems excessive, but who knows
// if there's weird deprecation going on :p
if (!document.getElementById('hs-analytics')) {
window._hsq = window._hsq || [];
var script = load('https://js.hubspot.com/analytics/' + (Math.ceil(new Date()/300000)*300000) + '/' + options.portalId + '.js');
script.id = 'hs-analytics';
}
// HubSpot makes a queue, so it's ready immediately.
ready();
},
// HubSpot does not use a userId, but the email address is required on
// the traits object.
identify : function (userId, traits) {
window._hsq.push(["identify", traits]);
},
// Event Tracking is available to HubSpot Enterprise customers only. In
// addition to adding any unique event name, you can also use the id of an
// existing custom event as the event variable.
track : function (event, properties) {
window._hsq.push(["trackEvent", event, properties]);
},
// HubSpot doesn't support passing in a custom URL.
pageview : function (url) {
window._hsq.push(['_trackPageview']);
}
});
});
require.register("analytics/src/providers/index.js", function(exports, require, module){
module.exports = [
require('./adroll'),
require('./amplitude'),
require('./bitdeli'),
require('./bugherd'),
require('./chartbeat'),
require('./clicktale'),
require('./clicky'),
require('./comscore'),
require('./crazyegg'),
require('./customerio'),
require('./errorception'),
require('./foxmetrics'),
require('./gauges'),
require('./get-satisfaction'),
require('./google-analytics'),
require('./gosquared'),
require('./heap'),
require('./hittail'),
require('./hubspot'),
require('./improvely'),
require('./intercom'),
require('./keen-io'),
require('./kissmetrics'),
require('./klaviyo'),
require('./livechat'),
require('./lytics'),
require('./mixpanel'),
require('./olark'),
require('./optimizely'),
require('./perfect-audience'),
require('./pingdom'),
require('./preact'),
require('./qualaroo'),
require('./quantcast'),
require('./sentry'),
require('./snapengage'),
require('./usercycle'),
require('./userfox'),
require('./uservoice'),
require('./vero'),
require('./visual-website-optimizer'),
require('./woopra')
];
});
require.register("analytics/src/providers/improvely.js", function(exports, require, module){
// http://www.improvely.com/docs/landing-page-code
// http://www.improvely.com/docs/conversion-code
// http://www.improvely.com/docs/labeling-visitors
var Provider = require('../provider')
, alias = require('alias')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Improvely',
defaults : {
// Improvely requires two options: `domain` and `projectId`.
domain : null,
projectId : null
},
initialize : function (options, ready) {
window._improvely = window._improvely || [];
window.improvely = window.improvely || {
init : function (e, t) { window._improvely.push(["init", e, t]); },
goal : function (e) { window._improvely.push(["goal", e]); },
label : function (e) { window._improvely.push(["label", e]); }
};
load('//' + options.domain + '.iljmp.com/improvely.js');
window.improvely.init(options.domain, options.projectId);
// Improvely creates a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
if (userId) window.improvely.label(userId);
},
track : function (event, properties) {
// Improvely calls `revenue` `amount`, and puts the `event` in properties as
// the `type`.
properties || (properties = {});
properties.type = event;
alias(properties, { 'revenue' : 'amount' });
window.improvely.goal(properties);
}
});
});
require.register("analytics/src/providers/intercom.js", function(exports, require, module){
// http://docs.intercom.io/
// http://docs.intercom.io/#IntercomJS
var Provider = require('../provider')
, extend = require('extend')
, load = require('load-script')
, isEmail = require('is-email');
module.exports = Provider.extend({
name : 'Intercom',
// Whether Intercom has already been booted or not. Intercom becomes booted
// after Intercom('boot', ...) has been called on the first identify.
booted : false,
key : 'appId',
defaults : {
// Intercom's required key.
appId : null,
// An optional setting to display the Intercom inbox widget.
activator : null,
// Whether to show the count of messages for the inbox widget.
counter : true
},
initialize : function (options, ready) {
load('https://static.intercomcdn.com/intercom.v1.js', ready);
},
identify : function (userId, traits, options) {
// Don't do anything if we just have traits the first time.
if (!this.booted && !userId) return;
// Intercom specific settings. BACKWARDS COMPATIBILITY: we need to check for
// the lowercase variant as well.
options || (options = {});
var Intercom = options.Intercom || options.intercom || {};
traits.increments = Intercom.increments;
traits.user_hash = Intercom.userHash || Intercom.user_hash;
// They need `created_at` as a Unix timestamp (seconds).
if (traits.created) {
traits.created_at = Math.floor(traits.created/1000);
delete traits.created;
}
// Convert a `company`'s `created` date.
if (traits.company && traits.company.created) {
traits.company.created_at = Math.floor(traits.company.created/1000);
delete traits.company.created;
}
// Optionally add the inbox widget.
if (this.options.activator) {
traits.widget = {
activator : this.options.activator,
use_counter : this.options.counter
};
}
// If this is the first time we've identified, `boot` instead of `update`
// and add our one-time boot settings.
if (this.booted) {
window.Intercom('update', traits);
} else {
extend(traits, {
app_id : this.options.appId,
user_id : userId
});
window.Intercom('boot', traits);
}
// Set the booted state, so that we know to call 'update' next time.
this.booted = true;
},
// Intercom doesn't have a separate `group` method, but they take a
// `companies` trait for the user.
group : function (groupId, properties, options) {
properties.id = groupId;
window.Intercom('update', { company : properties });
}
});
});
require.register("analytics/src/providers/keen-io.js", function(exports, require, module){
// https://keen.io/docs/
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Keen IO',
defaults : {
// The Project ID is **required**.
projectId : null,
// The Write Key is **required** to send events.
writeKey : null,
// The Read Key is optional, only if you want to "do analysis".
readKey : null,
// Whether or not to pass pageviews on to Keen IO.
pageview : true,
// Whether or not to track an initial pageview on `initialize`.
initialPageview : true
},
initialize : function (options, ready) {
window.Keen = window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};
window.Keen.configure({
projectId : options.projectId,
writeKey : options.writeKey,
readKey : options.readKey
});
load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js');
if (options.initialPageview) this.pageview();
// Keen IO defines all their functions in the snippet, so they're ready.
ready();
},
identify : function (userId, traits) {
// Use Keen IO global properties to include `userId` and `traits` on
// every event sent to Keen IO.
var globalUserProps = {};
if (userId) globalUserProps.userId = userId;
if (traits) globalUserProps.traits = traits;
if (userId || traits) {
window.Keen.setGlobalProperties(function(eventCollection) {
return { user: globalUserProps };
});
}
},
track : function (event, properties) {
window.Keen.addEvent(event, properties);
},
pageview : function (url) {
if (!this.options.pageview) return;
var properties = {
url : url || document.location.href,
name : document.title
};
this.track('Loaded a Page', properties);
}
});
});
require.register("analytics/src/providers/kissmetrics.js", function(exports, require, module){
// http://support.kissmetrics.com/apis/javascript
var Provider = require('../provider')
, alias = require('alias')
, load = require('load-script');
module.exports = Provider.extend({
name : 'KISSmetrics',
key : 'apiKey',
defaults : {
apiKey : null
},
initialize : function (options, ready) {
window._kmq = window._kmq || [];
load('//i.kissmetrics.com/i.js');
load('//doug1izaerwt3.cloudfront.net/' + options.apiKey + '.1.js');
// KISSmetrics creates a queue, so it's ready immediately.
ready();
},
// KISSmetrics uses two separate methods: `identify` for storing the
// `userId`, and `set` for storing `traits`.
identify : function (userId, traits) {
if (userId) window._kmq.push(['identify', userId]);
if (traits) window._kmq.push(['set', traits]);
},
track : function (event, properties) {
// KISSmetrics handles revenue with the `'Billing Amount'` property by
// default, although it's changeable in the interface.
if (properties) {
alias(properties, {
'revenue' : 'Billing Amount'
});
}
window._kmq.push(['record', event, properties]);
},
// Although undocumented, KISSmetrics actually supports not passing a second
// ID, in which case it uses the currenty identified user's ID.
alias : function (newId, originalId) {
window._kmq.push(['alias', newId, originalId]);
}
});
});
require.register("analytics/src/providers/klaviyo.js", function(exports, require, module){
// https://www.klaviyo.com/docs
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Klaviyo',
key : 'apiKey',
defaults : {
apiKey : null
},
initialize : function (options, ready) {
window._learnq = window._learnq || [];
window._learnq.push(['account', options.apiKey]);
load('//a.klaviyo.com/media/js/learnmarklet.js');
// Klaviyo creats a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
// Klaviyo requires a `userId` and takes the it on the traits object itself.
if (!userId) return;
traits.$id = userId;
window._learnq.push(['identify', traits]);
},
track : function (event, properties) {
window._learnq.push(['track', event, properties]);
}
});
});
require.register("analytics/src/providers/livechat.js", function(exports, require, module){
// http://www.livechatinc.com/api/javascript-api
var Provider = require('../provider')
, each = require('each')
, load = require('load-script');
module.exports = Provider.extend({
name : 'LiveChat',
key : 'license',
defaults : {
license : null
},
initialize : function (options, ready) {
window.__lc = { license : options.license };
load('//cdn.livechatinc.com/tracking.js', ready);
},
// LiveChat isn't an analytics service, but we can use the `userId` and
// `traits` to tag the user with their real name in the chat console.
identify : function (userId, traits) {
// In case the LiveChat library hasn't loaded yet.
if (!window.LC_API) return;
// LiveChat takes them in an array format.
var variables = [];
if (userId) variables.push({ name: 'User ID', value: userId });
if (traits) {
each(traits, function (key, value) {
variables.push({
name : key,
value : value
});
});
}
window.LC_API.set_custom_variables(variables);
}
});
});
require.register("analytics/src/providers/lytics.js", function(exports, require, module){
// Lytics
// --------
// [Documentation](http://developer.lytics.io/doc#jstag),
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Lytics',
key : 'cid',
defaults : {
cid: null
},
initialize : function (options, ready) {
window.jstag = (function () {
var t={_q:[],_c:{cid:options.cid,url:'//c.lytics.io'},ts:(new Date()).getTime()};
t.send=function(){
this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);
return this;
};
return t;
})();
load('//c.lytics.io/static/io.min.js');
ready();
},
identify: function (userId, traits) {
traits._uid = userId;
window.jstag.send(traits);
},
track: function (event, properties) {
properties._e = event;
window.jstag.send(properties);
},
pageview: function (url) {
window.jstag.send();
}
});
});
require.register("analytics/src/providers/mixpanel.js", function(exports, require, module){
// https://mixpanel.com/docs/integration-libraries/javascript
// https://mixpanel.com/docs/people-analytics/javascript
// https://mixpanel.com/docs/integration-libraries/javascript-full-api
var Provider = require('../provider')
, alias = require('alias')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Mixpanel',
key : 'token',
defaults : {
// Whether to call `mixpanel.nameTag` on `identify`.
nameTag : true,
// Whether to use Mixpanel's People API.
people : false,
// The Mixpanel API token for your account.
token : null,
// Whether to track pageviews to Mixpanel.
pageview : false,
// Whether to track an initial pageview on initialize.
initialPageview : false
},
initialize : function (options, ready) {
(function (c, a) {
window.mixpanel = a;
var b, d, h, e;
a._i = [];
a.init = function (b, c, f) {
function d(a, b) {
var c = b.split('.');
2 == c.length && (a = a[c[0]], b = c[1]);
a[b] = function () {
a.push([b].concat(Array.prototype.slice.call(arguments, 0)));
};
}
var g = a;
'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel';
g.people = g.people || [];
h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append'];
for (e = 0; e < h.length; e++) d(g, h[e]);
a._i.push([b, c, f]);
};
a.__SV = 1.2;
// Modification to the snippet: call ready whenever the library has
// fully loaded.
load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', ready);
})(document, window.mixpanel || []);
// Pass options directly to `init` as the second argument.
window.mixpanel.init(options.token, options);
if (options.initialPageview) this.pageview();
},
identify : function (userId, traits) {
// Alias the traits' keys with dollar signs for Mixpanel's API.
alias(traits, {
'created' : '$created',
'email' : '$email',
'firstName' : '$first_name',
'lastName' : '$last_name',
'lastSeen' : '$last_seen',
'name' : '$name',
'username' : '$username',
'phone' : '$phone'
});
// Finally, call all of the identify equivalents. Verify certain calls
// against options to make sure they're enabled.
if (userId) {
window.mixpanel.identify(userId);
if (this.options.nameTag) window.mixpanel.name_tag(traits && traits.$email || userId);
}
if (traits) {
window.mixpanel.register(traits);
if (this.options.people) window.mixpanel.people.set(traits);
}
},
track : function (event, properties) {
window.mixpanel.track(event, properties);
// Mixpanel handles revenue with a `transaction` call in their People
// feature. So if we're using people, record a transcation.
if (properties && properties.revenue && this.options.people) {
window.mixpanel.people.track_charge(properties.revenue);
}
},
// Mixpanel doesn't actually track the pageviews, but they do show up in the
// Mixpanel stream.
pageview : function (url) {
window.mixpanel.track_pageview(url);
// If they don't want pageviews tracked, leave now.
if (!this.options.pageview) return;
var properties = {
url : url || document.location.href,
name : document.title
};
this.track('Loaded a Page', properties);
},
// Although undocumented, Mixpanel actually supports the `originalId`. It
// just usually defaults to the current user's `distinct_id`.
alias : function (newId, originalId) {
if(window.mixpanel.get_distinct_id &&
window.mixpanel.get_distinct_id() === newId) return;
// HACK: internal mixpanel API to ensure we don't overwrite.
if(window.mixpanel.get_property &&
window.mixpanel.get_property('$people_distinct_id') === newId) return;
window.mixpanel.alias(newId, originalId);
}
});
});
require.register("analytics/src/providers/olark.js", function(exports, require, module){
// http://www.olark.com/documentation
var Provider = require('../provider')
, isEmail = require('is-email');
module.exports = Provider.extend({
name : 'Olark',
key : 'siteId',
chatting : false,
defaults : {
siteId : null,
// Whether to use the user's name or email in the Olark chat console.
identify : true,
// Whether to log pageviews to the Olark chat console.
track : false,
// Whether to log pageviews to the Olark chat console.
pageview : true
},
initialize : function (options, ready) {
window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
window.olark.identify(options.siteId);
// Set up event handlers for chat box open and close so that
// we know whether a conversation is active. If it is active,
// then we'll send track and pageview information.
var self = this;
window.olark('api.box.onExpand', function () { self.chatting = true; });
window.olark('api.box.onShrink', function () { self.chatting = false; });
// Olark creates it's method in the snippet, so it's ready immediately.
ready();
},
// Update traits about the user in Olark to make the operator's life easier.
identify : function (userId, traits) {
if (!this.options.identify) return;
var email = traits.email
, name = traits.name || traits.firstName
, phone = traits.phone
, nickname = name || email || userId;
// If we have a name and an email, add the email too to be more helpful.
if (name && email) nickname += ' ('+email+')';
// Call all of Olark's settings APIs.
window.olark('api.visitor.updateCustomFields', traits);
if (email) window.olark('api.visitor.updateEmailAddress', { emailAddress : email });
if (name) window.olark('api.visitor.updateFullName', { fullName : name });
if (phone) window.olark('api.visitor.updatePhoneNumber', { phoneNumber : phone });
if (nickname) window.olark('api.chat.updateVisitorNickname', { snippet : nickname });
},
// Log events the user triggers to the chat console, if you so desire it.
track : function (event, properties) {
if (!this.options.track || !this.chatting) return;
// To stay consistent with olark's default messages, it's all lowercase.
window.olark('api.chat.sendNotificationToOperator', {
body : 'visitor triggered "'+event+'"'
});
},
// Mimic the functionality Olark has for normal pageviews with pseudo-
// pageviews, telling the operator when a visitor changes pages.
pageview : function (url) {
if (!this.options.pageview || !this.chatting) return;
// To stay consistent with olark's default messages, it's all lowercase.
window.olark('api.chat.sendNotificationToOperator', {
body : 'looking at ' + window.location.href
});
}
});
});
require.register("analytics/src/providers/optimizely.js", function(exports, require, module){
// https://www.optimizely.com/docs/api
var each = require('each')
, nextTick = require('next-tick')
, Provider = require('../provider');
module.exports = Provider.extend({
name : 'Optimizely',
defaults : {
// Whether to replay variations into other enabled integrations as traits.
variations : true
},
initialize : function (options, ready, analytics) {
// Create the `optimizely` object in case it doesn't exist already.
// https://www.optimizely.com/docs/api#function-calls
window.optimizely = window.optimizely || [];
// If the `variations` option is true, replay our variations on the next
// tick to wait for the entire library to be ready for replays.
if (options.variations) {
var self = this;
nextTick(function () { self.replay(); });
}
// Optimizely should be on the page already, so it's always ready.
ready();
},
track : function (event, properties) {
// Optimizely takes revenue as cents, not dollars.
if (properties && properties.revenue) properties.revenue = properties.revenue * 100;
window.optimizely.push(['trackEvent', event, properties]);
},
replay : function () {
// Make sure we have access to Optimizely's `data` dictionary.
var data = window.optimizely.data;
if (!data) return;
// Grab a few pieces of data we'll need for replaying.
var experiments = data.experiments
, variationNamesMap = data.state.variationNamesMap;
// Create our traits object to add variations to.
var traits = {};
// Loop through all the experiement the user has been assigned a variation
// for and add them to our traits.
each(variationNamesMap, function (experimentId, variation) {
traits['Experiment: ' + experiments[experimentId].name] = variation;
});
this.analytics.identify(traits);
}
});
});
require.register("analytics/src/providers/perfect-audience.js", function(exports, require, module){
// https://www.perfectaudience.com/docs#javascript_api_autoopen
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Perfect Audience',
key : 'siteId',
defaults : {
siteId : null
},
initialize : function (options, ready) {
window._pa || (window._pa = {});
load('//tag.perfectaudience.com/serve/' + options.siteId + '.js', ready);
},
track : function (event, properties) {
window._pa.track(event, properties);
}
});
});
require.register("analytics/src/providers/pingdom.js", function(exports, require, module){
var date = require('load-date')
, Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Pingdom',
key : 'id',
defaults : {
id : null
},
initialize : function (options, ready) {
window._prum = [
['id', options.id],
['mark', 'firstbyte', date.getTime()]
];
// We've replaced the original snippet loader with our own load method.
load('//rum-static.pingdom.net/prum.min.js', ready);
}
});
});
require.register("analytics/src/providers/preact.js", function(exports, require, module){
// http://www.preact.io/api/javascript
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Preact',
key : 'projectCode',
defaults : {
projectCode : null
},
initialize : function (options, ready) {
var _lnq = window._lnq = window._lnq || [];
_lnq.push(["_setCode", options.projectCode]);
load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js');
ready();
},
identify : function (userId, traits) {
// Don't do anything if we just have traits. Preact requires a `userId`.
if (!userId) return;
// Swap the `created` trait to the `created_at` that Preact needs
// and convert it from milliseconds to seconds.
if (traits.created) {
traits.created_at = Math.floor(traits.created/1000);
delete traits.created;
}
window._lnq.push(['_setPersonData', {
name : traits.name,
email : traits.email,
uid : userId,
properties : traits
}]);
},
group : function (groupId, properties) {
if (!groupId) return;
properties.id = groupId;
window._lnq.push(['_setAccount', properties]);
},
track : function (event, properties) {
properties || (properties = {});
// Preact takes a few special properties, and the rest in `extras`. So first
// convert and remove the special ones from `properties`.
var special = { name : event };
// They take `revenue` in cents.
if (properties.revenue) {
special.revenue = properties.revenue * 100;
delete properties.revenue;
}
if (properties.note) {
special.note = properties.note;
delete properties.note;
}
window._lnq.push(['_logEvent', special, properties]);
}
});
});
require.register("analytics/src/providers/qualaroo.js", function(exports, require, module){
// http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
// http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Qualaroo',
defaults : {
// Qualaroo has two required options.
customerId : null,
siteToken : null,
// Whether to record traits when a user triggers an event. This can be
// useful for sending targetted questionnaries.
track : false
},
// Qualaroo's script has two options in its URL.
initialize : function (options, ready) {
window._kiq = window._kiq || [];
load('//s3.amazonaws.com/ki.js/' + options.customerId + '/' + options.siteToken + '.js');
// Qualaroo creates a queue, so it's ready immediately.
ready();
},
// Qualaroo uses two separate methods: `identify` for storing the `userId`,
// and `set` for storing `traits`.
identify : function (userId, traits) {
var identity = traits.email || userId;
if (identity) window._kiq.push(['identify', identity]);
if (traits) window._kiq.push(['set', traits]);
},
// Qualaroo doesn't have `track` method yet, but to allow the users to do
// targetted questionnaires we can set name-value pairs on the user properties
// that apply to the current visit.
track : function (event, properties) {
if (!this.options.track) return;
// Create a name-value pair that will be pretty unique. For an event like
// 'Loaded a Page' this will make it 'Triggered: Loaded a Page'.
var traits = {};
traits['Triggered: ' + event] = true;
// Fire a normal identify, with traits only.
this.identify(null, traits);
}
});
});
require.register("analytics/src/providers/quantcast.js", function(exports, require, module){
// https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Quantcast',
key : 'pCode',
defaults : {
pCode : null
},
initialize : function (options, ready) {
window._qevents = window._qevents || [];
window._qevents.push({ qacct: options.pCode });
load({
http : 'http://edge.quantserve.com/quant.js',
https : 'https://secure.quantserve.com/quant.js'
}, ready);
}
});
});
require.register("analytics/src/providers/sentry.js", function(exports, require, module){
// http://raven-js.readthedocs.org/en/latest/config/index.html
var Provider = require('../provider')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Sentry',
key : 'config',
defaults : {
config : null
},
initialize : function (options, ready) {
load('//d3nslu0hdya83q.cloudfront.net/dist/1.0/raven.min.js', function () {
// For now, Raven basically requires `install` to be called.
// https://github.com/getsentry/raven-js/blob/master/src/raven.js#L87
window.Raven.config(options.config).install();
ready();
});
},
identify : function (userId, traits) {
traits.id = userId;
window.Raven.setUser(traits);
},
// Raven will automatically use `captureMessage` if the error is a string.
log : function (error, properties) {
window.Raven.captureException(error, properties);
}
});
});
require.register("analytics/src/providers/snapengage.js", function(exports, require, module){
// http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'SnapEngage',
key : 'apiKey',
defaults : {
apiKey : null
},
initialize : function (options, ready) {
load('//commondatastorage.googleapis.com/code.snapengage.com/js/' + options.apiKey + '.js', ready);
},
// Set the email in the chat window if we have it.
identify : function (userId, traits, options) {
if (!traits.email) return;
window.SnapABug.setUserEmail(traits.email);
}
});
});
require.register("analytics/src/providers/usercycle.js", function(exports, require, module){
// http://docs.usercycle.com/javascript_api
var Provider = require('../provider')
, load = require('load-script')
, user = require('../user');
module.exports = Provider.extend({
name : 'USERcycle',
key : 'key',
defaults : {
key : null
},
initialize : function (options, ready) {
window._uc = window._uc || [];
window._uc.push(['_key', options.key]);
load('//api.usercycle.com/javascripts/track.js');
// USERcycle makes a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
if (userId) window._uc.push(['uid', userId]);
// USERcycle has a special "hidden" event that is used just for retention measurement.
// Lukas suggested on 6/4/2013 that we send traits on that event, since they use the
// the latest value of every event property as a "trait"
window._uc.push(['action', 'came_back', traits]);
},
track : function (event, properties) {
window._uc.push(['action', event, properties]);
}
});
});
require.register("analytics/src/providers/userfox.js", function(exports, require, module){
// https://www.userfox.com/docs/
var Provider = require('../provider')
, extend = require('extend')
, load = require('load-script')
, isEmail = require('is-email');
module.exports = Provider.extend({
name : 'userfox',
key : 'clientId',
defaults : {
// userfox's required key.
clientId : null
},
initialize : function (options, ready) {
window._ufq = window._ufq || [];
load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js');
// userfox creates its own queue, so we're ready right away.
ready();
},
identify : function (userId, traits) {
if (!traits.email) return;
// Initialize the library with the email now that we have it.
window._ufq.push(['init', {
clientId : this.options.clientId,
email : traits.email
}]);
// Record traits to "track" if we have the required signup date `created`.
// userfox takes `signup_date` as a string of seconds since the epoch.
if (traits.created) {
traits.signup_date = (traits.created.getTime() / 1000).toString();
delete traits.created;
window._ufq.push(['track', traits]);
}
}
});
});
require.register("analytics/src/providers/uservoice.js", function(exports, require, module){
// http://feedback.uservoice.com/knowledgebase/articles/225-how-do-i-pass-custom-data-through-the-widget-and-i
var Provider = require('../provider')
, load = require('load-script')
, alias = require('alias')
, clone = require('clone');
module.exports = Provider.extend({
name : 'UserVoice',
defaults : {
// These first two options are required.
widgetId : null,
forumId : null,
// Should we show the tab automatically?
showTab : true,
// There's tons of options for the tab.
mode : 'full',
primaryColor : '#cc6d00',
linkColor : '#007dbf',
defaultMode : 'support',
tabLabel : 'Feedback & Support',
tabColor : '#cc6d00',
tabPosition : 'middle-right',
tabInverted : false
},
initialize : function (options, ready) {
window.UserVoice = window.UserVoice || [];
load('//widget.uservoice.com/' + options.widgetId + '.js', ready);
var optionsClone = clone(options);
alias(optionsClone, {
'forumId' : 'forum_id',
'primaryColor' : 'primary_color',
'linkColor' : 'link_color',
'defaultMode' : 'default_mode',
'tabLabel' : 'tab_label',
'tabColor' : 'tab_color',
'tabPosition' : 'tab_position',
'tabInverted' : 'tab_inverted'
});
// If we don't automatically show the tab, let them show it via
// javascript. This is the default name for the function in their snippet.
window.showClassicWidget = function (showWhat) {
window.UserVoice.push([showWhat || 'showLightbox', 'classic_widget', optionsClone]);
};
// If we *do* automatically show the tab, get on with it!
if (options.showTab) {
window.showClassicWidget('showTab');
}
},
identify : function (userId, traits) {
// Pull the ID into traits.
traits.id = userId;
window.UserVoice.push(['setCustomFields', traits]);
}
});
});
require.register("analytics/src/providers/vero.js", function(exports, require, module){
// https://github.com/getvero/vero-api/blob/master/sections/js.md
var Provider = require('../provider')
, isEmail = require('is-email')
, load = require('load-script');
module.exports = Provider.extend({
name : 'Vero',
key : 'apiKey',
defaults : {
apiKey : null
},
initialize : function (options, ready) {
window._veroq = window._veroq || [];
window._veroq.push(['init', { api_key: options.apiKey }]);
load('//d3qxef4rp70elm.cloudfront.net/m.js');
// Vero creates a queue, so it's ready immediately.
ready();
},
identify : function (userId, traits) {
// Don't do anything if we just have traits, because Vero
// requires a `userId`.
if (!userId || !traits.email) return;
// Vero takes the `userId` as part of the traits object.
traits.id = userId;
window._veroq.push(['user', traits]);
},
track : function (event, properties) {
window._veroq.push(['track', event, properties]);
}
});
});
require.register("analytics/src/providers/visual-website-optimizer.js", function(exports, require, module){
// http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
// http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
var each = require('each')
, inherit = require('inherit')
, nextTick = require('next-tick')
, Provider = require('../provider');
/**
* Expose `VWO`.
*/
module.exports = VWO;
/**
* `VWO` inherits from the generic `Provider`.
*/
function VWO () {
Provider.apply(this, arguments);
}
inherit(VWO, Provider);
/**
* Name.
*/
VWO.prototype.name = 'Visual Website Optimizer';
/**
* Default options.
*/
VWO.prototype.defaults = {
// Whether to replay variations into other integrations as traits.
replay : true
};
/**
* Initialize.
*/
VWO.prototype.initialize = function (options, ready) {
if (options.replay) this.replay();
ready();
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function () {
var analytics = this.analytics;
nextTick(function () {
experiments(function (err, traits) {
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} callback Called with `err, experiments`.
* @return {Object} Dictionary of experiments and variations.
*/
function experiments (callback) {
enqueue(function () {
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return callback();
each(ids, function (id) {
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
callback(null, data);
});
}
/**
* Add a function to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn Function to enqueue.
*/
function enqueue (fn) {
window._vis_opt_queue || (window._vis_opt_queue = []);
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id ID of the experiment to read.
* @return {String} Variation name.
*/
function variation (id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
});
require.register("analytics/src/providers/woopra.js", function(exports, require, module){
// http://www.woopra.com/docs/setup/javascript-tracking/
var Provider = require('../provider')
, each = require('each')
, extend = require('extend')
, isEmail = require('is-email')
, load = require('load-script')
, type = require('type')
, user = require('../user');
module.exports = Provider.extend({
name : 'Woopra',
key : 'domain',
defaults : {
domain : null
},
initialize : function (options, ready) {
// Woopra gives us a nice ready callback.
var self = this;
window.woopraReady = function (tracker) {
tracker.setDomain(self.options.domain);
tracker.setIdleTimeout(300000);
var userId = user.id()
, traits = user.traits();
addTraits(userId, traits, tracker);
tracker.track();
ready();
return false;
};
load('//static.woopra.com/js/woopra.js');
},
identify : function (userId, traits) {
// We aren't guaranteed a tracker.
if (!window.woopraTracker) return;
addTraits(userId, traits, window.woopraTracker);
},
track : function (event, properties) {
// We aren't guaranteed a tracker.
if (!window.woopraTracker) return;
// Woopra takes its `event` as the `name` key.
properties || (properties = {});
properties.name = event;
window.woopraTracker.pushEvent(properties);
}
});
/**
* Convenience function for updating the userId and traits.
*
* @param {String} userId The user's ID.
* @param {Object} traits The user's traits.
* @param {Tracker} tracker The Woopra tracker object.
*/
function addTraits (userId, traits, tracker) {
// Move a `userId` into `traits`.
if (userId) traits.id = userId;
each(traits, function (key, value) {
// Woopra seems to only support strings as trait values.
if ('string' === type(value)) tracker.addVisitorProperty(key, value);
});
}
});
require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js");
require.alias("avetisk-defaults/index.js", "defaults/index.js");
require.alias("component-clone/index.js", "analytics/deps/clone/index.js");
require.alias("component-clone/index.js", "clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js");
require.alias("component-cookie/index.js", "cookie/index.js");
require.alias("component-each/index.js", "analytics/deps/each/index.js");
require.alias("component-each/index.js", "each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-event/index.js", "analytics/deps/event/index.js");
require.alias("component-event/index.js", "event/index.js");
require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js");
require.alias("component-inherit/index.js", "inherit/index.js");
require.alias("component-object/index.js", "analytics/deps/object/index.js");
require.alias("component-object/index.js", "object/index.js");
require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js");
require.alias("component-querystring/index.js", "querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-type/index.js", "analytics/deps/type/index.js");
require.alias("component-type/index.js", "type/index.js");
require.alias("component-url/index.js", "analytics/deps/url/index.js");
require.alias("component-url/index.js", "url/index.js");
require.alias("segmentio-after/index.js", "analytics/deps/after/index.js");
require.alias("segmentio-after/index.js", "after/index.js");
require.alias("segmentio-alias/index.js", "analytics/deps/alias/index.js");
require.alias("segmentio-alias/index.js", "alias/index.js");
require.alias("segmentio-bind-all/index.js", "analytics/deps/bind-all/index.js");
require.alias("segmentio-bind-all/index.js", "analytics/deps/bind-all/index.js");
require.alias("segmentio-bind-all/index.js", "bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("segmentio-bind-all/index.js", "segmentio-bind-all/index.js");
require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js");
require.alias("segmentio-canonical/index.js", "canonical/index.js");
require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js");
require.alias("segmentio-extend/index.js", "extend/index.js");
require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js");
require.alias("segmentio-is-email/index.js", "is-email/index.js");
require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js");
require.alias("segmentio-is-meta/index.js", "is-meta/index.js");
require.alias("segmentio-json/index.js", "analytics/deps/json/index.js");
require.alias("segmentio-json/index.js", "json/index.js");
require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js");
require.alias("segmentio-load-date/index.js", "analytics/deps/load-date/index.js");
require.alias("segmentio-load-date/index.js", "load-date/index.js");
require.alias("segmentio-load-script/index.js", "analytics/deps/load-script/index.js");
require.alias("segmentio-load-script/index.js", "load-script/index.js");
require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js");
require.alias("segmentio-new-date/index.js", "analytics/deps/new-date/index.js");
require.alias("segmentio-new-date/index.js", "new-date/index.js");
require.alias("component-type/index.js", "segmentio-new-date/deps/type/index.js");
require.alias("segmentio-on-body/index.js", "analytics/deps/on-body/index.js");
require.alias("segmentio-on-body/index.js", "on-body/index.js");
require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js");
require.alias("segmentio-store.js/store.js", "store/index.js");
require.alias("segmentio-json/index.js", "segmentio-store.js/deps/json/index.js");
require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js");
require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "top-domain/index.js");
require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js");
require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js");
require.alias("timoxley-next-tick/index.js", "analytics/deps/next-tick/index.js");
require.alias("timoxley-next-tick/index.js", "next-tick/index.js");
require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js");
require.alias("yields-prevent/index.js", "prevent/index.js");
require.alias("analytics/src/index.js", "analytics/index.js");
if (typeof exports == "object") {
module.exports = require("analytics");
} else if (typeof define == "function" && define.amd) {
define(function(){ return require("analytics"); });
} else {
this["analytics"] = require("analytics");
}})(); |
client/pages/examples/threejs/gpu-particles/index.js | fdesjardins/webgl | import React from 'react'
import * as THREE from 'three'
import Stats from 'stats.js'
import threeOrbitControls from 'three-orbit-controls'
import { css } from 'emotion'
import Example from '-/components/example'
import { onResize } from '-/utils'
import notes from './readme.md'
import {
createTextures,
fillTextures,
createRenderTarget,
createSceneAndCamera,
createParticles,
} from './particles'
import { vs, updatePos, updateVel } from './shaders'
const WIDTH = 300
const HEIGHT = 300
const PARTICLES = WIDTH * WIDTH
const checkCapabilities = (renderer) => {
if (
renderer.capabilities.isWebGL2 === false &&
renderer.extensions.has('OES_texture_float') === false
) {
console.error('No OES_texture_float support for float textures.')
return 0
}
if (renderer.capabilities.maxVertexTextures === 0) {
console.error('No support for vertex shader textures')
return 0
}
return 1
}
const init = ({ canvas, container }) => {
const scene = new THREE.Scene()
scene.background = new THREE.Color(0x000000)
const stats = new Stats()
stats.showPanel(0)
document.body.appendChild(stats.dom)
const camera = new THREE.PerspectiveCamera(
75,
canvas.clientWidth / canvas.clientWidth,
0.1,
2000
)
camera.updateProjectionMatrix()
camera.position.set(3, 3, 3)
let renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
renderer.setSize(canvas.clientWidth, canvas.clientWidth)
if (!checkCapabilities(renderer)) {
return
}
window.addEventListener(
'resize',
(event) => {
event.preventDefault()
onResize({ canvas, camera, renderer })
},
false
)
const OrbitControls = threeOrbitControls(THREE)
const controls = new OrbitControls(camera)
controls.update()
const dataTextures = createTextures({ width: WIDTH, height: HEIGHT })
fillTextures(dataTextures.position, dataTextures.velocity)
let currentPosTexture = createRenderTarget({ width: WIDTH, height: HEIGHT })
let nextPosTexture = createRenderTarget({ width: WIDTH, height: HEIGHT })
let currentVelTexture = createRenderTarget({ width: WIDTH, height: HEIGHT })
let nextVelTexture = createRenderTarget({ width: WIDTH, height: HEIGHT })
const { scene: rtScene, camera: rtCamera } = createSceneAndCamera({
w: WIDTH,
h: HEIGHT,
})
// Set up particle uniforms, textures, etc.
const uniforms = {
u_position: { value: dataTextures.position },
u_velocity: { value: dataTextures.velocity },
u_resolution: { value: new THREE.Vector2(WIDTH, WIDTH) },
u_time: { type: 'f', value: 0 },
u_delta: { type: 'f', value: 0 },
}
const posMaterial = new THREE.ShaderMaterial({
vertexShader: vs,
fragmentShader: updatePos,
uniforms,
})
const velMaterial = new THREE.ShaderMaterial({
vertexShader: vs,
fragmentShader: updateVel,
uniforms,
})
const geometry = new THREE.PlaneBufferGeometry(WIDTH, HEIGHT)
const object = new THREE.Mesh(geometry, posMaterial)
rtScene.add(object)
// Add the actual particles instance to the scene
const particles = createParticles(PARTICLES, WIDTH, uniforms)
scene.add(particles)
const clock = new THREE.Clock()
const animate = () => {
if (renderer) {
stats.begin()
requestAnimationFrame(animate)
// Update positions
object.material = posMaterial
renderer.setRenderTarget(nextPosTexture)
renderer.render(rtScene, rtCamera)
// Swap position textures
let temp = currentPosTexture
currentPosTexture = nextPosTexture
uniforms.u_position.value = currentPosTexture.texture
nextPosTexture = temp
// Update velocities
object.material = velMaterial
renderer.setRenderTarget(nextVelTexture)
renderer.render(rtScene, rtCamera)
// Swap velocity textures
temp = currentVelTexture
currentVelTexture = nextVelTexture
uniforms.u_velocity.value = currentVelTexture.texture
nextVelTexture = temp
// Render the scene
renderer.setRenderTarget(null)
renderer.render(scene, camera)
// Update the clock
uniforms.u_delta.value = clock.getDelta()
uniforms.u_time.value = clock.elapsedTime
stats.end()
}
}
animate()
return () => {
renderer.dispose()
stats.scene = null
document.body.removeChild(stats.dom)
renderer = null
}
}
const style = css`
canvas {
position: fixed;
top: 68px;
left: 0px;
width: 100vw;
height: calc(100vh - 68px) !important;
background-color: black;
}
`
const E = () => (
<div className={style}>
<Example notes={notes} init={init} />
</div>
)
export default E
|
ajax/libs/js-data-http/3.0.0-alpha.5/js-data-http.js | sajochiu/cdnjs | /*!
* js-data-http
* @version 3.0.0-alpha.5 - Homepage <http://www.js-data.io/docs/dshttpadapter>
* @author Jason Dobry <[email protected]>
* @copyright (c) 2014-2015 Jason Dobry
* @license MIT <https://github.com/js-data/js-data-http/blob/master/LICENSE>
*
* @overview HTTP adapter for js-data.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("js-data"));
else if(typeof define === 'function' && define.amd)
define(["js-data"], factory);
else if(typeof exports === 'object')
exports["HttpAdapter"] = factory(require("js-data"));
else
root["HttpAdapter"] = factory(root["JSData"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'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 ? "symbol" : typeof obj; };
var _jsData = __webpack_require__(1);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/* global fetch:true Headers:true Request:true */
var axios = __webpack_require__(2);
var _ = _jsData.utils._;
var addHiddenPropsToTarget = _jsData.utils.addHiddenPropsToTarget;
var copy = _jsData.utils.copy;
var deepMixIn = _jsData.utils.deepMixIn;
var extend = _jsData.utils.extend;
var fillIn = _jsData.utils.fillIn;
var forOwn = _jsData.utils.forOwn;
var isArray = _jsData.utils.isArray;
var isFunction = _jsData.utils.isFunction;
var isNumber = _jsData.utils.isNumber;
var isObject = _jsData.utils.isObject;
var isSorN = _jsData.utils.isSorN;
var isString = _jsData.utils.isString;
var isUndefined = _jsData.utils.isUndefined;
var resolve = _jsData.utils.resolve;
var reject = _jsData.utils.reject;
var toJson = _jsData.utils.toJson;
var hasFetch = false;
try {
hasFetch = window && window.fetch;
} catch (e) {}
function isValidString(value) {
return value != null && value !== '';
}
function join(items, separator) {
separator || (separator = '');
return items.filter(isValidString).join(separator);
}
function makePath() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var result = join(args, '/');
return result.replace(/([^:\/]|^)\/{2,}/g, '$1/');
}
function encode(val) {
return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');
}
function buildUrl(url, params) {
if (!params) {
return url;
}
var parts = [];
forOwn(params, function (val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (!isArray(val)) {
val = [val];
}
val.forEach(function (v) {
if (window.toString.call(v) === '[object Date]') {
v = v.toISOString();
} else if (isObject(v)) {
v = toJson(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
if (parts.length > 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
}
return url;
}
var noop = function noop() {
var self = this;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var opts = args[args.length - 1];
self.dbg.apply(self, [opts.op].concat(args));
};
var noop2 = function noop2() {
var self = this;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var opts = args[args.length - 2];
self.dbg.apply(self, [opts.op].concat(args));
};
var DEFAULTS = {
// Default and user-defined settings
/**
* @name HttpAdapter#basePath
* @type {string}
*/
basePath: '',
/**
* @name HttpAdapter#debug
* @type {boolean}
* @default false
*/
debug: false,
/**
* @name HttpAdapter#forceTrailingSlash
* @type {boolean}
* @default false
*/
forceTrailingSlash: false,
/**
* @name HttpAdapter#http
* @type {Function}
*/
http: axios,
/**
* @name HttpAdapter#httpConfig
* @type {Object}
*/
httpConfig: {},
/**
* @name HttpAdapter#suffix
* @type {string}
*/
suffix: '',
/**
* @name HttpAdapter#useFetch
* @type {boolean}
* @default false
*/
useFetch: false
};
/**
* HttpAdapter class.
*
* @class HttpAdapter
* @param {Object} [opts] Configuration options.
* @param {string} [opts.basePath=''] TODO
* @param {boolean} [opts.debug=false] TODO
* @param {boolean} [opts.forceTrailingSlash=false] TODO
* @param {Object} [opts.http=axios] TODO
* @param {Object} [opts.httpConfig={}] TODO
* @param {string} [opts.suffix=''] TODO
* @param {boolean} [opts.useFetch=false] TODO
*/
function HttpAdapter(opts) {
var self = this;
// Default values for arguments
opts || (opts = {});
fillIn(self, opts);
fillIn(self, DEFAULTS);
}
addHiddenPropsToTarget(HttpAdapter.prototype, {
/**
* @name HttpAdapter#afterCreate
* @method
* @param {Object} mapper
* @param {Object} props
* @param {Object} opts
* @param {Object} data
*/
afterCreate: noop2,
/**
* @name HttpAdapter#afterCreateMany
* @method
* @param {Object} mapper
* @param {Object} records
* @param {Object} opts
* @param {Object} data
*/
afterCreateMany: noop2,
/**
* @name HttpAdapter#afterDEL
* @method
* @param {string} url
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterDEL: noop2,
/**
* @name HttpAdapter#afterDestroy
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
* @param {Object} data
*/
afterDestroy: noop2,
/**
* @name HttpAdapter#afterDestroyAll
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
* @param {Object} data
*/
afterDestroyAll: noop2,
/**
* @name HttpAdapter#afterFind
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
* @param {Object} data
*/
afterFind: noop2,
/**
* @name HttpAdapter#afterFindAll
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
* @param {Object} data
*/
afterFindAll: noop2,
/**
* @name HttpAdapter#afterGET
* @method
* @param {string} url
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterGET: noop2,
/**
* @name HttpAdapter#afterHTTP
* @method
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterHTTP: noop2,
/**
* @name HttpAdapter#afterPOST
* @method
* @param {string} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterPOST: noop2,
/**
* @name HttpAdapter#afterPUT
* @method
* @param {string} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterPUT: noop2,
/**
* @name HttpAdapter#afterUpdate
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} props
* @param {Object} opts
* @param {Object} data
*/
afterUpdate: noop2,
/**
* @name HttpAdapter#afterUpdateAll
* @method
* @param {Object} mapper
* @param {Object} props
* @param {Object} query
* @param {Object} opts
* @param {Object} data
*/
afterUpdateAll: noop2,
/**
* @name HttpAdapter#afterUpdateMany
* @method
* @param {Object} mapper
* @param {Object} records
* @param {Object} opts
* @param {Object} data
*/
afterUpdateMany: noop2,
/**
* @name HttpAdapter#beforeCreate
* @method
* @param {Object} mapper
* @param {Object} props
* @param {Object} opts
*/
beforeCreate: noop,
/**
* @name HttpAdapter#beforeCreateMany
* @method
* @param {Object} mapper
* @param {Object} records
* @param {Object} opts
*/
beforeCreateMany: noop,
/**
* @name HttpAdapter#beforeDEL
* @method
* @param {Object} url
* @param {Object} config
* @param {Object} opts
*/
beforeDEL: noop,
/**
* @name HttpAdapter#beforeDestroy
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
*/
beforeDestroy: noop,
/**
* @name HttpAdapter#beforeDestroyAll
* @method
* @param {Object} mapper
* @param {Object} query
* @param {Object} opts
*/
beforeDestroyAll: noop,
/**
* @name HttpAdapter#beforeFind
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} opts
*/
beforeFind: noop,
/**
* @name HttpAdapter#beforeFindAll
* @method
* @param {Object} mapper
* @param {Object} query
* @param {Object} opts
*/
beforeFindAll: noop,
/**
* @name HttpAdapter#beforeGET
* @method
* @param {Object} url
* @param {Object} config
* @param {Object} opts
*/
beforeGET: noop,
/**
* @name HttpAdapter#beforeHTTP
* @method
* @param {Object} config
* @param {Object} opts
*/
beforeHTTP: noop,
/**
* @name HttpAdapter#beforePOST
* @method
* @param {Object} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
*/
beforePOST: noop,
/**
* @name HttpAdapter#beforePUT
* @method
* @param {Object} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
*/
beforePUT: noop,
/**
* @name HttpAdapter#beforeUpdate
* @method
* @param {Object} mapper
* @param {(string|number)} id
* @param {Object} props
* @param {Object} opts
*/
beforeUpdate: noop,
/**
* @name HttpAdapter#beforeUpdateAll
* @method
* @param {Object} mapper
* @param {Object} props
* @param {Object} query
* @param {Object} opts
*/
beforeUpdateAll: noop,
/**
* @name HttpAdapter#beforeUpdateMany
* @method
* @param {Object} mapper
* @param {Object} records
* @param {Object} opts
*/
beforeUpdateMany: noop,
/**
* Create a new the record from the provided `props`.
*
* @name HttpAdapter#create
* @method
* @param {Object} mapper The mapper.
* @param {Object} props Properties to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
create: function create(mapper, props, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeCreate lifecycle hook
op = opts.op = 'beforeCreate';
return resolve(self[op](mapper, props, opts)).then(function () {
op = opts.op = 'create';
self.dbg(op, mapper, props, opts);
return self.POST(self.getPath('create', mapper, props, opts), self.serialize(mapper, props, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterCreate lifecycle hook
op = opts.op = 'afterCreate';
return resolve(self[op](mapper, props, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Create multiple new records in batch.
*
* @name HttpAdapter#createMany
* @method
* @param {Object} mapper The mapper.
* @param {Array} records Array of property objects to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
createMany: function createMany(mapper, records, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeCreateMany lifecycle hook
op = opts.op = 'beforeCreateMany';
return resolve(self[op](mapper, records, opts)).then(function () {
op = opts.op = 'createMany';
self.dbg(op, mapper, records, opts);
return self.POST(self.getPath('createMany', mapper, null, opts), self.serialize(mapper, records, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterCreateMany lifecycle hook
op = opts.op = 'afterCreateMany';
return resolve(self[op](mapper, records, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Call {@link HttpAdapter#log} at the "debug" level.
*
* @name HttpAdapter#dbg
* @method
* @param {...*} [args] Args passed to {@link HttpAdapter#log}.
*/
dbg: function dbg() {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
this.log.apply(this, ['debug'].concat(args));
},
/**
* Make an Http request to `url` according to the configuration in `config`.
*
* @name HttpAdapter#DEL
* @method
* @param {string} url Url for the request.
* @param {Object} [config] Http configuration that will be passed to
* {@link HttpAdapter#HTTP}.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
DEL: function DEL(url, config, opts) {
var self = this;
var op = undefined;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.method = config.method || 'delete';
// beforeDEL lifecycle hook
op = opts.op = 'beforeDEL';
return resolve(self[op](url, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'DEL';
self.dbg(op, url, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterDEL lifecycle hook
op = opts.op = 'afterDEL';
return resolve(self[op](url, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Transform the server response object into the payload that will be returned
* to JSData.
*
* @name HttpAdapter#deserialize
* @method
* @param {Object} mapper The mapper used for the operation.
* @param {Object} response Response object from {@link HttpAdapter#HTTP}.
* @param {Object} opts Configuration options.
* @return {(Object|Array)} Deserialized data.
*/
deserialize: function deserialize(mapper, response, opts) {
opts || (opts = {});
if (isFunction(opts.deserialize)) {
return opts.deserialize(mapper, response, opts);
}
if (isFunction(mapper.deserialize)) {
return mapper.deserialize(mapper, response, opts);
}
if (opts.raw) {
return response;
}
return response ? 'data' in response ? response.data : response : response;
},
/**
* Destroy the record with the given primary key.
*
* @name HttpAdapter#destroy
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to destroy.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
destroy: function destroy(mapper, id, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeDestroy lifecycle hook
op = opts.op = 'beforeDestroy';
return resolve(self[op](mapper, id, opts)).then(function () {
op = opts.op = 'destroy';
self.dbg(op, mapper, id, opts);
return self.DEL(self.getPath('destroy', mapper, id, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterDestroy lifecycle hook
op = opts.op = 'afterDestroy';
return resolve(self[op](mapper, id, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Destroy the records that match the selection `query`.
*
* @name HttpAdapter#destroyAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} query Selection query.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
destroyAll: function destroyAll(mapper, query, opts) {
var self = this;
var op = undefined;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeDestroyAll lifecycle hook
op = opts.op = 'beforeDestroyAll';
return resolve(self.beforeDestroyAll(mapper, query, opts)).then(function () {
op = opts.op = 'destroyAll';
self.dbg(op, mapper, query, opts);
return self.DEL(self.getPath('destroyAll', mapper, null, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterDestroyAll lifecycle hook
op = opts.op = 'afterDestroyAll';
return resolve(self[op](mapper, query, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Log an error.
*
* @name HttpAdapter#error
* @method
* @param {...*} [args] Arguments to log.
*/
error: function error() {
if (console) {
var _console;
(_console = console)[typeof console.error === 'function' ? 'error' : 'log'].apply(_console, arguments);
}
},
/**
* Make an Http request using `window.fetch`.
*
* @name HttpAdapter#fetch
* @method
* @param {Object} config Request configuration.
* @param {Object} config.data Payload for the request.
* @param {string} config.method Http method for the request.
* @param {Object} config.headers Headers for the request.
* @param {Object} config.params Querystring for the request.
* @param {string} config.url Url for the request.
* @param {Object} [opts] Configuration options.
*/
fetch: function (_fetch) {
function fetch(_x, _x2) {
return _fetch.apply(this, arguments);
}
fetch.toString = function () {
return _fetch.toString();
};
return fetch;
}(function (config, opts) {
var requestConfig = {
method: config.method,
// turn the plain headers object into the Fetch Headers object
headers: new Headers(config.headers)
};
if (config.data) {
requestConfig.body = toJson(config.data);
}
return fetch(new Request(buildUrl(config.url, config.params), requestConfig)).then(function (response) {
response.config = {
method: config.method,
url: config.url
};
return response.json().then(function (data) {
response.data = data;
return response;
});
});
}),
/**
* Retrieve the record with the given primary key.
*
* @name HttpAdapter#find
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to retrieve.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
find: function find(mapper, id, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeFind lifecycle hook
op = opts.op = 'beforeFind';
return resolve(self[op](mapper, id, opts)).then(function () {
op = opts.op = 'find';
self.dbg(op, mapper, id, opts);
return self.GET(self.getPath('find', mapper, id, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterFind lifecycle hook
op = opts.op = 'afterFind';
return resolve(self[op](mapper, id, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Retrieve the records that match the selection `query`.
*
* @name HttpAdapter#findAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} query Selection query.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
findAll: function findAll(mapper, query, opts) {
var self = this;
var op = undefined;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
// beforeFindAll lifecycle hook
op = opts.op = 'beforeFindAll';
return resolve(self[op](mapper, query, opts)).then(function () {
op = opts.op = 'findAll';
self.dbg(op, mapper, query, opts);
return self.GET(self.getPath('findAll', mapper, opts.params, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterFindAll lifecycle hook
op = opts.op = 'afterFindAll';
return resolve(self[op](mapper, query, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* TODO
*
* @name HttpAdapter#GET
* @method
* @param {string} url The url for the request.
* @param {Object} config Request configuration options.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
GET: function GET(url, config, opts) {
var self = this;
var op = undefined;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.method = config.method || 'get';
// beforeGET lifecycle hook
op = opts.op = 'beforeGET';
return resolve(self[op](url, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'GET';
self.dbg(op, url, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterGET lifecycle hook
op = opts.op = 'afterGET';
return resolve(self[op](url, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* @name HttpAdapter#getEndpoint
* @method
* @param {Object} mapper TODO
* @param {*} id TODO
* @param {boolean} opts TODO
* @return {string} Full path.
*/
getEndpoint: function getEndpoint(mapper, id, opts) {
var self = this;
opts || (opts = {});
opts.params || (opts.params = {});
var endpoint = opts.hasOwnProperty('endpoint') ? opts.endpoint : mapper.endpoint;
var parents = mapper.parents || (mapper.parent ? _defineProperty({}, mapper.parent, {
key: mapper.parentKey,
field: mapper.parentField
}) : {});
forOwn(parents, function (parent, parentName) {
var item = undefined;
var parentKey = parent.key;
var parentField = parent.field;
var parentDef = mapper.getResource(parentName);
var parentId = opts.params[parentKey];
if (parentId === false || !parentKey || !parentDef) {
if (parentId === false) {
delete opts.params[parentKey];
}
return false;
} else {
delete opts.params[parentKey];
if (isString(id) || isNumber(id)) {
item = mapper.get(id);
} else if (isObject(id)) {
item = id;
}
if (item) {
parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null);
}
if (parentId) {
var _ret = function () {
delete opts.endpoint;
var _opts = {};
forOwn(opts, function (value, key) {
_opts[key] = value;
});
_(_opts, parentDef);
endpoint = makePath(self.getEndpoint(parentDef, parentId, _opts, parentId, endpoint));
return {
v: false
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
}
});
return endpoint;
},
/**
* @name HttpAdapter#getPath
* @method
* @param {string} method TODO
* @param {Object} mapper TODO
* @param {(string|number)?} id TODO
* @param {Object} opts Configuration options.
*/
getPath: function getPath(method, mapper, id, opts) {
var self = this;
opts || (opts = {});
var args = [opts.basePath === undefined ? mapper.basePath === undefined ? self.basePath : mapper.basePath : opts.basePath, self.getEndpoint(mapper, isString(id) || isNumber(id) || method === 'create' ? id : null, opts)];
if (method === 'find' || method === 'update' || method === 'destroy') {
args.push(id);
}
return makePath.apply(_jsData.utils, args);
},
/**
* Make an Http request.
*
* @name HttpAdapter#HTTP
* @method
* @param {Object} config Request configuration options.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
HTTP: function HTTP(config, opts) {
var self = this;
var start = new Date();
opts || (opts = {});
config = copy(config);
config = deepMixIn(config, self.httpConfig);
if (self.forceTrailingSlash && config.url[config.url.length - 1] !== '/') {
config.url += '/';
}
config.method = config.method.toUpperCase();
var suffix = config.suffix || opts.suffix || self.suffix;
if (suffix && config.url.substr(config.url.length - suffix.length) !== suffix) {
config.url += suffix;
}
function logResponse(data) {
var str = start.toUTCString() + ' - ' + config.method.toUpperCase() + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms';
if (data.status >= 200 && data.status < 300) {
if (self.log) {
self.dbg('debug', str, data);
}
return data;
} else {
if (self.error) {
self.error('\'FAILED: ' + str, data);
}
return reject(data);
}
}
if (!self.http) {
throw new Error('You have not configured this adapter with an http library!');
}
return resolve(self.beforeHTTP(config, opts)).then(function (_config) {
config = _config || config;
if (hasFetch && (self.useFetch || opts.useFetch || !self.http)) {
return self.fetch(config, opts).then(logResponse, logResponse);
}
return self.http(config).then(logResponse, logResponse).catch(function (err) {
return self.responseError(err, config, opts);
});
}).then(function (response) {
return resolve(self.afterHTTP(config, opts, response)).then(function (_response) {
return _response || response;
});
});
},
/**
* Log the provided arguments at the specified leve.
*
* @name HttpAdapter#log
* @method
* @param {string} level Log level.
* @param {...*} [args] Arguments to log.
*/
log: function log(level) {
for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
args[_key5 - 1] = arguments[_key5];
}
if (level && !args.length) {
args.push(level);
level = 'debug';
}
if (level === 'debug' && !this.debug) {
return;
}
var prefix = level.toUpperCase() + ': (HttpAdapter)';
if (console[level]) {
var _console2;
(_console2 = console)[level].apply(_console2, [prefix].concat(args));
} else {
var _console3;
(_console3 = console).log.apply(_console3, [prefix].concat(args));
}
},
/**
* TODO
*
* @name HttpAdapter#POST
* @method
* @param {*} url TODO
* @param {Object} data TODO
* @param {Object} config TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
POST: function POST(url, data, config, opts) {
var self = this;
var op = undefined;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.data = data || config.data;
config.method = config.method || 'post';
// beforePOST lifecycle hook
op = opts.op = 'beforePOST';
return resolve(self[op](url, data, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'POST';
self.dbg(op, url, data, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterPOST lifecycle hook
op = opts.op = 'afterPOST';
return resolve(self[op](url, data, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* TODO
*
* @name HttpAdapter#PUT
* @method
* @param {*} url TODO
* @param {Object} data TODO
* @param {Object} config TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
PUT: function PUT(url, data, config, opts) {
var self = this;
var op = undefined;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.data = data || config.data;
config.method = config.method || 'put';
// beforePUT lifecycle hook
op = opts.op = 'beforePUT';
return resolve(self[op](url, data, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'PUT';
self.dbg(op, url, data, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterPUT lifecycle hook
op = opts.op = 'afterPUT';
return resolve(self[op](url, data, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* TODO
*
* @name HttpAdapter#queryTransform
* @method
* @param {Object} mapper TODO
* @param {*} params TODO
* @param {*} opts TODO
* @return {*} Transformed params.
*/
queryTransform: function queryTransform(mapper, params, opts) {
opts || (opts = {});
if (isFunction(opts.queryTransform)) {
return opts.queryTransform(mapper, params, opts);
}
if (isFunction(mapper.queryTransform)) {
return mapper.queryTransform(mapper, params, opts);
}
return params;
},
/**
* Error handler invoked when the promise returned by {@link HttpAdapter#http}
* is rejected. Default implementation is to just return the error wrapped in
* a rejected Promise, aka rethrow the error. {@link HttpAdapter#http} is
* called by {@link HttpAdapter#HTTP}.
*
* @name HttpAdapter#responseError
* @method
* @param {*} err The error that {@link HttpAdapter#http} rejected with.
* @param {Object} config The `config` argument that was passed to {@link HttpAdapter#HTTP}.
* @param {*} opts The `opts` argument that was passed to {@link HttpAdapter#HTTP}.
* @return {Promise}
*/
responseError: function responseError(err, config, opts) {
return reject(err);
},
/**
* TODO
*
* @name HttpAdapter#serialize
* @method
* @param {Object} mapper TODO
* @param {Object} data TODO
* @param {*} opts TODO
* @return {*} Serialized data.
*/
serialize: function serialize(mapper, data, opts) {
opts || (opts = {});
if (isFunction(opts.serialize)) {
return opts.serialize(mapper, data, opts);
}
if (isFunction(mapper.serialize)) {
return mapper.serialize(mapper, data, opts);
}
return data;
},
/**
* TODO
*
* @name HttpAdapter#update
* @method
* @param {Object} mapper TODO
* @param {*} id TODO
* @param {*} props TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
update: function update(mapper, id, props, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeUpdate lifecycle hook
op = opts.op = 'beforeUpdate';
return resolve(self[op](mapper, id, props, opts)).then(function () {
op = opts.op = 'update';
self.dbg(op, mapper, id, props, opts);
return self.PUT(self.getPath('update', mapper, id, opts), self.serialize(mapper, props, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterUpdate lifecycle hook
op = opts.op = 'afterUpdate';
return resolve(self[op](mapper, id, props, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* TODO
*
* @name HttpAdapter#updateAll
* @method
* @param {Object} mapper TODO
* @param {Object} props TODO
* @param {Object} query TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
updateAll: function updateAll(mapper, props, query, opts) {
var self = this;
var op = undefined;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeUpdateAll lifecycle hook
op = opts.op = 'beforeUpdateAll';
return resolve(self[op](mapper, props, query, opts)).then(function () {
op = opts.op = 'updateAll';
self.dbg(op, mapper, props, query, opts);
return self.PUT(self.getPath('updateAll', mapper, null, opts), self.serialize(mapper, props, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterUpdateAll lifecycle hook
op = opts.op = 'afterUpdateAll';
return resolve(self[op](mapper, props, query, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
},
/**
* Update multiple records in batch.
*
* {@link HttpAdapter#beforeUpdateMany} will be called before calling
* {@link HttpAdapter#PUT}.
* {@link HttpAdapter#afterUpdateMany} will be called after calling
* {@link HttpAdapter#PUT}.
*
* @name HttpAdapter#updateMany
* @method
* @param {Object} mapper The mapper.
* @param {Array} records Array of property objects to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
updateMany: function updateMany(mapper, records, opts) {
var self = this;
var op = undefined;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = isUndefined(opts.suffix) ? mapper.suffix : opts.suffix;
// beforeUpdateMany lifecycle hook
op = opts.op = 'beforeUpdateMany';
return resolve(self[op](mapper, records, opts)).then(function () {
op = opts.op = 'updateMany';
self.dbg(op, mapper, records, opts);
return self.PUT(self.getPath('updateMany', mapper, null, opts), self.serialize(mapper, records, opts), opts);
}).then(function (response) {
return self.deserialize(mapper, response, opts);
}).then(function (data) {
// afterUpdateMany lifecycle hook
op = opts.op = 'afterUpdateMany';
return resolve(self[op](mapper, records, opts, data)).then(function (_data) {
// Allow re-assignment from lifecycle hook
return isUndefined(_data) ? data : _data;
});
});
}
});
/**
* Add an Http actions to a mapper.
*
* @name HttpAdapter.addAction
* @method
* @param {string} name Name of the new action.
* @param {Object} [opts] Action configuration
* @param {string} [opts.adapter]
* @param {string} [opts.pathname]
* @param {Function} [opts.request]
* @param {Function} [opts.response]
* @param {Function} [opts.responseError]
* @return {Function} Decoration function, which should be passed the mapper to
* decorate when invoked.
*/
HttpAdapter.addAction = function (name, opts) {
if (!name || !isString(name)) {
throw new TypeError('action(name[, opts]): Expected: string, Found: ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name)));
}
return function (mapper) {
if (mapper[name]) {
throw new Error('action(name[, opts]): ' + name + ' already exists on target!');
}
opts.request = opts.request || function (config) {
return config;
};
opts.response = opts.response || function (response) {
return response;
};
opts.responseError = opts.responseError || function (err) {
return reject(err);
};
mapper[name] = function (id, _opts) {
var self = this;
if (isObject(id)) {
_opts = id;
}
_opts = _opts || {};
var adapter = self.getAdapter(opts.adapter || self.defaultAdapter || 'http');
var config = {};
fillIn(config, opts);
if (!_opts.hasOwnProperty('endpoint') && config.endpoint) {
_opts.endpoint = config.endpoint;
}
if (typeof _opts.getEndpoint === 'function') {
config.url = _opts.getEndpoint(self, _opts);
} else {
var _args = [_opts.basePath || self.basePath || adapter.basePath, adapter.getEndpoint(self, isSorN(id) ? id : null, _opts)];
if (isSorN(id)) {
_args.push(id);
}
_args.push(opts.pathname || name);
config.url = makePath.apply(null, _args);
}
config.method = config.method || 'GET';
config.mapper = self.name;
deepMixIn(config)(_opts);
return resolve(config).then(_opts.request || opts.request).then(function (config) {
return adapter.HTTP(config);
}).then(function (data) {
if (data && data.config) {
data.config.mapper = self.name;
}
return data;
}).then(_opts.response || opts.response, _opts.responseError || opts.responseError);
};
return mapper;
};
};
/**
* Add multiple Http actions to a mapper. See {@link HttpAdapter.addAction} for
* action configuration options.
*
* @name HttpAdapter.addActions
* @method
* @param {Object.<string, Object>} opts Object where the key is an action name
* and the value is the configuration for the action.
* @return {Function} Decoration function, which should be passed the mapper to
* decorate when invoked.
*/
HttpAdapter.addActions = function (opts) {
opts || (opts = {});
return function (mapper) {
forOwn(mapper, function (value, key) {
HttpAdapter.addAction(key, value)(mapper);
});
return mapper;
};
};
/**
* Alternative to ES6 class syntax for extending `HttpAdapter`.
*
* __ES6__:
* ```javascript
* class MyHttpAdapter extends HttpAdapter {
* deserialize (Model, data, opts) {
* const data = super.deserialize(Model, data, opts)
* data.foo = 'bar'
* return data
* }
* }
* ```
*
* __ES5__:
* ```javascript
* var instanceProps = {
* // override deserialize
* deserialize: function (Model, data, opts) {
* var Ctor = this.constructor
* var superDeserialize = (Ctor.__super__ || Object.getPrototypeOf(Ctor)).deserialize
* // call the super deserialize
* var data = superDeserialize(Model, data, opts)
* data.foo = 'bar'
* return data
* },
* say: function () { return 'hi' }
* }
* var classProps = {
* yell: function () { return 'HI' }
* }
*
* var MyHttpAdapter = HttpAdapter.extend(instanceProps, classProps)
* var adapter = new MyHttpAdapter()
* adapter.say() // "hi"
* MyHttpAdapter.yell() // "HI"
* ```
*
* @name HttpAdapter.extend
* @method
* @param {Object} [instanceProps] Properties that will be added to the
* prototype of the subclass.
* @param {Object} [classProps] Properties that will be added as static
* properties to the subclass itself.
* @return {Object} Subclass of `HttpAdapter`.
*/
HttpAdapter.extend = extend;
/**
* Details of the current version of the `js-data-http` module.
*
* @name HttpAdapter.version
* @type {Object}
* @property {string} version.full The full semver value.
* @property {number} version.major The major version number.
* @property {number} version.minor The minor version number.
* @property {number} version.patch The patch version number.
* @property {(string|boolean)} version.alpha The alpha version value,
* otherwise `false` if the current version is not alpha.
* @property {(string|boolean)} version.beta The beta version value,
* otherwise `false` if the current version is not beta.
*/
HttpAdapter.version = {
full: '3.0.0-alpha.5',
major: parseInt('3', 10),
minor: parseInt('0', 10),
patch: parseInt('0', 10),
alpha: true ? '5' : false,
beta: true ? 'false' : false
};
/**
* Registered as `js-data-http` in NPM and Bower. The build of `js-data-http`
* that works on Node.js is registered in NPM as `js-data-http-node`. The build
* of `js-data-http` that does not bundle `axios` is registered in NPM and Bower
* as `js-data-fetch`.
*
* __Script tag__:
* ```javascript
* window.HttpAdapter
* ```
* __CommonJS__:
* ```javascript
* var HttpAdapter = require('js-data-http')
* ```
* __ES6 Modules__:
* ```javascript
* import HttpAdapter from 'js-data-http'
* ```
* __AMD__:
* ```javascript
* define('myApp', ['js-data-http'], function (HttpAdapter) { ... })
* ```
*
* @module js-data-http
*/
module.exports = HttpAdapter;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(3);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var defaults = __webpack_require__(4);
var utils = __webpack_require__(5);
var dispatchRequest = __webpack_require__(6);
var InterceptorManager = __webpack_require__(15);
var isAbsoluteURL = __webpack_require__(16);
var combineURLs = __webpack_require__(17);
var bind = __webpack_require__(18);
var transformData = __webpack_require__(11);
function Axios(defaultConfig) {
this.defaults = utils.merge({}, defaultConfig);
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = utils.merge({
url: arguments[0]
}, arguments[1]);
}
config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
// Support baseURL config
if (config.baseURL && !isAbsoluteURL(config.url)) {
config.url = combineURLs(config.baseURL, config.url);
}
// Don't allow overriding defaults.withCredentials
config.withCredentials = config.withCredentials || this.defaults.withCredentials;
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
var defaultInstance = new Axios(defaults);
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
axios.create = function create(defaultConfig) {
return new Axios(defaultConfig);
};
// Expose defaults
axios.defaults = defaultInstance.defaults;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(19);
// Expose interceptors
axios.interceptors = defaultInstance.interceptors;
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
var PROTECTION_PREFIX = /^\)\]\}',?\n/;
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
module.exports = {
transformRequest: [function transformResponseJSON(data, headers) {
if (utils.isFormData(data)) {
return data;
}
if (utils.isArrayBuffer(data)) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) {
// Set application/json if no Content-Type has been specified
if (!utils.isUndefined(headers)) {
utils.forEach(headers, function processContentTypeHeader(val, key) {
if (key.toLowerCase() === 'content-type') {
headers['Content-Type'] = val;
}
});
if (utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = 'application/json;charset=utf-8';
}
}
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponseJSON(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
data = data.replace(PROTECTION_PREFIX, '');
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
patch: utils.merge(DEFAULT_CONTENT_TYPE),
post: utils.merge(DEFAULT_CONTENT_TYPE),
put: utils.merge(DEFAULT_CONTENT_TYPE)
},
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString.call(val) === '[object FormData]';
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* typeof document.createElement -> undefined
*/
function isStandardBrowserEnv() {
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
typeof document.createElement === 'function'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray(obj)) {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
trim: trim
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Dispatch a request to the server using whichever adapter
* is supported by the current environment.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
return new Promise(function executor(resolve, reject) {
try {
var adapter;
if (typeof config.adapter === 'function') {
// For custom adapter support
adapter = config.adapter;
} else if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(8);
} else if (typeof process !== 'undefined') {
// For node use HTTP adapter
adapter = __webpack_require__(8);
}
if (typeof adapter === 'function') {
adapter(resolve, reject, config);
}
} catch (e) {
reject(e);
}
});
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ },
/* 7 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(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;
clearTimeout(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) {
setTimeout(drainQueue, 0);
}
};
// 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; };
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
var buildURL = __webpack_require__(9);
var parseHeaders = __webpack_require__(10);
var transformData = __webpack_require__(11);
var isURLSameOrigin = __webpack_require__(12);
var btoa = window.btoa || __webpack_require__(13);
module.exports = function xhrAdapter(resolve, reject, config) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// For IE 8/9 CORS support
// Only supports POST and GET calls and doesn't returns the response headers.
if (window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
request = new window.XDomainRequest();
}
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onload = function handleLoad() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
var response = {
data: transformData(
responseData,
responseHeaders,
config.transformResponse
),
// IE sends 1223 instead of 204 (https://github.com/mzabriskie/axios/issues/201)
status: request.status === 1223 ? 204 : request.status,
statusText: request.status === 1223 ? 'No Content' : request.statusText,
headers: responseHeaders,
config: config
};
// Resolve or reject the Promise based on the status
((response.status >= 200 && response.status < 300) ||
(!('status' in request) && response.responseText) ?
resolve :
reject)(response);
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new Error('Network Error'));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(14);
// Add xsrf header
var xsrfValue = config.withCredentials || isURLSameOrigin(config.url) ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (config.withCredentials) {
request.withCredentials = true;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
if (request.responseType !== 'json') {
throw e;
}
}
}
if (utils.isArrayBuffer(requestData)) {
requestData = new DataView(requestData);
}
// Send the request
request.send(requestData);
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
}
if (!utils.isArray(val)) {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ },
/* 13 */
/***/ function(module, exports) {
'use strict';
// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.code = 5;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
function btoa(input) {
var str = String(input);
var output = '';
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars;
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3 / 4);
if (charCode > 0xFF) {
throw new InvalidCharacterError('INVALID_CHARACTER_ERR: DOM Exception 5');
}
block = block << 8 | charCode;
}
return output;
}
module.exports = btoa;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(5);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ },
/* 16 */
/***/ function(module, exports) {
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ },
/* 17 */
/***/ function(module, exports) {
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
};
/***/ },
/* 18 */
/***/ function(module, exports) {
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }
/******/ ])
});
;
//# sourceMappingURL=js-data-http.js.map |
packages/rocketchat-otr/package.js | NMandapaty/Rocket.Chat | Package.describe({
name: 'rocketchat:otr',
version: '0.0.1',
summary: 'Off-the-record messaging for Rocket.Chat',
git: ''
});
Package.onUse(function(api) {
api.use([
'ecmascript',
'less',
'rocketchat:lib',
'tracker',
'reactive-var'
]);
api.use('templating', 'client');
api.addFiles([
'client/rocketchat.otr.js',
'client/rocketchat.otr.room.js',
'client/stylesheets/otr.less',
'client/views/otrFlexTab.html',
'client/views/otrFlexTab.js',
'client/tabBar.js'
], 'client');
api.addFiles([
'server/settings.js',
'server/models/Messages.js',
'server/methods/deleteOldOTRMessages.js',
'server/methods/updateOTRAck.js'
], 'server');
});
|
router/route/auth.js | jstogether/jstogether | import express from 'express';
import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';
import {Strategy as GithubStrategy} from 'passport-github';
import path from 'path';
import bcrypt from 'bcrypt';
import React from 'react';
import db from '../../db';
let User = db.model('User');
let router = express.Router();
passport.serializeUser((user, done) => done(null, user.username));
passport.deserializeUser((username, done) => User.findOne({username}, done));
/*******************************************/
/** LOCAL STRATEGY - USERNAME/PASSWORD **/
/*******************************************/
passport.use('local', new LocalStrategy((username, password, done) => {
User.get(username, (err, user) => {
if (err) return done(err);
if (!user) {
return done(null, false, {
message: 'User not found.'
});
}
bcrypt.compare(password, user.password, (err, result) => {
if (err) return done(err);
if (!result) {
return done(null, false, {
message: 'Incorrect password.'
});
}
return done(null, user);
});
});
}));
router.post('/register', (req, res) => {
let user = {
username: req.body.username,
password: req.body.password
};
User.create(user, (err, user) => {
if (err) {
let status = err.code === 11000 ? 409 : 500;
return res.sendStatus(status);
}
passport.authenticate('local')(req, res, () => {
req.logIn(req.user, (err) => {
if (err) res.status(403).send(err);
return res.send(req.user.toClient());
});
});
});
});
router.post('/login', passport.authenticate('local'), (req, res) => {
req.logIn(req.user, (err) => {
if (err) res.status(403).send(err);
return res.send(req.user.toClient());
});
});
/********************************/
/** OAUTH2 STRATEGY - GITHUB **/
/********************************/
passport.use('github', new GithubStrategy({
clientID: process.env.GITHUB_CLIENT_ID || 'no clientid',
clientSecret: process.env.GITHUB_CLIENT_SECRET || 'no secret',
callbackURL: process.env.GITHUB_CALLBACK_URL || 'http://localhost:1025/auth/github/callback'
}, (accessToken, refreshToken, profile, done) => {
const user = {
username: profile.username,
fullName: profile.displayName,
githubUrl: profile.profileUrl,
email: '', // TODO: get this from github manually
location: profile._json.location,
avatarUrl: profile._json.avatar_url
};
User.findOrCreate({username: user.username}, user, done);
}));
router.get('/github', passport.authenticate('github', {
scope: 'user:email'
}));
router.get('/github/callback', passport.authenticate('github'), (req, res) => {
req.login(req.user, (err) => {
return res.redirect('/');
});
});
router.all('/logout', (req, res) => {
req.logout();
res.send({
logout: true
});
});
export default router; |
ajax/libs/redux-form/6.0.0/redux-form.js | pombredanne/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReduxForm"] = factory(require("react"));
else
root["ReduxForm"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.untouchWithKey = exports.untouch = exports.touchWithKey = exports.touch = exports.swapArrayValues = exports.stopSubmit = exports.stopAsyncValidation = exports.startSubmit = exports.startAsyncValidation = exports.reset = exports.propTypes = exports.initializeWithKey = exports.initialize = exports.getValues = exports.removeArrayValue = exports.reduxForm = exports.reducer = exports.focus = exports.destroy = exports.changeWithKey = exports.change = exports.blur = exports.addArrayValue = exports.actionTypes = undefined;
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _reactRedux = __webpack_require__(58);
var _createAll2 = __webpack_require__(28);
var _createAll3 = _interopRequireDefault(_createAll2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isNative = typeof window !== 'undefined' && window.navigator && window.navigator.product && window.navigator.product === 'ReactNative';
var _createAll = (0, _createAll3.default)(isNative, _react2.default, _reactRedux.connect);
var actionTypes = _createAll.actionTypes;
var addArrayValue = _createAll.addArrayValue;
var blur = _createAll.blur;
var change = _createAll.change;
var changeWithKey = _createAll.changeWithKey;
var destroy = _createAll.destroy;
var focus = _createAll.focus;
var reducer = _createAll.reducer;
var reduxForm = _createAll.reduxForm;
var removeArrayValue = _createAll.removeArrayValue;
var getValues = _createAll.getValues;
var initialize = _createAll.initialize;
var initializeWithKey = _createAll.initializeWithKey;
var propTypes = _createAll.propTypes;
var reset = _createAll.reset;
var startAsyncValidation = _createAll.startAsyncValidation;
var startSubmit = _createAll.startSubmit;
var stopAsyncValidation = _createAll.stopAsyncValidation;
var stopSubmit = _createAll.stopSubmit;
var swapArrayValues = _createAll.swapArrayValues;
var touch = _createAll.touch;
var touchWithKey = _createAll.touchWithKey;
var untouch = _createAll.untouch;
var untouchWithKey = _createAll.untouchWithKey;
exports.actionTypes = actionTypes;
exports.addArrayValue = addArrayValue;
exports.blur = blur;
exports.change = change;
exports.changeWithKey = changeWithKey;
exports.destroy = destroy;
exports.focus = focus;
exports.reducer = reducer;
exports.reduxForm = reduxForm;
exports.removeArrayValue = removeArrayValue;
exports.getValues = getValues;
exports.initialize = initialize;
exports.initializeWithKey = initializeWithKey;
exports.propTypes = propTypes;
exports.reset = reset;
exports.startAsyncValidation = startAsyncValidation;
exports.startSubmit = startSubmit;
exports.stopAsyncValidation = stopAsyncValidation;
exports.stopSubmit = stopSubmit;
exports.swapArrayValues = swapArrayValues;
exports.touch = touch;
exports.touchWithKey = touchWithKey;
exports.untouch = untouch;
exports.untouchWithKey = untouchWithKey;
/***/ },
/* 1 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports.makeFieldValue = makeFieldValue;
exports.isFieldValue = isFieldValue;
var flag = '_isFieldValue';
var isObject = function isObject(object) {
return typeof object === 'object';
};
function makeFieldValue(object) {
if (object && isObject(object)) {
Object.defineProperty(object, flag, { value: true });
}
return object;
}
function isFieldValue(object) {
return !!(object && isObject(object) && object[flag]);
}
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = isValid;
function isValid(error) {
if (Array.isArray(error)) {
return error.reduce(function (valid, errorValue) {
return valid && isValid(errorValue);
}, true);
}
if (error && typeof error === 'object') {
return Object.keys(error).reduce(function (valid, key) {
return valid && isValid(error[key]);
}, true);
}
return !error;
}
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var ADD_ARRAY_VALUE = exports.ADD_ARRAY_VALUE = 'redux-form/ADD_ARRAY_VALUE';
var BLUR = exports.BLUR = 'redux-form/BLUR';
var CHANGE = exports.CHANGE = 'redux-form/CHANGE';
var DESTROY = exports.DESTROY = 'redux-form/DESTROY';
var FOCUS = exports.FOCUS = 'redux-form/FOCUS';
var INITIALIZE = exports.INITIALIZE = 'redux-form/INITIALIZE';
var REMOVE_ARRAY_VALUE = exports.REMOVE_ARRAY_VALUE = 'redux-form/REMOVE_ARRAY_VALUE';
var RESET = exports.RESET = 'redux-form/RESET';
var START_ASYNC_VALIDATION = exports.START_ASYNC_VALIDATION = 'redux-form/START_ASYNC_VALIDATION';
var START_SUBMIT = exports.START_SUBMIT = 'redux-form/START_SUBMIT';
var STOP_ASYNC_VALIDATION = exports.STOP_ASYNC_VALIDATION = 'redux-form/STOP_ASYNC_VALIDATION';
var STOP_SUBMIT = exports.STOP_SUBMIT = 'redux-form/STOP_SUBMIT';
var SUBMIT_FAILED = exports.SUBMIT_FAILED = 'redux-form/SUBMIT_FAILED';
var SWAP_ARRAY_VALUES = exports.SWAP_ARRAY_VALUES = 'redux-form/SWAP_ARRAY_VALUES';
var TOUCH = exports.TOUCH = 'redux-form/TOUCH';
var UNTOUCH = exports.UNTOUCH = 'redux-form/UNTOUCH';
/***/ },
/* 5 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = mapValues;
/**
* Maps all the values in the given object through the given function and saves them, by key, to a result object
*/
function mapValues(obj, fn) {
return obj ? Object.keys(obj).reduce(function (accumulator, key) {
var _extends2;
return _extends({}, accumulator, (_extends2 = {}, _extends2[key] = fn(obj[key], key), _extends2));
}, {}) : obj;
}
/***/ },
/* 6 */
/***/ function(module, exports) {
module.exports = isPromise;
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.untouch = exports.touch = exports.swapArrayValues = exports.submitFailed = exports.stopSubmit = exports.stopAsyncValidation = exports.startSubmit = exports.startAsyncValidation = exports.reset = exports.removeArrayValue = exports.initialize = exports.focus = exports.destroy = exports.change = exports.blur = exports.addArrayValue = undefined;
var _actionTypes = __webpack_require__(4);
var addArrayValue = exports.addArrayValue = function addArrayValue(path, value, index, fields) {
return { type: _actionTypes.ADD_ARRAY_VALUE, path: path, value: value, index: index, fields: fields };
};
var blur = exports.blur = function blur(field, value) {
return { type: _actionTypes.BLUR, field: field, value: value };
};
var change = exports.change = function change(field, value) {
return { type: _actionTypes.CHANGE, field: field, value: value };
};
var destroy = exports.destroy = function destroy() {
return { type: _actionTypes.DESTROY };
};
var focus = exports.focus = function focus(field) {
return { type: _actionTypes.FOCUS, field: field };
};
var initialize = exports.initialize = function initialize(data, fields) {
if (!Array.isArray(fields)) {
throw new Error('must provide fields array to initialize() action creator');
}
return { type: _actionTypes.INITIALIZE, data: data, fields: fields };
};
var removeArrayValue = exports.removeArrayValue = function removeArrayValue(path, index) {
return { type: _actionTypes.REMOVE_ARRAY_VALUE, path: path, index: index };
};
var reset = exports.reset = function reset() {
return { type: _actionTypes.RESET };
};
var startAsyncValidation = exports.startAsyncValidation = function startAsyncValidation(field) {
return { type: _actionTypes.START_ASYNC_VALIDATION, field: field };
};
var startSubmit = exports.startSubmit = function startSubmit() {
return { type: _actionTypes.START_SUBMIT };
};
var stopAsyncValidation = exports.stopAsyncValidation = function stopAsyncValidation(errors) {
return { type: _actionTypes.STOP_ASYNC_VALIDATION, errors: errors };
};
var stopSubmit = exports.stopSubmit = function stopSubmit(errors) {
return { type: _actionTypes.STOP_SUBMIT, errors: errors };
};
var submitFailed = exports.submitFailed = function submitFailed() {
return { type: _actionTypes.SUBMIT_FAILED };
};
var swapArrayValues = exports.swapArrayValues = function swapArrayValues(path, indexA, indexB) {
return { type: _actionTypes.SWAP_ARRAY_VALUES, path: path, indexA: indexA, indexB: indexB };
};
var touch = exports.touch = function touch() {
for (var _len = arguments.length, fields = Array(_len), _key = 0; _key < _len; _key++) {
fields[_key] = arguments[_key];
}
return { type: _actionTypes.TOUCH, fields: fields };
};
var untouch = exports.untouch = function untouch() {
for (var _len2 = arguments.length, fields = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fields[_key2] = arguments[_key2];
}
return { type: _actionTypes.UNTOUCH, fields: fields };
};
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = bindActionData;
var _mapValues = __webpack_require__(5);
var _mapValues2 = _interopRequireDefault(_mapValues);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Adds additional properties to the results of the function or map of functions passed
*/
function bindActionData(action, data) {
if (typeof action === 'function') {
return function () {
return _extends({}, action.apply(undefined, arguments), data);
};
}
if (typeof action === 'object') {
return (0, _mapValues2.default)(action, function (value) {
return bindActionData(value, data);
});
}
return action;
}
/***/ },
/* 9 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var dataKey = exports.dataKey = 'value';
var createOnDragStart = function createOnDragStart(name, getValue) {
return function (event) {
event.dataTransfer.setData(dataKey, getValue());
};
};
exports.default = createOnDragStart;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isEvent = __webpack_require__(11);
var _isEvent2 = _interopRequireDefault(_isEvent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getSelectedValues = function getSelectedValues(options) {
var result = [];
if (options) {
for (var index = 0; index < options.length; index++) {
var option = options[index];
if (option.selected) {
result.push(option.value);
}
}
}
return result;
};
var getValue = function getValue(event, isReactNative) {
if ((0, _isEvent2.default)(event)) {
if (!isReactNative && event.nativeEvent && event.nativeEvent.text !== undefined) {
return event.nativeEvent.text;
}
if (isReactNative && event.nativeEvent !== undefined) {
return event.nativeEvent.text;
}
var _event$target = event.target;
var type = _event$target.type;
var value = _event$target.value;
var checked = _event$target.checked;
var files = _event$target.files;
var dataTransfer = event.dataTransfer;
if (type === 'checkbox') {
return checked;
}
if (type === 'file') {
return files || dataTransfer && dataTransfer.files;
}
if (type === 'select-multiple') {
return getSelectedValues(event.target.options);
}
return value;
}
// not an event, so must be either our value or an object containing our value in the 'value' key
return event && typeof event === 'object' && event.value !== undefined ? event.value : // extract value from { value: value } structure. https://github.com/nikgraf/belle/issues/58
event;
};
exports.default = getValue;
/***/ },
/* 11 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var isEvent = function isEvent(candidate) {
return !!(candidate && candidate.stopPropagation && candidate.preventDefault);
};
exports.default = isEvent;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isEvent = __webpack_require__(11);
var _isEvent2 = _interopRequireDefault(_isEvent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var silenceEvent = function silenceEvent(event) {
var is = (0, _isEvent2.default)(event);
if (is) {
event.preventDefault();
}
return is;
};
exports.default = silenceEvent;
/***/ },
/* 13 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = getDisplayName;
function getDisplayName(Comp) {
return Comp.displayName || Comp.name || 'Component';
}
/***/ },
/* 14 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var getValue = function getValue(field, state, dest) {
var dotIndex = field.indexOf('.');
var openIndex = field.indexOf('[');
var closeIndex = field.indexOf(']');
if (openIndex > 0 && closeIndex !== openIndex + 1) {
throw new Error('found [ not followed by ]');
}
if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) {
(function () {
// array field
var key = field.substring(0, openIndex);
var rest = field.substring(closeIndex + 1);
if (rest[0] === '.') {
rest = rest.substring(1);
}
var array = state && state[key] || [];
if (rest) {
if (!dest[key]) {
dest[key] = [];
}
array.forEach(function (item, index) {
if (!dest[key][index]) {
dest[key][index] = {};
}
getValue(rest, item, dest[key][index]);
});
} else {
dest[key] = array.map(function (item) {
return item && item.value;
});
}
})();
} else if (dotIndex > 0) {
// subobject field
var _key = field.substring(0, dotIndex);
var _rest = field.substring(dotIndex + 1);
if (!dest[_key]) {
dest[_key] = {};
}
getValue(_rest, state && state[_key] || {}, dest[_key]);
} else {
dest[field] = state[field] && state[field].value;
}
};
var getValues = function getValues(fields, state) {
return fields.reduce(function (accumulator, field) {
getValue(field, state, accumulator);
return accumulator;
}, {});
};
exports.default = getValues;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _fieldValue = __webpack_require__(1);
/**
* A different version of getValues() that does not need the fields array
*/
var getValuesFromState = function getValuesFromState(state) {
if (!state) {
return state;
}
var keys = Object.keys(state);
if (!keys.length) {
return undefined;
}
return keys.reduce(function (accumulator, key) {
var field = state[key];
if (field) {
if (field.hasOwnProperty && field.hasOwnProperty('value')) {
if (field.value !== undefined) {
accumulator[key] = field.value;
}
} else if (Array.isArray(field)) {
accumulator[key] = field.map(function (arrayField) {
return (0, _fieldValue.isFieldValue)(arrayField) ? arrayField.value : getValuesFromState(arrayField);
});
} else if (typeof field === 'object') {
var result = getValuesFromState(field);
if (result && Object.keys(result).length > 0) {
accumulator[key] = result;
}
}
}
return accumulator;
}, {});
};
exports.default = getValuesFromState;
/***/ },
/* 16 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
/**
* Reads any potentially deep value from an object using dot and array syntax
*/
var read = function read(path, object) {
if (!path || !object) {
return object;
}
var dotIndex = path.indexOf('.');
if (dotIndex === 0) {
return read(path.substring(1), object);
}
var openIndex = path.indexOf('[');
var closeIndex = path.indexOf(']');
if (dotIndex >= 0 && (openIndex < 0 || dotIndex < openIndex)) {
// iterate down object tree
return read(path.substring(dotIndex + 1), object[path.substring(0, dotIndex)]);
}
if (openIndex >= 0 && (dotIndex < 0 || openIndex < dotIndex)) {
if (closeIndex < 0) {
throw new Error('found [ but no ]');
}
var key = path.substring(0, openIndex);
var index = path.substring(openIndex + 1, closeIndex);
if (!index.length) {
return object[key];
}
if (openIndex === 0) {
return read(path.substring(closeIndex + 1), object[index]);
}
if (!object[key]) {
return undefined;
}
return read(path.substring(closeIndex + 1), object[key][index]);
}
return object[path];
};
exports.default = read;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.initialState = exports.globalErrorKey = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _initialState, _behaviors;
var _actionTypes = __webpack_require__(4);
var _mapValues = __webpack_require__(5);
var _mapValues2 = _interopRequireDefault(_mapValues);
var _read = __webpack_require__(16);
var _read2 = _interopRequireDefault(_read);
var _write = __webpack_require__(18);
var _write2 = _interopRequireDefault(_write);
var _getValuesFromState = __webpack_require__(15);
var _getValuesFromState2 = _interopRequireDefault(_getValuesFromState);
var _initializeState = __webpack_require__(39);
var _initializeState2 = _interopRequireDefault(_initializeState);
var _resetState = __webpack_require__(45);
var _resetState2 = _interopRequireDefault(_resetState);
var _setErrors = __webpack_require__(46);
var _setErrors2 = _interopRequireDefault(_setErrors);
var _fieldValue = __webpack_require__(1);
var _normalizeFields = __webpack_require__(41);
var _normalizeFields2 = _interopRequireDefault(_normalizeFields);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var globalErrorKey = exports.globalErrorKey = '_error';
var initialState = exports.initialState = (_initialState = {
_active: undefined,
_asyncValidating: false
}, _initialState[globalErrorKey] = undefined, _initialState._initialized = false, _initialState._submitting = false, _initialState._submitFailed = false, _initialState);
var behaviors = (_behaviors = {}, _behaviors[_actionTypes.ADD_ARRAY_VALUE] = function (state, _ref) {
var path = _ref.path;
var index = _ref.index;
var value = _ref.value;
var fields = _ref.fields;
var array = (0, _read2.default)(path, state);
var stateCopy = _extends({}, state);
var arrayCopy = array ? [].concat(array) : [];
var newValue = value !== null && typeof value === 'object' ? (0, _initializeState2.default)(value, fields || Object.keys(value)) : (0, _fieldValue.makeFieldValue)({ value: value });
if (index === undefined) {
arrayCopy.push(newValue);
} else {
arrayCopy.splice(index, 0, newValue);
}
return (0, _write2.default)(path, arrayCopy, stateCopy);
}, _behaviors[_actionTypes.BLUR] = function (state, _ref2) {
var field = _ref2.field;
var value = _ref2.value;
var touch = _ref2.touch;
// remove _active from state
var _active = state._active;
var stateCopy = _objectWithoutProperties(state, ['_active']); // eslint-disable-line prefer-const
return (0, _write2.default)(field, function (previous) {
var result = _extends({}, previous);
if (value !== undefined) {
result.value = value;
}
if (touch) {
result.touched = true;
}
return (0, _fieldValue.makeFieldValue)(result);
}, stateCopy);
}, _behaviors[_actionTypes.CHANGE] = function (state, _ref3) {
var field = _ref3.field;
var value = _ref3.value;
var touch = _ref3.touch;
return (0, _write2.default)(field, function (previous) {
var _previous$value = _extends({}, previous, { value: value });
var asyncError = _previous$value.asyncError;
var submitError = _previous$value.submitError;
var result = _objectWithoutProperties(_previous$value, ['asyncError', 'submitError']);
if (touch) {
result.touched = true;
}
return (0, _fieldValue.makeFieldValue)(result);
}, state);
}, _behaviors[_actionTypes.DESTROY] = function () {
return undefined;
}, _behaviors[_actionTypes.FOCUS] = function (state, _ref4) {
var field = _ref4.field;
var stateCopy = (0, _write2.default)(field, function (previous) {
return (0, _fieldValue.makeFieldValue)(_extends({}, previous, { visited: true }));
}, state);
stateCopy._active = field;
return stateCopy;
}, _behaviors[_actionTypes.INITIALIZE] = function (state, _ref5) {
var _extends2;
var data = _ref5.data;
var fields = _ref5.fields;
return _extends({}, (0, _initializeState2.default)(data, fields, state), (_extends2 = {
_asyncValidating: false,
_active: undefined
}, _extends2[globalErrorKey] = undefined, _extends2._initialized = true, _extends2._submitting = false, _extends2._submitFailed = false, _extends2));
}, _behaviors[_actionTypes.REMOVE_ARRAY_VALUE] = function (state, _ref6) {
var path = _ref6.path;
var index = _ref6.index;
var array = (0, _read2.default)(path, state);
var stateCopy = _extends({}, state);
var arrayCopy = array ? [].concat(array) : [];
if (index === undefined) {
arrayCopy.pop();
} else if (isNaN(index)) {
delete arrayCopy[index];
} else {
arrayCopy.splice(index, 1);
}
return (0, _write2.default)(path, arrayCopy, stateCopy);
}, _behaviors[_actionTypes.RESET] = function (state) {
var _extends3;
return _extends({}, (0, _resetState2.default)(state), (_extends3 = {
_active: undefined,
_asyncValidating: false
}, _extends3[globalErrorKey] = undefined, _extends3._initialized = state._initialized, _extends3._submitting = false, _extends3._submitFailed = false, _extends3));
}, _behaviors[_actionTypes.START_ASYNC_VALIDATION] = function (state, _ref7) {
var field = _ref7.field;
return _extends({}, state, {
_asyncValidating: field || true
});
}, _behaviors[_actionTypes.START_SUBMIT] = function (state) {
return _extends({}, state, {
_submitting: true
});
}, _behaviors[_actionTypes.STOP_ASYNC_VALIDATION] = function (state, _ref8) {
var _extends4;
var errors = _ref8.errors;
return _extends({}, (0, _setErrors2.default)(state, errors, 'asyncError'), (_extends4 = {
_asyncValidating: false
}, _extends4[globalErrorKey] = errors && errors[globalErrorKey], _extends4));
}, _behaviors[_actionTypes.STOP_SUBMIT] = function (state, _ref9) {
var _extends5;
var errors = _ref9.errors;
return _extends({}, (0, _setErrors2.default)(state, errors, 'submitError'), (_extends5 = {}, _extends5[globalErrorKey] = errors && errors[globalErrorKey], _extends5._submitting = false, _extends5._submitFailed = !!(errors && Object.keys(errors).length), _extends5));
}, _behaviors[_actionTypes.SUBMIT_FAILED] = function (state) {
return _extends({}, state, {
_submitFailed: true
});
}, _behaviors[_actionTypes.SWAP_ARRAY_VALUES] = function (state, _ref10) {
var path = _ref10.path;
var indexA = _ref10.indexA;
var indexB = _ref10.indexB;
var array = (0, _read2.default)(path, state);
var arrayLength = array.length;
if (indexA === indexB || isNaN(indexA) || isNaN(indexB) || indexA >= arrayLength || indexB >= arrayLength) {
return state; // do nothing
}
var stateCopy = _extends({}, state);
var arrayCopy = [].concat(array);
arrayCopy[indexA] = array[indexB];
arrayCopy[indexB] = array[indexA];
return (0, _write2.default)(path, arrayCopy, stateCopy);
}, _behaviors[_actionTypes.TOUCH] = function (state, _ref11) {
var fields = _ref11.fields;
return _extends({}, state, fields.reduce(function (accumulator, field) {
return (0, _write2.default)(field, function (value) {
return (0, _fieldValue.makeFieldValue)(_extends({}, value, { touched: true }));
}, accumulator);
}, state));
}, _behaviors[_actionTypes.UNTOUCH] = function (state, _ref12) {
var fields = _ref12.fields;
return _extends({}, state, fields.reduce(function (accumulator, field) {
return (0, _write2.default)(field, function (value) {
if (value) {
var touched = value.touched;
var rest = _objectWithoutProperties(value, ['touched']);
return (0, _fieldValue.makeFieldValue)(rest);
}
return (0, _fieldValue.makeFieldValue)(value);
}, accumulator);
}, state));
}, _behaviors);
var reducer = function reducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var behavior = behaviors[action.type];
return behavior ? behavior(state, action) : state;
};
function formReducer() {
var _extends11;
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var form = action.form;
var key = action.key;
var rest = _objectWithoutProperties(action, ['form', 'key']); // eslint-disable-line no-redeclare
if (!form) {
return state;
}
if (key) {
var _extends8, _extends9;
if (action.type === _actionTypes.DESTROY) {
var _extends7;
return _extends({}, state, (_extends7 = {}, _extends7[form] = state[form] && Object.keys(state[form]).reduce(function (accumulator, stateKey) {
var _extends6;
return stateKey === key ? accumulator : _extends({}, accumulator, (_extends6 = {}, _extends6[stateKey] = state[form][stateKey], _extends6));
}, {}), _extends7));
}
return _extends({}, state, (_extends9 = {}, _extends9[form] = _extends({}, state[form], (_extends8 = {}, _extends8[key] = reducer((state[form] || {})[key], rest), _extends8)), _extends9));
}
if (action.type === _actionTypes.DESTROY) {
return Object.keys(state).reduce(function (accumulator, formName) {
var _extends10;
return formName === form ? accumulator : _extends({}, accumulator, (_extends10 = {}, _extends10[formName] = state[formName], _extends10));
}, {});
}
return _extends({}, state, (_extends11 = {}, _extends11[form] = reducer(state[form], rest), _extends11));
}
/**
* Adds additional functionality to the reducer
*/
function decorate(target) {
target.plugin = function plugin(reducers) {
var _this = this;
// use 'function' keyword to enable 'this'
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this(state, action);
return _extends({}, result, (0, _mapValues2.default)(reducers, function (pluginReducer, key) {
return pluginReducer(result[key] || initialState, action);
}));
});
};
target.normalize = function normalize(normalizers) {
var _this2 = this;
// use 'function' keyword to enable 'this'
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this2(state, action);
return _extends({}, result, (0, _mapValues2.default)(normalizers, function (formNormalizers, form) {
var runNormalize = function runNormalize(previous, currentResult) {
var previousValues = (0, _getValuesFromState2.default)(_extends({}, initialState, previous));
var formResult = _extends({}, initialState, currentResult);
var values = (0, _getValuesFromState2.default)(formResult);
return (0, _normalizeFields2.default)(formNormalizers, formResult, previous, values, previousValues);
};
if (action.key) {
var _extends12;
return _extends({}, result[form], (_extends12 = {}, _extends12[action.key] = runNormalize(state[form][action.key], result[form][action.key]), _extends12));
}
return runNormalize(state[form], result[form]);
}));
});
};
return target;
}
exports.default = decorate(formReducer);
/***/ },
/* 18 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
/**
* Writes any potentially deep value from an object using dot and array syntax,
* and returns a new copy of the object.
*/
var write = function write(path, value, object) {
var _extends7;
var dotIndex = path.indexOf('.');
if (dotIndex === 0) {
return write(path.substring(1), value, object);
}
var openIndex = path.indexOf('[');
var closeIndex = path.indexOf(']');
if (dotIndex >= 0 && (openIndex < 0 || dotIndex < openIndex)) {
var _extends2;
// is dot notation
var key = path.substring(0, dotIndex);
return _extends({}, object, (_extends2 = {}, _extends2[key] = write(path.substring(dotIndex + 1), value, object[key] || {}), _extends2));
}
if (openIndex >= 0 && (dotIndex < 0 || openIndex < dotIndex)) {
var _ret = function () {
var _extends6;
// is array notation
if (closeIndex < 0) {
throw new Error('found [ but no ]');
}
var key = path.substring(0, openIndex);
var index = path.substring(openIndex + 1, closeIndex);
var array = object[key] || [];
var rest = path.substring(closeIndex + 1);
if (index) {
var _extends4;
// indexed array
if (rest.length) {
var _extends3;
// need to keep recursing
var dest = array[index] || {};
var arrayCopy = [].concat(array);
arrayCopy[index] = write(rest, value, dest);
return {
v: _extends({}, object || {}, (_extends3 = {}, _extends3[key] = arrayCopy, _extends3))
};
}
var copy = [].concat(array);
copy[index] = typeof value === 'function' ? value(copy[index]) : value;
return {
v: _extends({}, object || {}, (_extends4 = {}, _extends4[key] = copy, _extends4))
};
}
// indexless array
if (rest.length) {
var _extends5;
// need to keep recursing
if ((!array || !array.length) && typeof value === 'function') {
return {
v: object
}; // don't even set a value under [key]
}
var _arrayCopy = array.map(function (dest) {
return write(rest, value, dest);
});
return {
v: _extends({}, object || {}, (_extends5 = {}, _extends5[key] = _arrayCopy, _extends5))
};
}
var result = void 0;
if (Array.isArray(value)) {
result = value;
} else if (object[key]) {
result = array.map(function (dest) {
return typeof value === 'function' ? value(dest) : value;
});
} else if (typeof value === 'function') {
return {
v: object
}; // don't even set a value under [key]
} else {
result = value;
}
return {
v: _extends({}, object || {}, (_extends6 = {}, _extends6[key] = result, _extends6))
};
}();
if (typeof _ret === "object") return _ret.v;
}
return _extends({}, object, (_extends7 = {}, _extends7[path] = typeof value === 'function' ? value(object[path]) : value, _extends7));
};
exports.default = write;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var pSlice = Array.prototype.slice;
var objectKeys = __webpack_require__(52);
var isArguments = __webpack_require__(51);
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) {
var keys = Object.getOwnPropertyNames(sourceComponent);
for (var i=0; i<keys.length; ++i) {
if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) {
try {
targetComponent[keys[i]] = sourceComponent[keys[i]];
} catch (error) {
}
}
}
return targetComponent;
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
exports["default"] = _react.PropTypes.shape({
subscribe: _react.PropTypes.func.isRequired,
dispatch: _react.PropTypes.func.isRequired,
getState: _react.PropTypes.func.isRequired
});
/***/ },
/* 22 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = compose;
/**
* Composes single-argument functions from right to left.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing functions from right to
* left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
*/
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return function () {
if (funcs.length === 0) {
return arguments.length <= 0 ? undefined : arguments[0];
}
var last = funcs[funcs.length - 1];
var rest = funcs.slice(0, -1);
return rest.reduceRight(function (composed, f) {
return f(composed);
}, last.apply(undefined, arguments));
};
}
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.ActionTypes = undefined;
exports["default"] = createStore;
var _isPlainObject = __webpack_require__(26);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = exports.ActionTypes = {
INIT: '@@redux/INIT'
};
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [initialState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} enhancer The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, initialState, enhancer) {
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
enhancer = initialState;
initialState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
return enhancer(createStore)(reducer, initialState);
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = initialState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all states changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!(0, _isPlainObject2["default"])(action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.');
}
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
};
}
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined;
var _createStore = __webpack_require__(23);
var _createStore2 = _interopRequireDefault(_createStore);
var _combineReducers = __webpack_require__(67);
var _combineReducers2 = _interopRequireDefault(_combineReducers);
var _bindActionCreators = __webpack_require__(66);
var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators);
var _applyMiddleware = __webpack_require__(65);
var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware);
var _compose = __webpack_require__(22);
var _compose2 = _interopRequireDefault(_compose);
var _warning = __webpack_require__(25);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
(0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
}
exports.createStore = _createStore2["default"];
exports.combineReducers = _combineReducers2["default"];
exports.bindActionCreators = _bindActionCreators2["default"];
exports.applyMiddleware = _applyMiddleware2["default"];
exports.compose = _compose2["default"];
/***/ },
/* 25 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = warning;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var getPrototype = __webpack_require__(68),
isHostObject = __webpack_require__(69),
isObjectLike = __webpack_require__(70);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object,
* else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isPromise = __webpack_require__(6);
var _isPromise2 = _interopRequireDefault(_isPromise);
var _isValid = __webpack_require__(2);
var _isValid2 = _interopRequireDefault(_isValid);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var asyncValidation = function asyncValidation(fn, start, stop, field) {
start(field);
var promise = fn();
if (!(0, _isPromise2.default)(promise)) {
throw new Error('asyncValidate function passed to reduxForm must return a promise');
}
var handleErrors = function handleErrors(rejected) {
return function (errors) {
if (!(0, _isValid2.default)(errors)) {
stop(errors);
return Promise.reject();
} else if (rejected) {
stop();
throw new Error('Asynchronous validation promise was rejected without errors.');
}
stop();
return Promise.resolve();
};
};
return promise.then(handleErrors(false), handleErrors(true));
};
exports.default = asyncValidation;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = createAll;
var _reducer = __webpack_require__(17);
var _reducer2 = _interopRequireDefault(_reducer);
var _createReduxForm = __webpack_require__(31);
var _createReduxForm2 = _interopRequireDefault(_createReduxForm);
var _mapValues = __webpack_require__(5);
var _mapValues2 = _interopRequireDefault(_mapValues);
var _bindActionData = __webpack_require__(8);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _actions = __webpack_require__(7);
var actions = _interopRequireWildcard(_actions);
var _actionTypes = __webpack_require__(4);
var actionTypes = _interopRequireWildcard(_actionTypes);
var _createPropTypes = __webpack_require__(30);
var _createPropTypes2 = _interopRequireDefault(_createPropTypes);
var _getValuesFromState = __webpack_require__(15);
var _getValuesFromState2 = _interopRequireDefault(_getValuesFromState);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// bind form as first parameter of action creators
var boundActions = _extends({}, (0, _mapValues2.default)(_extends({}, actions, {
changeWithKey: function changeWithKey(key) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return (0, _bindActionData2.default)(actions.change, { key: key }).apply(undefined, args);
},
initializeWithKey: function initializeWithKey(key) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
return (0, _bindActionData2.default)(actions.initialize, { key: key }).apply(undefined, args);
},
reset: function reset(key) {
return (0, _bindActionData2.default)(actions.reset, { key: key })();
},
touchWithKey: function touchWithKey(key) {
for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return (0, _bindActionData2.default)(actions.touch, { key: key }).apply(undefined, args);
},
untouchWithKey: function untouchWithKey(key) {
for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
return (0, _bindActionData2.default)(actions.untouch, { key: key }).apply(undefined, args);
},
destroy: function destroy(key) {
return (0, _bindActionData2.default)(actions.destroy, { key: key })();
}
}), function (action) {
return function (form) {
for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
args[_key5 - 1] = arguments[_key5];
}
return (0, _bindActionData2.default)(action, { form: form }).apply(undefined, args);
};
}));
var addArrayValue = boundActions.addArrayValue;
var blur = boundActions.blur;
var change = boundActions.change;
var changeWithKey = boundActions.changeWithKey;
var destroy = boundActions.destroy;
var focus = boundActions.focus;
var initialize = boundActions.initialize;
var initializeWithKey = boundActions.initializeWithKey;
var removeArrayValue = boundActions.removeArrayValue;
var reset = boundActions.reset;
var startAsyncValidation = boundActions.startAsyncValidation;
var startSubmit = boundActions.startSubmit;
var stopAsyncValidation = boundActions.stopAsyncValidation;
var stopSubmit = boundActions.stopSubmit;
var submitFailed = boundActions.submitFailed;
var swapArrayValues = boundActions.swapArrayValues;
var touch = boundActions.touch;
var touchWithKey = boundActions.touchWithKey;
var untouch = boundActions.untouch;
var untouchWithKey = boundActions.untouchWithKey;
function createAll(isReactNative, React, connect) {
return {
actionTypes: actionTypes,
addArrayValue: addArrayValue,
blur: blur,
change: change,
changeWithKey: changeWithKey,
destroy: destroy,
focus: focus,
getValues: _getValuesFromState2.default,
initialize: initialize,
initializeWithKey: initializeWithKey,
propTypes: (0, _createPropTypes2.default)(React),
reduxForm: (0, _createReduxForm2.default)(isReactNative, React, connect),
reducer: _reducer2.default,
removeArrayValue: removeArrayValue,
reset: reset,
startAsyncValidation: startAsyncValidation,
startSubmit: startSubmit,
stopAsyncValidation: stopAsyncValidation,
stopSubmit: stopSubmit,
submitFailed: submitFailed,
swapArrayValues: swapArrayValues,
touch: touch,
touchWithKey: touchWithKey,
untouch: untouch,
untouchWithKey: untouchWithKey
};
}
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _actions = __webpack_require__(7);
var importedActions = _interopRequireWildcard(_actions);
var _getDisplayName = __webpack_require__(13);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _reducer = __webpack_require__(17);
var _deepEqual = __webpack_require__(19);
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _bindActionData = __webpack_require__(8);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _getValues = __webpack_require__(14);
var _getValues2 = _interopRequireDefault(_getValues);
var _isValid = __webpack_require__(2);
var _isValid2 = _interopRequireDefault(_isValid);
var _readFields = __webpack_require__(43);
var _readFields2 = _interopRequireDefault(_readFields);
var _handleSubmit2 = __webpack_require__(38);
var _handleSubmit3 = _interopRequireDefault(_handleSubmit2);
var _asyncValidation = __webpack_require__(27);
var _asyncValidation2 = _interopRequireDefault(_asyncValidation);
var _silenceEvents = __webpack_require__(37);
var _silenceEvents2 = _interopRequireDefault(_silenceEvents);
var _silenceEvent = __webpack_require__(12);
var _silenceEvent2 = _interopRequireDefault(_silenceEvent);
var _wrapMapDispatchToProps = __webpack_require__(49);
var _wrapMapDispatchToProps2 = _interopRequireDefault(_wrapMapDispatchToProps);
var _wrapMapStateToProps = __webpack_require__(50);
var _wrapMapStateToProps2 = _interopRequireDefault(_wrapMapStateToProps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Creates a HOC that knows how to create redux-connected sub-components.
*/
var createHigherOrderComponent = function createHigherOrderComponent(config, isReactNative, React, connect, WrappedComponent, mapStateToProps, mapDispatchToProps, mergeProps, options) {
var Component = React.Component;
var PropTypes = React.PropTypes;
return function (reduxMountPoint, formName, formKey, getFormState) {
var ReduxForm = function (_Component) {
_inherits(ReduxForm, _Component);
function ReduxForm(props) {
_classCallCheck(this, ReduxForm);
// bind functions
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.asyncValidate = _this.asyncValidate.bind(_this);
_this.handleSubmit = _this.handleSubmit.bind(_this);
_this.fields = (0, _readFields2.default)(props, {}, {}, _this.asyncValidate, isReactNative);
var submitPassback = _this.props.submitPassback;
submitPassback(function () {
return _this.handleSubmit();
}); // wrapped in function to disallow params
return _this;
}
ReduxForm.prototype.componentWillMount = function componentWillMount() {
var _props = this.props;
var fields = _props.fields;
var form = _props.form;
var initialize = _props.initialize;
var initialValues = _props.initialValues;
if (initialValues && !form._initialized) {
initialize(initialValues, fields);
}
};
ReduxForm.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!(0, _deepEqual2.default)(this.props.fields, nextProps.fields) || !(0, _deepEqual2.default)(this.props.form, nextProps.form, { strict: true })) {
this.fields = (0, _readFields2.default)(nextProps, this.props, this.fields, this.asyncValidate, isReactNative);
}
if (!(0, _deepEqual2.default)(this.props.initialValues, nextProps.initialValues)) {
this.props.initialize(nextProps.initialValues, nextProps.fields);
}
};
ReduxForm.prototype.componentWillUnmount = function componentWillUnmount() {
if (config.destroyOnUnmount) {
this.props.destroy();
}
};
ReduxForm.prototype.asyncValidate = function asyncValidate(name, value) {
var _this2 = this;
var _props2 = this.props;
var asyncValidate = _props2.asyncValidate;
var dispatch = _props2.dispatch;
var fields = _props2.fields;
var form = _props2.form;
var startAsyncValidation = _props2.startAsyncValidation;
var stopAsyncValidation = _props2.stopAsyncValidation;
var validate = _props2.validate;
var isSubmitting = !name;
if (asyncValidate) {
var _ret = function () {
var values = (0, _getValues2.default)(fields, form);
if (name) {
values[name] = value;
}
var syncErrors = validate(values, _this2.props);
var allPristine = _this2.fields._meta.allPristine;
var initialized = form._initialized;
// if blur validating, only run async validate if sync validation passes
// and submitting (not blur validation) or form is dirty or form was never initialized
var syncValidationPasses = isSubmitting || (0, _isValid2.default)(syncErrors[name]);
if (syncValidationPasses && (isSubmitting || !allPristine || !initialized)) {
return {
v: (0, _asyncValidation2.default)(function () {
return asyncValidate(values, dispatch, _this2.props);
}, startAsyncValidation, stopAsyncValidation, name)
};
}
}();
if (typeof _ret === "object") return _ret.v;
}
};
ReduxForm.prototype.handleSubmit = function handleSubmit(submitOrEvent) {
var _this3 = this;
var _props3 = this.props;
var onSubmit = _props3.onSubmit;
var fields = _props3.fields;
var form = _props3.form;
var check = function check(submit) {
if (!submit || typeof submit !== 'function') {
throw new Error('You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop');
}
return submit;
};
return !submitOrEvent || (0, _silenceEvent2.default)(submitOrEvent) ?
// submitOrEvent is an event: fire submit
(0, _handleSubmit3.default)(check(onSubmit), (0, _getValues2.default)(fields, form), this.props, this.asyncValidate) :
// submitOrEvent is the submit function: return deferred submit thunk
(0, _silenceEvents2.default)(function () {
return (0, _handleSubmit3.default)(check(submitOrEvent), (0, _getValues2.default)(fields, form), _this3.props, _this3.asyncValidate);
});
};
ReduxForm.prototype.render = function render() {
var _this4 = this,
_ref;
var allFields = this.fields;
var _props4 = this.props;
var addArrayValue = _props4.addArrayValue;
var asyncBlurFields = _props4.asyncBlurFields;
var blur = _props4.blur;
var change = _props4.change;
var destroy = _props4.destroy;
var focus = _props4.focus;
var fields = _props4.fields;
var form = _props4.form;
var initialValues = _props4.initialValues;
var initialize = _props4.initialize;
var onSubmit = _props4.onSubmit;
var propNamespace = _props4.propNamespace;
var reset = _props4.reset;
var removeArrayValue = _props4.removeArrayValue;
var returnRejectedSubmitPromise = _props4.returnRejectedSubmitPromise;
var startAsyncValidation = _props4.startAsyncValidation;
var startSubmit = _props4.startSubmit;
var stopAsyncValidation = _props4.stopAsyncValidation;
var stopSubmit = _props4.stopSubmit;
var submitFailed = _props4.submitFailed;
var swapArrayValues = _props4.swapArrayValues;
var touch = _props4.touch;
var untouch = _props4.untouch;
var validate = _props4.validate;
var passableProps = _objectWithoutProperties(_props4, ['addArrayValue', 'asyncBlurFields', 'blur', 'change', 'destroy', 'focus', 'fields', 'form', 'initialValues', 'initialize', 'onSubmit', 'propNamespace', 'reset', 'removeArrayValue', 'returnRejectedSubmitPromise', 'startAsyncValidation', 'startSubmit', 'stopAsyncValidation', 'stopSubmit', 'submitFailed', 'swapArrayValues', 'touch', 'untouch', 'validate']); // eslint-disable-line no-redeclare
var _allFields$_meta = allFields._meta;
var allPristine = _allFields$_meta.allPristine;
var allValid = _allFields$_meta.allValid;
var errors = _allFields$_meta.errors;
var formError = _allFields$_meta.formError;
var values = _allFields$_meta.values;
var props = {
// State:
active: form._active,
asyncValidating: form._asyncValidating,
dirty: !allPristine,
error: formError,
errors: errors,
fields: allFields,
formKey: formKey,
invalid: !allValid,
pristine: allPristine,
submitting: form._submitting,
submitFailed: form._submitFailed,
valid: allValid,
values: values,
// Actions:
asyncValidate: (0, _silenceEvents2.default)(function () {
return _this4.asyncValidate();
}),
// ^ doesn't just pass this.asyncValidate to disallow values passing
destroyForm: (0, _silenceEvents2.default)(destroy),
handleSubmit: this.handleSubmit,
initializeForm: (0, _silenceEvents2.default)(function (initValues) {
return initialize(initValues, fields);
}),
resetForm: (0, _silenceEvents2.default)(reset),
touch: (0, _silenceEvents2.default)(function () {
return touch.apply(undefined, arguments);
}),
touchAll: (0, _silenceEvents2.default)(function () {
return touch.apply(undefined, fields);
}),
untouch: (0, _silenceEvents2.default)(function () {
return untouch.apply(undefined, arguments);
}),
untouchAll: (0, _silenceEvents2.default)(function () {
return untouch.apply(undefined, fields);
})
};
var passedProps = propNamespace ? (_ref = {}, _ref[propNamespace] = props, _ref) : props;
return React.createElement(WrappedComponent, _extends({}, passableProps, passedProps));
};
return ReduxForm;
}(Component);
ReduxForm.displayName = 'ReduxForm(' + (0, _getDisplayName2.default)(WrappedComponent) + ')';
ReduxForm.WrappedComponent = WrappedComponent;
ReduxForm.propTypes = {
// props:
asyncBlurFields: PropTypes.arrayOf(PropTypes.string),
asyncValidate: PropTypes.func,
dispatch: PropTypes.func.isRequired,
fields: PropTypes.arrayOf(PropTypes.string).isRequired,
form: PropTypes.object,
initialValues: PropTypes.any,
onSubmit: PropTypes.func,
propNamespace: PropTypes.string,
readonly: PropTypes.bool,
returnRejectedSubmitPromise: PropTypes.bool,
submitPassback: PropTypes.func.isRequired,
validate: PropTypes.func,
// actions:
addArrayValue: PropTypes.func.isRequired,
blur: PropTypes.func.isRequired,
change: PropTypes.func.isRequired,
destroy: PropTypes.func.isRequired,
focus: PropTypes.func.isRequired,
initialize: PropTypes.func.isRequired,
removeArrayValue: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
startAsyncValidation: PropTypes.func.isRequired,
startSubmit: PropTypes.func.isRequired,
stopAsyncValidation: PropTypes.func.isRequired,
stopSubmit: PropTypes.func.isRequired,
submitFailed: PropTypes.func.isRequired,
swapArrayValues: PropTypes.func.isRequired,
touch: PropTypes.func.isRequired,
untouch: PropTypes.func.isRequired
};
ReduxForm.defaultProps = {
asyncBlurFields: [],
form: _reducer.initialState,
readonly: false,
returnRejectedSubmitPromise: false,
validate: function validate() {
return {};
}
};
// bind touch flags to blur and change
var unboundActions = _extends({}, importedActions, {
blur: (0, _bindActionData2.default)(importedActions.blur, {
touch: !!config.touchOnBlur
}),
change: (0, _bindActionData2.default)(importedActions.change, {
touch: !!config.touchOnChange
})
});
// make redux connector with or without form key
var decorate = formKey !== undefined && formKey !== null ? connect((0, _wrapMapStateToProps2.default)(mapStateToProps, function (state) {
var formState = getFormState(state, reduxMountPoint);
if (!formState) {
throw new Error('You need to mount the redux-form reducer at "' + reduxMountPoint + '"');
}
return formState && formState[formName] && formState[formName][formKey];
}), (0, _wrapMapDispatchToProps2.default)(mapDispatchToProps, (0, _bindActionData2.default)(unboundActions, {
form: formName,
key: formKey
})), mergeProps, options) : connect((0, _wrapMapStateToProps2.default)(mapStateToProps, function (state) {
var formState = getFormState(state, reduxMountPoint);
if (!formState) {
throw new Error('You need to mount the redux-form reducer at "' + reduxMountPoint + '"');
}
return formState && formState[formName];
}), (0, _wrapMapDispatchToProps2.default)(mapDispatchToProps, (0, _bindActionData2.default)(unboundActions, { form: formName })), mergeProps, options);
return decorate(ReduxForm);
};
};
exports.default = createHigherOrderComponent;
/***/ },
/* 30 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var createPropTypes = function createPropTypes(_ref) {
var _ref$PropTypes = _ref.PropTypes;
var any = _ref$PropTypes.any;
var bool = _ref$PropTypes.bool;
var string = _ref$PropTypes.string;
var func = _ref$PropTypes.func;
var object = _ref$PropTypes.object;
return {
// State:
active: string, // currently active field
asyncValidating: bool.isRequired, // true if async validation is running
dirty: bool.isRequired, // true if any values are different from initialValues
error: any, // form-wide error from '_error' key in validation result
errors: object, // a map of errors corresponding to structure of form data (result of validation)
fields: object.isRequired, // the map of fields
formKey: any, // the form key if one was provided (used when doing multirecord forms)
invalid: bool.isRequired, // true if there are any validation errors
pristine: bool.isRequired, // true if the values are the same as initialValues
submitting: bool.isRequired, // true if the form is in the process of being submitted
submitFailed: bool.isRequired, // true if the form was submitted and failed for any reason
valid: bool.isRequired, // true if there are no validation errors
values: object.isRequired, // the values of the form as they will be submitted
// Actions:
asyncValidate: func.isRequired, // function to trigger async validation
destroyForm: func.isRequired, // action to destroy the form's data in Redux
handleSubmit: func.isRequired, // function to submit the form
initializeForm: func.isRequired, // action to initialize form data
resetForm: func.isRequired, // action to reset the form data to previously initialized values
touch: func.isRequired, // action to mark fields as touched
touchAll: func.isRequired, // action to mark ALL fields as touched
untouch: func.isRequired, // action to mark fields as untouched
untouchAll: func.isRequired // action to mark ALL fields as untouched
};
};
exports.default = createPropTypes;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createReduxFormConnector = __webpack_require__(32);
var _createReduxFormConnector2 = _interopRequireDefault(_createReduxFormConnector);
var _hoistNonReactStatics = __webpack_require__(20);
var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* The decorator that is the main API to redux-form
*/
var createReduxForm = function createReduxForm(isReactNative, React, connect) {
var Component = React.Component;
var reduxFormConnector = (0, _createReduxFormConnector2.default)(isReactNative, React, connect);
return function (config, mapStateToProps, mapDispatchToProps, mergeProps, options) {
return function (WrappedComponent) {
var ReduxFormConnector = reduxFormConnector(WrappedComponent, mapStateToProps, mapDispatchToProps, mergeProps, options);
var configWithDefaults = _extends({
touchOnBlur: true,
touchOnChange: false,
destroyOnUnmount: true
}, config);
var ConnectedForm = function (_Component) {
_inherits(ConnectedForm, _Component);
function ConnectedForm(props) {
_classCallCheck(this, ConnectedForm);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.handleSubmitPassback = _this.handleSubmitPassback.bind(_this);
return _this;
}
ConnectedForm.prototype.handleSubmitPassback = function handleSubmitPassback(submit) {
this.submit = submit;
};
ConnectedForm.prototype.render = function render() {
return React.createElement(ReduxFormConnector, _extends({}, configWithDefaults, this.props, {
submitPassback: this.handleSubmitPassback }));
};
return ConnectedForm;
}(Component);
return (0, _hoistNonReactStatics2.default)(ConnectedForm, WrappedComponent);
};
};
};
exports.default = createReduxForm;
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _noGetters = __webpack_require__(55);
var _noGetters2 = _interopRequireDefault(_noGetters);
var _getDisplayName = __webpack_require__(13);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _createHigherOrderComponent = __webpack_require__(29);
var _createHigherOrderComponent2 = _interopRequireDefault(_createHigherOrderComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* This component tracks props that affect how the form is mounted to the store. Normally these should not change,
* but if they do, the connected components below it need to be redefined.
*/
var createReduxFormConnector = function createReduxFormConnector(isReactNative, React, connect) {
return function (WrappedComponent, mapStateToProps, mapDispatchToProps, mergeProps, options) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var ReduxFormConnector = function (_Component) {
_inherits(ReduxFormConnector, _Component);
function ReduxFormConnector(props) {
_classCallCheck(this, ReduxFormConnector);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.cache = new _noGetters2.default(_this, {
ReduxForm: {
params: [
// props that effect how redux-form connects to the redux store
'reduxMountPoint', 'form', 'formKey', 'getFormState'],
fn: (0, _createHigherOrderComponent2.default)(props, isReactNative, React, connect, WrappedComponent, mapStateToProps, mapDispatchToProps, mergeProps, options)
}
});
return _this;
}
ReduxFormConnector.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.cache.componentWillReceiveProps(nextProps);
};
ReduxFormConnector.prototype.render = function render() {
var ReduxForm = this.cache.get('ReduxForm');
// remove some redux-form config-only props
var _props = this.props;
var reduxMountPoint = _props.reduxMountPoint;
var destroyOnUnmount = _props.destroyOnUnmount;
var form = _props.form;
var getFormState = _props.getFormState;
var touchOnBlur = _props.touchOnBlur;
var touchOnChange = _props.touchOnChange;
var passableProps = _objectWithoutProperties(_props, ['reduxMountPoint', 'destroyOnUnmount', 'form', 'getFormState', 'touchOnBlur', 'touchOnChange']); // eslint-disable-line no-redeclare
return React.createElement(ReduxForm, passableProps);
};
return ReduxFormConnector;
}(Component);
ReduxFormConnector.displayName = 'ReduxFormConnector(' + (0, _getDisplayName2.default)(WrappedComponent) + ')';
ReduxFormConnector.WrappedComponent = WrappedComponent;
ReduxFormConnector.propTypes = {
destroyOnUnmount: PropTypes.bool,
reduxMountPoint: PropTypes.string,
form: PropTypes.string.isRequired,
formKey: PropTypes.string,
getFormState: PropTypes.func,
touchOnBlur: PropTypes.bool,
touchOnChange: PropTypes.bool
};
ReduxFormConnector.defaultProps = {
reduxMountPoint: 'form',
getFormState: function getFormState(state, reduxMountPoint) {
return state[reduxMountPoint];
}
};
return ReduxFormConnector;
};
};
exports.default = createReduxFormConnector;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _getValue = __webpack_require__(10);
var _getValue2 = _interopRequireDefault(_getValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createOnBlur = function createOnBlur(name, blur, isReactNative, afterBlur) {
return function (event) {
var value = (0, _getValue2.default)(event, isReactNative);
blur(name, value);
if (afterBlur) {
afterBlur(name, value);
}
};
};
exports.default = createOnBlur;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _getValue = __webpack_require__(10);
var _getValue2 = _interopRequireDefault(_getValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createOnChange = function createOnChange(name, change, isReactNative) {
return function (event) {
return change(name, (0, _getValue2.default)(event, isReactNative));
};
};
exports.default = createOnChange;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createOnDragStart = __webpack_require__(9);
var createOnDrop = function createOnDrop(name, change) {
return function (event) {
change(name, event.dataTransfer.getData(_createOnDragStart.dataKey));
};
};
exports.default = createOnDrop;
/***/ },
/* 36 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var createOnFocus = function createOnFocus(name, focus) {
return function () {
return focus(name);
};
};
exports.default = createOnFocus;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _silenceEvent = __webpack_require__(12);
var _silenceEvent2 = _interopRequireDefault(_silenceEvent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var silenceEvents = function silenceEvents(fn) {
return function (event) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return (0, _silenceEvent2.default)(event) ? fn.apply(undefined, args) : fn.apply(undefined, [event].concat(args));
};
};
exports.default = silenceEvents;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isPromise = __webpack_require__(6);
var _isPromise2 = _interopRequireDefault(_isPromise);
var _isValid = __webpack_require__(2);
var _isValid2 = _interopRequireDefault(_isValid);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var handleSubmit = function handleSubmit(submit, values, props, asyncValidate) {
var dispatch = props.dispatch;
var fields = props.fields;
var startSubmit = props.startSubmit;
var stopSubmit = props.stopSubmit;
var submitFailed = props.submitFailed;
var returnRejectedSubmitPromise = props.returnRejectedSubmitPromise;
var touch = props.touch;
var validate = props.validate;
var syncErrors = validate(values, props);
touch.apply(undefined, fields); // touch all fields
if ((0, _isValid2.default)(syncErrors)) {
var doSubmit = function doSubmit() {
var result = submit(values, dispatch);
if ((0, _isPromise2.default)(result)) {
startSubmit();
return result.then(function (submitResult) {
stopSubmit();
return submitResult;
}, function (submitError) {
stopSubmit(submitError);
if (returnRejectedSubmitPromise) {
return Promise.reject(submitError);
}
});
}
return result;
};
var asyncValidateResult = asyncValidate();
return (0, _isPromise2.default)(asyncValidateResult) ?
// asyncValidateResult will be rejected if async validation failed
asyncValidateResult.then(doSubmit, function () {
submitFailed();
return returnRejectedSubmitPromise ? Promise.reject() : Promise.resolve();
}) : doSubmit(); // no async validation, so submit
}
submitFailed();
if (returnRejectedSubmitPromise) {
return Promise.reject(syncErrors);
}
};
exports.default = handleSubmit;
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _fieldValue = __webpack_require__(1);
var makeEntry = function makeEntry(value) {
return (0, _fieldValue.makeFieldValue)(value === undefined ? {} : { initial: value, value: value });
};
/**
* Sets the initial values into the state and returns a new copy of the state
*/
var initializeState = function initializeState(values, fields) {
var state = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!fields) {
throw new Error('fields must be passed when initializing state');
}
if (!values || !fields.length) {
return state;
}
var initializeField = function initializeField(path, src, dest) {
var dotIndex = path.indexOf('.');
if (dotIndex === 0) {
return initializeField(path.substring(1), src, dest);
}
var openIndex = path.indexOf('[');
var closeIndex = path.indexOf(']');
var result = _extends({}, dest) || {};
if (dotIndex >= 0 && (openIndex < 0 || dotIndex < openIndex)) {
// is dot notation
var key = path.substring(0, dotIndex);
result[key] = src[key] && initializeField(path.substring(dotIndex + 1), src[key], result[key] || {});
} else if (openIndex >= 0 && (dotIndex < 0 || openIndex < dotIndex)) {
(function () {
// is array notation
if (closeIndex < 0) {
throw new Error('found \'[\' but no \']\': \'' + path + '\'');
}
var key = path.substring(0, openIndex);
var srcArray = src[key];
var destArray = result[key];
var rest = path.substring(closeIndex + 1);
if (Array.isArray(srcArray)) {
if (rest.length) {
// need to keep recursing
result[key] = srcArray.map(function (srcValue, srcIndex) {
return initializeField(rest, srcValue, destArray && destArray[srcIndex]);
});
} else {
result[key] = srcArray.map(function (srcValue) {
return makeEntry(srcValue);
});
}
} else {
result[key] = [];
}
})();
} else {
result[path] = makeEntry(src && src[path]);
}
return result;
};
return fields.reduce(function (accumulator, field) {
return initializeField(field, values, accumulator);
}, _extends({}, state));
};
exports.default = initializeState;
/***/ },
/* 40 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = isPristine;
function isPristine(initial, data) {
if (initial === data) {
return true;
}
if (typeof initial === 'boolean' || typeof data === 'boolean') {
return initial === data;
} else if (initial instanceof Date && data instanceof Date) {
return initial.getTime() === data.getTime();
} else if (initial && typeof initial === 'object') {
if (!data || typeof data !== 'object') {
return false;
}
var initialKeys = Object.keys(initial);
var dataKeys = Object.keys(data);
if (initialKeys.length !== dataKeys.length) {
return false;
}
for (var index = 0; index < dataKeys.length; index++) {
var key = dataKeys[index];
if (!isPristine(initial[key], data[key])) {
return false;
}
}
} else if (initial || data) {
// allow '' to equate to undefined or null
return initial === data;
}
return true;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = normalizeFields;
var _fieldValue = __webpack_require__(1);
function extractKey(field) {
var dotIndex = field.indexOf('.');
var openIndex = field.indexOf('[');
var closeIndex = field.indexOf(']');
if (openIndex > 0 && closeIndex !== openIndex + 1) {
throw new Error('found [ not followed by ]');
}
var isArray = openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex);
var key = void 0;
var nestedPath = void 0;
if (isArray) {
key = field.substring(0, openIndex);
nestedPath = field.substring(closeIndex + 1);
if (nestedPath[0] === '.') {
nestedPath = nestedPath.substring(1);
}
} else if (dotIndex > 0) {
key = field.substring(0, dotIndex);
nestedPath = field.substring(dotIndex + 1);
} else {
key = field;
}
return { isArray: isArray, key: key, nestedPath: nestedPath };
}
function normalizeField(field, fullFieldPath, state, previousState, values, previousValues, normalizers) {
if (field.isArray) {
if (field.nestedPath) {
var _ret = function () {
var array = state && state[field.key] || [];
var previousArray = previousState && previousState[field.key] || [];
var nestedField = extractKey(field.nestedPath);
return {
v: array.map(function (nestedState, i) {
nestedState[nestedField.key] = normalizeField(nestedField, fullFieldPath, nestedState, previousArray[i], values, previousValues, normalizers);
return nestedState;
})
};
}();
if (typeof _ret === "object") return _ret.v;
}
var _normalizer = normalizers[fullFieldPath];
var result = _normalizer(state && state[field.key], previousState && previousState[field.key], values, previousValues);
return field.isArray ? result && result.map(_fieldValue.makeFieldValue) : result;
} else if (field.nestedPath) {
var nestedState = state && state[field.key] || {};
var _nestedField = extractKey(field.nestedPath);
nestedState[_nestedField.key] = normalizeField(_nestedField, fullFieldPath, nestedState, previousState && previousState[field.key], values, previousValues, normalizers);
return nestedState;
}
var finalField = state && state[field.key] || {};
var normalizer = normalizers[fullFieldPath];
finalField.value = normalizer(finalField.value, previousState && previousState[field.key] && previousState[field.key].value, values, previousValues);
return (0, _fieldValue.makeFieldValue)(finalField);
}
function normalizeFields(normalizers, state, previousState, values, previousValues) {
var newState = Object.keys(normalizers).reduce(function (accumulator, field) {
var extracted = extractKey(field);
accumulator[extracted.key] = normalizeField(extracted, field, state, previousState, values, previousValues, normalizers);
return accumulator;
}, {});
return _extends({}, state, newState);
}
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createOnBlur = __webpack_require__(33);
var _createOnBlur2 = _interopRequireDefault(_createOnBlur);
var _createOnChange = __webpack_require__(34);
var _createOnChange2 = _interopRequireDefault(_createOnChange);
var _createOnDragStart = __webpack_require__(9);
var _createOnDragStart2 = _interopRequireDefault(_createOnDragStart);
var _createOnDrop = __webpack_require__(35);
var _createOnDrop2 = _interopRequireDefault(_createOnDrop);
var _createOnFocus = __webpack_require__(36);
var _createOnFocus2 = _interopRequireDefault(_createOnFocus);
var _silencePromise = __webpack_require__(47);
var _silencePromise2 = _interopRequireDefault(_silencePromise);
var _read = __webpack_require__(16);
var _read2 = _interopRequireDefault(_read);
var _updateField = __webpack_require__(48);
var _updateField2 = _interopRequireDefault(_updateField);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getSuffix(input, closeIndex) {
var suffix = input.substring(closeIndex + 1);
if (suffix[0] === '.') {
suffix = suffix.substring(1);
}
return suffix;
}
var getNextKey = function getNextKey(path) {
var dotIndex = path.indexOf('.');
var openIndex = path.indexOf('[');
if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) {
return path.substring(0, openIndex);
}
return dotIndex > 0 ? path.substring(0, dotIndex) : path;
};
var readField = function readField(state, fieldName) {
var pathToHere = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2];
var fields = arguments[3];
var syncErrors = arguments[4];
var asyncValidate = arguments[5];
var isReactNative = arguments[6];
var props = arguments[7];
var callback = arguments.length <= 8 || arguments[8] === undefined ? function () {
return null;
} : arguments[8];
var prefix = arguments.length <= 9 || arguments[9] === undefined ? '' : arguments[9];
var asyncBlurFields = props.asyncBlurFields;
var blur = props.blur;
var change = props.change;
var focus = props.focus;
var form = props.form;
var initialValues = props.initialValues;
var readonly = props.readonly;
var addArrayValue = props.addArrayValue;
var removeArrayValue = props.removeArrayValue;
var swapArrayValues = props.swapArrayValues;
var dotIndex = fieldName.indexOf('.');
var openIndex = fieldName.indexOf('[');
var closeIndex = fieldName.indexOf(']');
if (openIndex > 0 && closeIndex !== openIndex + 1) {
throw new Error('found [ not followed by ]');
}
if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) {
var _ret = function () {
// array field
var key = fieldName.substring(0, openIndex);
var rest = getSuffix(fieldName, closeIndex);
var stateArray = state && state[key] || [];
var fullPrefix = prefix + fieldName.substring(0, closeIndex + 1);
var subfields = props.fields.reduce(function (accumulator, field) {
if (field.indexOf(fullPrefix) === 0) {
accumulator.push(field);
}
return accumulator;
}, []).map(function (field) {
return getSuffix(field, prefix.length + closeIndex);
});
var addMethods = function addMethods(dest) {
Object.defineProperty(dest, 'addField', {
value: function value(_value, index) {
return addArrayValue(pathToHere + key, _value, index, subfields);
}
});
Object.defineProperty(dest, 'removeField', {
value: function value(index) {
return removeArrayValue(pathToHere + key, index);
}
});
Object.defineProperty(dest, 'swapFields', {
value: function value(indexA, indexB) {
return swapArrayValues(pathToHere + key, indexA, indexB);
}
});
return dest;
};
if (!fields[key] || fields[key].length !== stateArray.length) {
fields[key] = fields[key] ? [].concat(fields[key]) : [];
addMethods(fields[key]);
}
var fieldArray = fields[key];
var changed = false;
stateArray.forEach(function (fieldState, index) {
if (rest && !fieldArray[index]) {
fieldArray[index] = {};
changed = true;
}
var dest = rest ? fieldArray[index] : {};
var nextPath = '' + pathToHere + key + '[' + index + ']' + (rest ? '.' : '');
var nextPrefix = '' + prefix + key + '[]' + (rest ? '.' : '');
var result = readField(fieldState, rest, nextPath, dest, syncErrors, asyncValidate, isReactNative, props, callback, nextPrefix);
if (!rest && fieldArray[index] !== result) {
// if nothing after [] in field name, assign directly to array
fieldArray[index] = result;
changed = true;
}
});
if (fieldArray.length > stateArray.length) {
// remove extra items that aren't in state array
fieldArray.splice(stateArray.length, fieldArray.length - stateArray.length);
}
return {
v: changed ? addMethods([].concat(fieldArray)) : fieldArray
};
}();
if (typeof _ret === "object") return _ret.v;
}
if (dotIndex > 0) {
// subobject field
var _key = fieldName.substring(0, dotIndex);
var _rest = fieldName.substring(dotIndex + 1);
var subobject = fields[_key] || {};
var nextPath = pathToHere + _key + '.';
var nextKey = getNextKey(_rest);
var previous = subobject[nextKey];
var result = readField(state[_key] || {}, _rest, nextPath, subobject, syncErrors, asyncValidate, isReactNative, props, callback, nextPath);
if (result !== previous) {
var _extends2;
subobject = _extends({}, subobject, (_extends2 = {}, _extends2[nextKey] = result, _extends2));
}
fields[_key] = subobject;
return subobject;
}
var name = pathToHere + fieldName;
var field = fields[fieldName] || {};
if (field.name !== name) {
var onChange = (0, _createOnChange2.default)(name, change, isReactNative);
var initialFormValue = (0, _read2.default)(name + '.initial', form);
var initialValue = initialFormValue || (0, _read2.default)(name, initialValues);
field.name = name;
field.checked = initialValue === true || undefined;
field.value = initialValue;
field.initialValue = initialValue;
if (!readonly) {
field.onBlur = (0, _createOnBlur2.default)(name, blur, isReactNative, ~asyncBlurFields.indexOf(name) && function (blurName, blurValue) {
return (0, _silencePromise2.default)(asyncValidate(blurName, blurValue));
});
field.onChange = onChange;
field.onDragStart = (0, _createOnDragStart2.default)(name, function () {
return field.value;
});
field.onDrop = (0, _createOnDrop2.default)(name, change);
field.onFocus = (0, _createOnFocus2.default)(name, focus);
field.onUpdate = onChange; // alias to support belle. https://github.com/nikgraf/belle/issues/58
}
field.valid = true;
field.invalid = false;
Object.defineProperty(field, '_isField', { value: true });
}
var fieldState = (fieldName ? state[fieldName] : state) || {};
var syncError = (0, _read2.default)(name, syncErrors);
var updated = (0, _updateField2.default)(field, fieldState, name === form._active, syncError);
if (fieldName || fields[fieldName] !== updated) {
fields[fieldName] = updated;
}
callback(updated);
return updated;
};
exports.default = readField;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _readField = __webpack_require__(42);
var _readField2 = _interopRequireDefault(_readField);
var _write = __webpack_require__(18);
var _write2 = _interopRequireDefault(_write);
var _getValues = __webpack_require__(14);
var _getValues2 = _interopRequireDefault(_getValues);
var _removeField = __webpack_require__(44);
var _removeField2 = _interopRequireDefault(_removeField);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Reads props and generates (or updates) field structure
*/
var readFields = function readFields(props, previousProps, myFields, asyncValidate, isReactNative) {
var fields = props.fields;
var form = props.form;
var validate = props.validate;
var previousFields = previousProps.fields;
var values = (0, _getValues2.default)(fields, form);
var syncErrors = validate(values, props);
var errors = {};
var formError = syncErrors._error || form._error;
var allValid = !formError;
var allPristine = true;
var tally = function tally(field) {
if (field.error) {
errors = (0, _write2.default)(field.name, field.error, errors);
allValid = false;
}
if (field.dirty) {
allPristine = false;
}
};
var fieldObjects = previousFields ? previousFields.reduce(function (accumulator, previousField) {
return ~fields.indexOf(previousField) ? accumulator : (0, _removeField2.default)(accumulator, previousField);
}, _extends({}, myFields)) : _extends({}, myFields);
fields.forEach(function (name) {
(0, _readField2.default)(form, name, undefined, fieldObjects, syncErrors, asyncValidate, isReactNative, props, tally);
});
Object.defineProperty(fieldObjects, '_meta', {
value: {
allPristine: allPristine,
allValid: allValid,
values: values,
errors: errors,
formError: formError
}
});
return fieldObjects;
};
exports.default = readFields;
/***/ },
/* 44 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var without = function without(object, key) {
var copy = _extends({}, object);
delete copy[key];
return copy;
};
var removeField = function removeField(fields, path) {
var dotIndex = path.indexOf('.');
var openIndex = path.indexOf('[');
var closeIndex = path.indexOf(']');
if (openIndex > 0 && closeIndex !== openIndex + 1) {
throw new Error('found [ not followed by ]');
}
if (openIndex > 0 && (dotIndex < 0 || openIndex < dotIndex)) {
var _ret = function () {
// array field
var key = path.substring(0, openIndex);
if (!Array.isArray(fields[key])) {
return {
v: without(fields, key)
};
}
var rest = path.substring(closeIndex + 1);
if (rest[0] === '.') {
rest = rest.substring(1);
}
if (rest) {
var _ret2 = function () {
var _extends2;
var copy = [];
fields[key].forEach(function (item, index) {
var result = removeField(item, rest);
if (Object.keys(result).length) {
copy[index] = result;
}
});
return {
v: {
v: copy.length ? _extends({}, fields, (_extends2 = {}, _extends2[key] = copy, _extends2)) : without(fields, key)
}
};
}();
if (typeof _ret2 === "object") return _ret2.v;
}
return {
v: without(fields, key)
};
}();
if (typeof _ret === "object") return _ret.v;
}
if (dotIndex > 0) {
var _extends3;
// subobject field
var _key = path.substring(0, dotIndex);
var _rest = path.substring(dotIndex + 1);
if (!fields[_key]) {
return fields;
}
var result = removeField(fields[_key], _rest);
return Object.keys(result).length ? _extends({}, fields, (_extends3 = {}, _extends3[_key] = removeField(fields[_key], _rest), _extends3)) : without(fields, _key);
}
return without(fields, path);
};
exports.default = removeField;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _fieldValue = __webpack_require__(1);
var reset = function reset(value) {
return (0, _fieldValue.makeFieldValue)(value === undefined || value && value.initial === undefined ? {} : { initial: value.initial, value: value.initial });
};
/**
* Sets the initial values into the state and returns a new copy of the state
*/
var resetState = function resetState(values) {
return values ? Object.keys(values).reduce(function (accumulator, key) {
var value = values[key];
if (Array.isArray(value)) {
accumulator[key] = value.map(function (item) {
return (0, _fieldValue.isFieldValue)(item) ? reset(item) : resetState(item);
});
} else if (value) {
if ((0, _fieldValue.isFieldValue)(value)) {
accumulator[key] = reset(value);
} else if (typeof value === 'object' && value !== null) {
accumulator[key] = resetState(value);
} else {
accumulator[key] = value;
}
}
return accumulator;
}, {}) : values;
};
exports.default = resetState;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _fieldValue = __webpack_require__(1);
var isMetaKey = function isMetaKey(key) {
return key[0] === '_';
};
/**
* Sets an error on a field deep in the tree, returning a new copy of the state
*/
var setErrors = function setErrors(state, errors, destKey) {
var clear = function clear() {
if (Array.isArray(state)) {
return state.map(function (stateItem, index) {
return setErrors(stateItem, errors && errors[index], destKey);
});
}
if (state && typeof state === 'object') {
var result = Object.keys(state).reduce(function (accumulator, key) {
var _extends2;
return isMetaKey(key) ? accumulator : _extends({}, accumulator, (_extends2 = {}, _extends2[key] = setErrors(state[key], errors && errors[key], destKey), _extends2));
}, state);
if ((0, _fieldValue.isFieldValue)(state)) {
(0, _fieldValue.makeFieldValue)(result);
}
return result;
}
return (0, _fieldValue.makeFieldValue)(state);
};
if (!errors) {
if (!state) {
return state;
}
if (state[destKey]) {
var copy = _extends({}, state);
delete copy[destKey];
return (0, _fieldValue.makeFieldValue)(copy);
}
return clear();
}
if (typeof errors === 'string') {
var _extends3;
return (0, _fieldValue.makeFieldValue)(_extends({}, state, (_extends3 = {}, _extends3[destKey] = errors, _extends3)));
}
if (Array.isArray(errors)) {
if (!state || Array.isArray(state)) {
var _ret = function () {
var copy = (state || []).map(function (stateItem, index) {
return setErrors(stateItem, errors[index], destKey);
});
errors.forEach(function (errorItem, index) {
return copy[index] = setErrors(copy[index], errorItem, destKey);
});
return {
v: copy
};
}();
if (typeof _ret === "object") return _ret.v;
}
return setErrors(state, errors[0], destKey); // use first error
}
if ((0, _fieldValue.isFieldValue)(state)) {
var _extends4;
return (0, _fieldValue.makeFieldValue)(_extends({}, state, (_extends4 = {}, _extends4[destKey] = errors, _extends4)));
}
var errorKeys = Object.keys(errors);
if (!errorKeys.length && !state) {
return state;
}
return errorKeys.reduce(function (accumulator, key) {
var _extends5;
return isMetaKey(key) ? accumulator : _extends({}, accumulator, (_extends5 = {}, _extends5[key] = setErrors(state && state[key], errors[key], destKey), _extends5));
}, clear() || {});
};
exports.default = setErrors;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isPromise = __webpack_require__(6);
var _isPromise2 = _interopRequireDefault(_isPromise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var noop = function noop() {
return undefined;
};
var silencePromise = function silencePromise(promise) {
return (0, _isPromise2.default)(promise) ? promise.then(noop, noop) : promise;
};
exports.default = silencePromise;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _isPristine = __webpack_require__(40);
var _isPristine2 = _interopRequireDefault(_isPristine);
var _isValid = __webpack_require__(2);
var _isValid2 = _interopRequireDefault(_isValid);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Updates a field object from the store values
*/
var updateField = function updateField(field, formField, active, syncError) {
var diff = {};
var formFieldValue = formField.value === undefined ? '' : formField.value;
// update field value
if (field.value !== formFieldValue) {
diff.value = formFieldValue;
diff.checked = typeof formFieldValue === 'boolean' ? formFieldValue : undefined;
}
// update dirty/pristine
var pristine = (0, _isPristine2.default)(formFieldValue, formField.initial);
if (field.pristine !== pristine) {
diff.dirty = !pristine;
diff.pristine = pristine;
}
// update field error
var error = syncError || formField.submitError || formField.asyncError;
if (error !== field.error) {
diff.error = error;
}
var valid = (0, _isValid2.default)(error);
if (field.valid !== valid) {
diff.invalid = !valid;
diff.valid = valid;
}
if (active !== field.active) {
diff.active = active;
}
var touched = !!formField.touched;
if (touched !== field.touched) {
diff.touched = touched;
}
var visited = !!formField.visited;
if (visited !== field.visited) {
diff.visited = visited;
}
if ('initial' in formField && formField.initial !== field.initialValue) {
field.initialValue = formField.initial;
}
return Object.keys(diff).length ? _extends({}, field, diff) : field;
};
exports.default = updateField;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _redux = __webpack_require__(24);
var wrapMapDispatchToProps = function wrapMapDispatchToProps(mapDispatchToProps, actionCreators) {
if (mapDispatchToProps) {
if (typeof mapDispatchToProps === 'function') {
if (mapDispatchToProps.length > 1) {
return function (dispatch, ownProps) {
return _extends({
dispatch: dispatch
}, mapDispatchToProps(dispatch, ownProps), (0, _redux.bindActionCreators)(actionCreators, dispatch));
};
}
return function (dispatch) {
return _extends({
dispatch: dispatch
}, mapDispatchToProps(dispatch), (0, _redux.bindActionCreators)(actionCreators, dispatch));
};
}
return function (dispatch) {
return _extends({
dispatch: dispatch
}, (0, _redux.bindActionCreators)(mapDispatchToProps, dispatch), (0, _redux.bindActionCreators)(actionCreators, dispatch));
};
}
return function (dispatch) {
return _extends({
dispatch: dispatch
}, (0, _redux.bindActionCreators)(actionCreators, dispatch));
};
};
exports.default = wrapMapDispatchToProps;
/***/ },
/* 50 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var wrapMapStateToProps = function wrapMapStateToProps(mapStateToProps, getForm) {
if (mapStateToProps) {
if (typeof mapStateToProps !== 'function') {
throw new Error('mapStateToProps must be a function');
}
if (mapStateToProps.length > 1) {
return function (state, ownProps) {
return _extends({}, mapStateToProps(state, ownProps), {
form: getForm(state)
});
};
}
return function (state) {
return _extends({}, mapStateToProps(state), {
form: getForm(state)
});
};
}
return function (state) {
return {
form: getForm(state)
};
};
};
exports.default = wrapMapStateToProps;
/***/ },
/* 51 */
/***/ function(module, exports) {
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
/***/ },
/* 52 */
/***/ function(module, exports) {
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (true) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _deepEqual = __webpack_require__(19);
var _deepEqual2 = _interopRequireDefault(_deepEqual);
function intersects(array1, array2) {
return !!(array1 && array2 && array1.some(function (item) {
return ~array2.indexOf(item);
}));
}
var LazyCache = (function () {
function LazyCache(component, calculators) {
var _this = this;
_classCallCheck(this, LazyCache);
this.component = component;
this.allProps = [];
this.cache = Object.keys(calculators).reduce(function (accumulator, key) {
var _extends2;
var calculator = calculators[key];
var fn = calculator.fn;
var paramNames = calculator.params;
paramNames.forEach(function (param) {
if (! ~_this.allProps.indexOf(param)) {
_this.allProps.push(param);
}
});
return _extends({}, accumulator, (_extends2 = {}, _extends2[key] = {
value: undefined,
props: paramNames,
fn: fn
}, _extends2));
}, {});
}
LazyCache.prototype.get = function get(key) {
var component = this.component;
var _cache$key = this.cache[key];
var value = _cache$key.value;
var fn = _cache$key.fn;
var props = _cache$key.props;
if (value !== undefined) {
return value;
}
var params = props.map(function (prop) {
return component.props[prop];
});
var result = fn.apply(undefined, params);
this.cache[key].value = result;
return result;
};
LazyCache.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this2 = this;
var component = this.component;
var diffProps = [];
this.allProps.forEach(function (prop) {
if (!_deepEqual2['default'](component.props[prop], nextProps[prop])) {
diffProps.push(prop);
}
});
if (diffProps.length) {
Object.keys(this.cache).forEach(function (key) {
if (intersects(diffProps, _this2.cache[key].props)) {
delete _this2.cache[key].value; // uncache value
}
});
}
};
return LazyCache;
})();
exports['default'] = LazyCache;
module.exports = exports['default'];
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(54);
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports["default"] = undefined;
var _react = __webpack_require__(3);
var _storeShape = __webpack_require__(21);
var _storeShape2 = _interopRequireDefault(_storeShape);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var didWarnAboutReceivingStore = false;
function warnAboutReceivingStore() {
if (didWarnAboutReceivingStore) {
return;
}
didWarnAboutReceivingStore = true;
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error('<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/rackt/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.');
}
/* eslint-disable no-console */
}
var Provider = function (_Component) {
_inherits(Provider, _Component);
Provider.prototype.getChildContext = function getChildContext() {
return { store: this.store };
};
function Provider(props, context) {
_classCallCheck(this, Provider);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.store = props.store;
return _this;
}
Provider.prototype.render = function render() {
var children = this.props.children;
return _react.Children.only(children);
};
return Provider;
}(_react.Component);
exports["default"] = Provider;
if (true) {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
var store = this.store;
var nextStore = nextProps.store;
if (store !== nextStore) {
warnAboutReceivingStore();
}
};
}
Provider.propTypes = {
store: _storeShape2["default"].isRequired,
children: _react.PropTypes.element.isRequired
};
Provider.childContextTypes = {
store: _storeShape2["default"].isRequired
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.__esModule = true;
exports["default"] = connect;
var _react = __webpack_require__(3);
var _storeShape = __webpack_require__(21);
var _storeShape2 = _interopRequireDefault(_storeShape);
var _shallowEqual = __webpack_require__(59);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _wrapActionCreators = __webpack_require__(60);
var _wrapActionCreators2 = _interopRequireDefault(_wrapActionCreators);
var _isPlainObject = __webpack_require__(64);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _hoistNonReactStatics = __webpack_require__(20);
var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics);
var _invariant = __webpack_require__(53);
var _invariant2 = _interopRequireDefault(_invariant);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var defaultMapStateToProps = function defaultMapStateToProps(state) {
return {};
}; // eslint-disable-line no-unused-vars
var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) {
return { dispatch: dispatch };
};
var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) {
return _extends({}, parentProps, stateProps, dispatchProps);
};
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
function checkStateShape(stateProps, dispatch) {
(0, _invariant2["default"])((0, _isPlainObject2["default"])(stateProps), '`%sToProps` must return an object. Instead received %s.', dispatch ? 'mapDispatch' : 'mapState', stateProps);
return stateProps;
}
// Helps track hot reloading.
var nextVersion = 0;
function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
var shouldSubscribe = Boolean(mapStateToProps);
var mapState = mapStateToProps || defaultMapStateToProps;
var mapDispatch = (0, _isPlainObject2["default"])(mapDispatchToProps) ? (0, _wrapActionCreators2["default"])(mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps;
var finalMergeProps = mergeProps || defaultMergeProps;
var checkMergedEquals = finalMergeProps !== defaultMergeProps;
var _options$pure = options.pure;
var pure = _options$pure === undefined ? true : _options$pure;
var _options$withRef = options.withRef;
var withRef = _options$withRef === undefined ? false : _options$withRef;
// Helps track hot reloading.
var version = nextVersion++;
function computeMergedProps(stateProps, dispatchProps, parentProps) {
var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps);
(0, _invariant2["default"])((0, _isPlainObject2["default"])(mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps);
return mergedProps;
}
return function wrapWithConnect(WrappedComponent) {
var Connect = function (_Component) {
_inherits(Connect, _Component);
Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate() {
return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged;
};
function Connect(props, context) {
_classCallCheck(this, Connect);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.version = version;
_this.store = props.store || context.store;
(0, _invariant2["default"])(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + _this.constructor.displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + _this.constructor.displayName + '".'));
var storeState = _this.store.getState();
_this.state = { storeState: storeState };
_this.clearCache();
return _this;
}
Connect.prototype.computeStateProps = function computeStateProps(store, props) {
if (!this.finalMapStateToProps) {
return this.configureFinalMapState(store, props);
}
var state = store.getState();
var stateProps = this.doStatePropsDependOnOwnProps ? this.finalMapStateToProps(state, props) : this.finalMapStateToProps(state);
return checkStateShape(stateProps);
};
Connect.prototype.configureFinalMapState = function configureFinalMapState(store, props) {
var mappedState = mapState(store.getState(), props);
var isFactory = typeof mappedState === 'function';
this.finalMapStateToProps = isFactory ? mappedState : mapState;
this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1;
return isFactory ? this.computeStateProps(store, props) : checkStateShape(mappedState);
};
Connect.prototype.computeDispatchProps = function computeDispatchProps(store, props) {
if (!this.finalMapDispatchToProps) {
return this.configureFinalMapDispatch(store, props);
}
var dispatch = store.dispatch;
var dispatchProps = this.doDispatchPropsDependOnOwnProps ? this.finalMapDispatchToProps(dispatch, props) : this.finalMapDispatchToProps(dispatch);
return checkStateShape(dispatchProps, true);
};
Connect.prototype.configureFinalMapDispatch = function configureFinalMapDispatch(store, props) {
var mappedDispatch = mapDispatch(store.dispatch, props);
var isFactory = typeof mappedDispatch === 'function';
this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch;
this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1;
return isFactory ? this.computeDispatchProps(store, props) : checkStateShape(mappedDispatch, true);
};
Connect.prototype.updateStatePropsIfNeeded = function updateStatePropsIfNeeded() {
var nextStateProps = this.computeStateProps(this.store, this.props);
if (this.stateProps && (0, _shallowEqual2["default"])(nextStateProps, this.stateProps)) {
return false;
}
this.stateProps = nextStateProps;
return true;
};
Connect.prototype.updateDispatchPropsIfNeeded = function updateDispatchPropsIfNeeded() {
var nextDispatchProps = this.computeDispatchProps(this.store, this.props);
if (this.dispatchProps && (0, _shallowEqual2["default"])(nextDispatchProps, this.dispatchProps)) {
return false;
}
this.dispatchProps = nextDispatchProps;
return true;
};
Connect.prototype.updateMergedPropsIfNeeded = function updateMergedPropsIfNeeded() {
var nextMergedProps = computeMergedProps(this.stateProps, this.dispatchProps, this.props);
if (this.mergedProps && checkMergedEquals && (0, _shallowEqual2["default"])(nextMergedProps, this.mergedProps)) {
return false;
}
this.mergedProps = nextMergedProps;
return true;
};
Connect.prototype.isSubscribed = function isSubscribed() {
return typeof this.unsubscribe === 'function';
};
Connect.prototype.trySubscribe = function trySubscribe() {
if (shouldSubscribe && !this.unsubscribe) {
this.unsubscribe = this.store.subscribe(this.handleChange.bind(this));
this.handleChange();
}
};
Connect.prototype.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
};
Connect.prototype.componentDidMount = function componentDidMount() {
this.trySubscribe();
};
Connect.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!pure || !(0, _shallowEqual2["default"])(nextProps, this.props)) {
this.haveOwnPropsChanged = true;
}
};
Connect.prototype.componentWillUnmount = function componentWillUnmount() {
this.tryUnsubscribe();
this.clearCache();
};
Connect.prototype.clearCache = function clearCache() {
this.dispatchProps = null;
this.stateProps = null;
this.mergedProps = null;
this.haveOwnPropsChanged = true;
this.hasStoreStateChanged = true;
this.renderedElement = null;
this.finalMapDispatchToProps = null;
this.finalMapStateToProps = null;
};
Connect.prototype.handleChange = function handleChange() {
if (!this.unsubscribe) {
return;
}
var prevStoreState = this.state.storeState;
var storeState = this.store.getState();
if (!pure || prevStoreState !== storeState) {
this.hasStoreStateChanged = true;
this.setState({ storeState: storeState });
}
};
Connect.prototype.getWrappedInstance = function getWrappedInstance() {
(0, _invariant2["default"])(withRef, 'To access the wrapped instance, you need to specify ' + '{ withRef: true } as the fourth argument of the connect() call.');
return this.refs.wrappedInstance;
};
Connect.prototype.render = function render() {
var haveOwnPropsChanged = this.haveOwnPropsChanged;
var hasStoreStateChanged = this.hasStoreStateChanged;
var renderedElement = this.renderedElement;
this.haveOwnPropsChanged = false;
this.hasStoreStateChanged = false;
var shouldUpdateStateProps = true;
var shouldUpdateDispatchProps = true;
if (pure && renderedElement) {
shouldUpdateStateProps = hasStoreStateChanged || haveOwnPropsChanged && this.doStatePropsDependOnOwnProps;
shouldUpdateDispatchProps = haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps;
}
var haveStatePropsChanged = false;
var haveDispatchPropsChanged = false;
if (shouldUpdateStateProps) {
haveStatePropsChanged = this.updateStatePropsIfNeeded();
}
if (shouldUpdateDispatchProps) {
haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded();
}
var haveMergedPropsChanged = true;
if (haveStatePropsChanged || haveDispatchPropsChanged || haveOwnPropsChanged) {
haveMergedPropsChanged = this.updateMergedPropsIfNeeded();
} else {
haveMergedPropsChanged = false;
}
if (!haveMergedPropsChanged && renderedElement) {
return renderedElement;
}
if (withRef) {
this.renderedElement = (0, _react.createElement)(WrappedComponent, _extends({}, this.mergedProps, {
ref: 'wrappedInstance'
}));
} else {
this.renderedElement = (0, _react.createElement)(WrappedComponent, this.mergedProps);
}
return this.renderedElement;
};
return Connect;
}(_react.Component);
Connect.displayName = 'Connect(' + getDisplayName(WrappedComponent) + ')';
Connect.WrappedComponent = WrappedComponent;
Connect.contextTypes = {
store: _storeShape2["default"]
};
Connect.propTypes = {
store: _storeShape2["default"]
};
if (true) {
Connect.prototype.componentWillUpdate = function componentWillUpdate() {
if (this.version === version) {
return;
}
// We are hot reloading!
this.version = version;
this.trySubscribe();
this.clearCache();
};
}
return (0, _hoistNonReactStatics2["default"])(Connect, WrappedComponent);
};
}
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.connect = exports.Provider = undefined;
var _Provider = __webpack_require__(56);
var _Provider2 = _interopRequireDefault(_Provider);
var _connect = __webpack_require__(57);
var _connect2 = _interopRequireDefault(_connect);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.Provider = _Provider2["default"];
exports.connect = _connect2["default"];
/***/ },
/* 59 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = shallowEqual;
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports["default"] = wrapActionCreators;
var _redux = __webpack_require__(24);
function wrapActionCreators(actionCreators) {
return function (dispatch) {
return (0, _redux.bindActionCreators)(actionCreators, dispatch);
};
}
/***/ },
/* 61 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf;
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
module.exports = getPrototype;
/***/ },
/* 62 */
/***/ function(module, exports) {
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
module.exports = isHostObject;
/***/ },
/* 63 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
var getPrototype = __webpack_require__(61),
isHostObject = __webpack_require__(62),
isObjectLike = __webpack_require__(63);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object,
* else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.__esModule = true;
exports["default"] = applyMiddleware;
var _compose = __webpack_require__(22);
var _compose2 = _interopRequireDefault(_compose);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function (reducer, initialState, enhancer) {
var store = createStore(reducer, initialState, enhancer);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
/***/ },
/* 66 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = bindActionCreators;
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
var keys = Object.keys(actionCreators);
var boundActionCreators = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports["default"] = combineReducers;
var _createStore = __webpack_require__(23);
var _isPlainObject = __webpack_require__(26);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = __webpack_require__(25);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!(0, _isPlainObject2["default"])(inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key);
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
return function combination() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (sanityError) {
throw sanityError;
}
if (true) {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action);
if (warningMessage) {
(0, _warning2["default"])(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i];
var reducer = finalReducers[key];
var previousStateForKey = state[key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
/***/ },
/* 68 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf;
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
module.exports = getPrototype;
/***/ },
/* 69 */
/***/ function(module, exports) {
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
module.exports = isHostObject;
/***/ },
/* 70 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }
/******/ ])
});
; |
ajax/libs/forerunnerdb/1.3.529/fdb-legacy.js | x112358/cdnjs | (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){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatch[joinMatchIndex].query;
joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]);
}
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":39}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":39}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
delete this._listeners;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy,
this._options
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
sData,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
if (xAxis.categories) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
} else {
seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]);
}
}
sData = {
name: seriesName,
data: seriesValues
};
if (options.seriesOptions) {
for (k in options.seriesOptions) {
if (options.seriesOptions.hasOwnProperty(k)) {
sData[k] = options.seriesOptions[k];
}
}
}
seriesData.push(sData);
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () {
self._changeListener.apply(self, arguments);
});
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () {
self.drop.apply(self);
});
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if (typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy,
self._options
);
if (seriesData.xAxis.categories) {
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
}
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) {
callback(false, true);
}
delete this._listeners;
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via selector.
* @func lineChart
* @memberof Highchart
* @param {String} selector The chart selector.
* @returns {*}
*/
'string': function (selector) {
return this._highcharts[selector];
},
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var φ1 = this.toRadians(lat1);
var φ2 = this.toRadians(lat2);
var Δφ = this.toRadians(lat2-lat1);
var Δλ = this.toRadians(lng2-lng1);
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":39}],17:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":31}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check we have a database object to work from
if (!this.db()) {
throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!');
}
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],28:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":39}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
delete this._listeners;
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":39}],34:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":77}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":39,"pako":78}],36:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":39}],38:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Handler for Date() objects
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
// Handler for RegExp() objects
this.registerEncoder('$regexp', function (data) {
if (data instanceof RegExp) {
return {
source: data.source,
params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '')
};
}
});
this.registerDecoder('$regexp', function (data) {
return new RegExp(data.source, data.params);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],39:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.529',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
var self = this;
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (this._view[viewName]) {
return this._view[viewName];
} else {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
self.emit('create', [self._view[viewName], 'view', viewName]);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":44}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":44}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":44}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":44}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":44}],52:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":44}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. 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.
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.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":44}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":44}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":44}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":44}],76:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(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;
clearTimeout(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) {
setTimeout(drainQueue, 0);
}
};
// 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; };
},{}],77:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.3.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
(function () {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
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
};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function (self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function () {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
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];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
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);
}
// 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.
// 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 === '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, '_');
}
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) {
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(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
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;
});
promise.then(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 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(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.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.resolve();
}) : Promise.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.reject(error);
return self._driverSet;
});
this._driverSet.then(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; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
var localForage = new LocalForage();
exports['default'] = localForage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// 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) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// 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;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(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;
}
// 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];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null
};
// 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(this);
// Create an array of readiness of the related localForages.
var readyPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== this) {
// Don't wait for itself...
readyPromises.push(forage.ready()['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.all(readyPromises).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 in forages) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, 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') {
globalObject.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 () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
};
});
}
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) {
globalObject.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;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(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++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function (blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(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'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = asyncStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(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(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(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(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(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(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++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).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(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(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(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(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(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(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 executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = localStorageWrapper;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
(function () {
'use strict';
// 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;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// 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) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// 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 valueString = '';
if (value) {
valueString = value.toString();
}
// 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 && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[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 (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[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);
}
}
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;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
exports['default'] = localforageSerializer;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL 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] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(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 self.setDriver(self.LOCALSTORAGE).then(function () {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(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) {
t.executeSql('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.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('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(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('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;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = webSQLStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],78:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],82:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":81}],83:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],84:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],85:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],86:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],88:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":81}],91:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],92:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":81}],93:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
ajax/libs/yui/3.9.0/datatable-core/datatable-core-debug.js | froala/cdnjs | YUI.add('datatable-core', function (Y, NAME) {
/**
The core implementation of the `DataTable` and `DataTable.Base` Widgets.
@module datatable
@submodule datatable-core
@since 3.5.0
**/
var INVALID = Y.Attribute.INVALID_VALUE,
Lang = Y.Lang,
isFunction = Lang.isFunction,
isObject = Lang.isObject,
isArray = Lang.isArray,
isString = Lang.isString,
isNumber = Lang.isNumber,
toArray = Y.Array,
keys = Y.Object.keys,
Table;
/**
_API docs for this extension are included in the DataTable class._
Class extension providing the core API and structure for the DataTable Widget.
Use this class extension with Widget or another Base-based superclass to create
the basic DataTable model API and composing class structure.
@class DataTable.Core
@for DataTable
@since 3.5.0
**/
Table = Y.namespace('DataTable').Core = function () {};
Table.ATTRS = {
/**
Columns to include in the rendered table.
If omitted, the attributes on the configured `recordType` or the first item
in the `data` collection will be used as a source.
This attribute takes an array of strings or objects (mixing the two is
fine). Each string or object is considered a column to be rendered.
Strings are converted to objects, so `columns: ['first', 'last']` becomes
`columns: [{ key: 'first' }, { key: 'last' }]`.
DataTable.Core only concerns itself with a few properties of columns.
These properties are:
* `key` - Used to identify the record field/attribute containing content for
this column. Also used to create a default Model if no `recordType` or
`data` are provided during construction. If `name` is not specified, this
is assigned to the `_id` property (with added incrementer if the key is
used by multiple columns).
* `children` - Traversed to initialize nested column objects
* `name` - Used in place of, or in addition to, the `key`. Useful for
columns that aren't bound to a field/attribute in the record data. This
is assigned to the `_id` property.
* `id` - For backward compatibility. Implementers can specify the id of
the header cell. This should be avoided, if possible, to avoid the
potential for creating DOM elements with duplicate IDs.
* `field` - For backward compatibility. Implementers should use `name`.
* `_id` - Assigned unique-within-this-instance id for a column. By order
of preference, assumes the value of `name`, `key`, `id`, or `_yuid`.
This is used by the rendering views as well as feature module
as a means to identify a specific column without ambiguity (such as
multiple columns using the same `key`.
* `_yuid` - Guid stamp assigned to the column object.
* `_parent` - Assigned to all child columns, referencing their parent
column.
@attribute columns
@type {Object[]|String[]}
@default (from `recordType` ATTRS or first item in the `data`)
@since 3.5.0
**/
columns: {
// TODO: change to setter to clone input array/objects
validator: isArray,
setter: '_setColumns',
getter: '_getColumns'
},
/**
Model subclass to use as the `model` for the ModelList stored in the `data`
attribute.
If not provided, it will try really hard to figure out what to use. The
following attempts will be made to set a default value:
1. If the `data` attribute is set with a ModelList instance and its `model`
property is set, that will be used.
2. If the `data` attribute is set with a ModelList instance, and its
`model` property is unset, but it is populated, the `ATTRS` of the
`constructor of the first item will be used.
3. If the `data` attribute is set with a non-empty array, a Model subclass
will be generated using the keys of the first item as its `ATTRS` (see
the `_createRecordClass` method).
4. If the `columns` attribute is set, a Model subclass will be generated
using the columns defined with a `key`. This is least desirable because
columns can be duplicated or nested in a way that's not parsable.
5. If neither `data` nor `columns` is set or populated, a change event
subscriber will listen for the first to be changed and try all over
again.
@attribute recordType
@type {Function}
@default (see description)
@since 3.5.0
**/
recordType: {
getter: '_getRecordType',
setter: '_setRecordType'
},
/**
The collection of data records to display. This attribute is a pass
through to a `data` property, which is a ModelList instance.
If this attribute is passed a ModelList or subclass, it will be assigned to
the property directly. If an array of objects is passed, a new ModelList
will be created using the configured `recordType` as its `model` property
and seeded with the array.
Retrieving this attribute will return the ModelList stored in the `data`
property.
@attribute data
@type {ModelList|Object[]}
@default `new ModelList()`
@since 3.5.0
**/
data: {
valueFn: '_initData',
setter : '_setData',
lazyAdd: false
},
/**
Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned
to this attribute will be HTML escaped for security.
@attribute summary
@type {String}
@default '' (empty string)
@since 3.5.0
**/
//summary: {},
/**
HTML content of an optional `<caption>` element to appear above the table.
Leave this config unset or set to a falsy value to remove the caption.
@attribute caption
@type HTML
@default '' (empty string)
@since 3.5.0
**/
//caption: {},
/**
Deprecated as of 3.5.0. Passes through to the `data` attribute.
WARNING: `get('recordset')` will NOT return a Recordset instance as of
3.5.0. This is a break in backward compatibility.
@attribute recordset
@type {Object[]|Recordset}
@deprecated Use the `data` attribute
@since 3.5.0
**/
recordset: {
setter: '_setRecordset',
getter: '_getRecordset',
lazyAdd: false
},
/**
Deprecated as of 3.5.0. Passes through to the `columns` attribute.
WARNING: `get('columnset')` will NOT return a Columnset instance as of
3.5.0. This is a break in backward compatibility.
@attribute columnset
@type {Object[]}
@deprecated Use the `columns` attribute
@since 3.5.0
**/
columnset: {
setter: '_setColumnset',
getter: '_getColumnset',
lazyAdd: false
}
};
Y.mix(Table.prototype, {
// -- Instance properties -------------------------------------------------
/**
The ModelList that manages the table's data.
@property data
@type {ModelList}
@default undefined (initially unset)
@since 3.5.0
**/
//data: null,
// -- Public methods ------------------------------------------------------
/**
Gets the column configuration object for the given key, name, or index. For
nested columns, `name` can be an array of indexes, each identifying the index
of that column in the respective parent's "children" array.
If you pass a column object, it will be returned.
For columns with keys, you can also fetch the column with
`instance.get('columns.foo')`.
@method getColumn
@param {String|Number|Number[]} name Key, "name", index, or index array to
identify the column
@return {Object} the column configuration object
@since 3.5.0
**/
getColumn: function (name) {
var col, columns, i, len, cols;
if (isObject(name) && !isArray(name)) {
// TODO: support getting a column from a DOM node - this will cross
// the line into the View logic, so it should be relayed
// Assume an object passed in is already a column def
col = name;
} else {
col = this.get('columns.' + name);
}
if (col) {
return col;
}
columns = this.get('columns');
if (isNumber(name) || isArray(name)) {
name = toArray(name);
cols = columns;
for (i = 0, len = name.length - 1; cols && i < len; ++i) {
cols = cols[name[i]] && cols[name[i]].children;
}
return (cols && cols[name[i]]) || null;
}
return null;
},
/**
Returns the Model associated to the record `id`, `clientId`, or index (not
row index). If none of those yield a Model from the `data` ModelList, the
arguments will be passed to the `view` instance's `getRecord` method
if it has one.
If no Model can be found, `null` is returned.
@method getRecord
@param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or
identifier for a row or child element
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var record = this.data.getById(seed) || this.data.getByClientId(seed);
if (!record) {
if (isNumber(seed)) {
record = this.data.item(seed);
}
// TODO: this should be split out to base somehow
if (!record && this.view && this.view.getRecord) {
record = this.view.getRecord.apply(this.view, arguments);
}
}
return record || null;
},
// -- Protected and private properties and methods ------------------------
/**
This tells `Y.Base` that it should create ad-hoc attributes for config
properties passed to DataTable's constructor. This is useful for setting
configurations on the DataTable that are intended for the rendering View(s).
@property _allowAdHocAttrs
@type Boolean
@default true
@protected
@since 3.6.0
**/
_allowAdHocAttrs: true,
/**
A map of column key to column configuration objects parsed from the
`columns` attribute.
@property _columnMap
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_columnMap: null,
/**
The Node instance of the table containing the data rows. This is set when
the table is rendered. It may also be set by progressive enhancement,
though this extension does not provide the logic to parse from source.
@property _tableNode
@type {Node}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_tableNode: null,
/**
Updates the `_columnMap` property in response to changes in the `columns`
attribute.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
_afterColumnsChange: function (e) {
this._setColumnMap(e.newVal);
},
/**
Updates the `modelList` attributes of the rendered views in response to the
`data` attribute being assigned a new ModelList.
@method _afterDataChange
@param {EventFacade} e the `dataChange` event
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var modelList = e.newVal;
this.data = e.newVal;
if (!this.get('columns') && modelList.size()) {
// TODO: this will cause a re-render twice because the Views are
// subscribed to columnsChange
this._initColumns();
}
},
/**
Assigns to the new recordType as the model for the data ModelList
@method _afterRecordTypeChange
@param {EventFacade} e recordTypeChange event
@protected
@since 3.6.0
**/
_afterRecordTypeChange: function (e) {
var data = this.data.toJSON();
this.data.model = e.newVal;
this.data.reset(data);
if (!this.get('columns') && data) {
if (data.length) {
this._initColumns();
} else {
this.set('columns', keys(e.newVal.ATTRS));
}
}
},
/**
Creates a Model subclass from an array of attribute names or an object of
attribute definitions. This is used to generate a class suitable to
represent the data passed to the `data` attribute if no `recordType` is
set.
@method _createRecordClass
@param {String[]|Object} attrs Names assigned to the Model subclass's
`ATTRS` or its entire `ATTRS` definition object
@return {Model}
@protected
@since 3.5.0
**/
_createRecordClass: function (attrs) {
var ATTRS, i, len;
if (isArray(attrs)) {
ATTRS = {};
for (i = 0, len = attrs.length; i < len; ++i) {
ATTRS[attrs[i]] = {};
}
} else if (isObject(attrs)) {
ATTRS = attrs;
}
return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });
},
/**
Tears down the instance.
@method destructor
@protected
@since 3.6.0
**/
destructor: function () {
new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();
},
/**
The getter for the `columns` attribute. Returns the array of column
configuration objects if `instance.get('columns')` is called, or the
specific column object if `instance.get('columns.columnKey')` is called.
@method _getColumns
@param {Object[]} columns The full array of column objects
@param {String} name The attribute name requested
(e.g. 'columns' or 'columns.foo');
@protected
@since 3.5.0
**/
_getColumns: function (columns, name) {
// Workaround for an attribute oddity (ticket #2529254)
// getter is expected to return an object if get('columns.foo') is called.
// Note 'columns.' is 8 characters
return name.length > 8 ? this._columnMap : columns;
},
/**
Relays the `get()` request for the deprecated `columnset` attribute to the
`columns` attribute.
THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will
expect a Columnset instance returned from `get('columnset')`.
@method _getColumnset
@param {Object} ignored The current value stored in the `columnset` state
@param {String} name The attribute name requested
(e.g. 'columnset' or 'columnset.foo');
@deprecated This will be removed with the `columnset` attribute in a future
version.
@protected
@since 3.5.0
**/
_getColumnset: function (_, name) {
return this.get(name.replace(/^columnset/, 'columns'));
},
/**
Returns the Model class of the instance's `data` attribute ModelList. If
not set, returns the explicitly configured value.
@method _getRecordType
@param {Model} val The currently configured value
@return {Model}
**/
_getRecordType: function (val) {
// Prefer the value stored in the attribute because the attribute
// change event defaultFn sets e.newVal = this.get('recordType')
// before notifying the after() subs. But if this getter returns
// this.data.model, then after() subs would get e.newVal === previous
// model before _afterRecordTypeChange can set
// this.data.model = e.newVal
return val || (this.data && this.data.model);
},
/**
Initializes the `_columnMap` property from the configured `columns`
attribute. If `columns` is not set, but there are records in the `data`
ModelList, use
`ATTRS` of that class.
@method _initColumns
@protected
@since 3.5.0
**/
_initColumns: function () {
var columns = this.get('columns') || [],
item;
// Default column definition from the configured recordType
if (!columns.length && this.data.size()) {
// TODO: merge superclass attributes up to Model?
item = this.data.item(0);
if (item.toJSON) {
item = item.toJSON();
}
this.set('columns', keys(item));
}
this._setColumnMap(columns);
},
/**
Sets up the change event subscriptions to maintain internal state.
@method _initCoreEvents
@protected
@since 3.6.0
**/
_initCoreEvents: function () {
this._eventHandles.coreAttrChanges = this.after({
columnsChange : Y.bind('_afterColumnsChange', this),
recordTypeChange: Y.bind('_afterRecordTypeChange', this),
dataChange : Y.bind('_afterDataChange', this)
});
},
/**
Defaults the `data` attribute to an empty ModelList if not set during
construction. Uses the configured `recordType` for the ModelList's `model`
proeprty if set.
@method _initData
@protected
@return {ModelList}
@since 3.6.0
**/
_initData: function () {
var recordType = this.get('recordType'),
// TODO: LazyModelList if recordType doesn't have complex ATTRS
modelList = new Y.ModelList();
if (recordType) {
modelList.model = recordType;
}
return modelList;
},
/**
Initializes the instance's `data` property from the value of the `data`
attribute. If the attribute value is a ModelList, it is assigned directly
to `this.data`. If it is an array, a ModelList is created, its `model`
property is set to the configured `recordType` class, and it is seeded with
the array data. This ModelList is then assigned to `this.data`.
@method _initDataProperty
@param {Array|ModelList|ArrayList} data Collection of data to populate the
DataTable
@protected
@since 3.6.0
**/
_initDataProperty: function (data) {
var recordType;
if (!this.data) {
recordType = this.get('recordType');
if (data && data.each && data.toJSON) {
this.data = data;
if (recordType) {
this.data.model = recordType;
}
} else {
// TODO: customize the ModelList or read the ModelList class
// from a configuration option?
this.data = new Y.ModelList();
if (recordType) {
this.data.model = recordType;
}
}
// TODO: Replace this with an event relay for specific events.
// Using bubbling causes subscription conflicts with the models'
// aggregated change event and 'change' events from DOM elements
// inside the table (via Widget UI event).
this.data.addTarget(this);
}
},
/**
Initializes the columns, `recordType` and data ModelList.
@method initializer
@param {Object} config Configuration object passed to constructor
@protected
@since 3.5.0
**/
initializer: function (config) {
var data = config.data,
columns = config.columns,
recordType;
// Referencing config.data to allow _setData to be more stringent
// about its behavior
this._initDataProperty(data);
// Default columns from recordType ATTRS if recordType is supplied at
// construction. If no recordType is supplied, but the data is
// supplied as a non-empty array, use the keys of the first item
// as the columns.
if (!columns) {
recordType = (config.recordType || config.data === this.data) &&
this.get('recordType');
if (recordType) {
columns = keys(recordType.ATTRS);
} else if (isArray(data) && data.length) {
columns = keys(data[0]);
}
if (columns) {
this.set('columns', columns);
}
}
this._initColumns();
this._eventHandles = {};
this._initCoreEvents();
},
/**
Iterates the array of column configurations to capture all columns with a
`key` property. An map is built with column keys as the property name and
the corresponding column object as the associated value. This map is then
assigned to the instance's `_columnMap` property.
@method _setColumnMap
@param {Object[]|String[]} columns The array of column config objects
@protected
@since 3.6.0
**/
_setColumnMap: function (columns) {
var map = {};
function process(cols) {
var i, len, col, key;
for (i = 0, len = cols.length; i < len; ++i) {
col = cols[i];
key = col.key;
// First in wins for multiple columns with the same key
// because the first call to genId (in _setColumns) will
// return the same key, which will then be overwritten by the
// subsequent same-keyed column. So table.getColumn(key) would
// return the last same-keyed column.
if (key && !map[key]) {
map[key] = col;
}
//TODO: named columns can conflict with keyed columns
map[col._id] = col;
if (col.children) {
process(col.children);
}
}
}
process(columns);
this._columnMap = map;
},
/**
Translates string columns into objects with that string as the value of its
`key` property.
All columns are assigned a `_yuid` stamp and `_id` property corresponding
to the column's configured `name` or `key` property with any spaces
replaced with dashes. If the same `name` or `key` appears in multiple
columns, subsequent appearances will have their `_id` appended with an
incrementing number (e.g. if column "foo" is included in the `columns`
attribute twice, the first will get `_id` of "foo", and the second an `_id`
of "foo1"). Columns that are children of other columns will have the
`_parent` property added, assigned the column object to which they belong.
@method _setColumns
@param {null|Object[]|String[]} val Array of config objects or strings
@return {null|Object[]}
@protected
**/
_setColumns: function (val) {
var keys = {},
known = [],
knownCopies = [],
arrayIndex = Y.Array.indexOf;
function copyObj(o) {
var copy = {},
key, val, i;
known.push(o);
knownCopies.push(copy);
for (key in o) {
if (o.hasOwnProperty(key)) {
val = o[key];
if (isArray(val)) {
copy[key] = val.slice();
} else if (isObject(val, true)) {
i = arrayIndex(val, known);
copy[key] = i === -1 ? copyObj(val) : knownCopies[i];
} else {
copy[key] = o[key];
}
}
}
return copy;
}
function genId(name) {
// Sanitize the name for use in generated CSS classes.
// TODO: is there more to do for other uses of _id?
name = name.replace(/\s+/, '-');
if (keys[name]) {
name += (keys[name]++);
} else {
keys[name] = 1;
}
return name;
}
function process(cols, parent) {
var columns = [],
i, len, col, yuid;
for (i = 0, len = cols.length; i < len; ++i) {
columns[i] = // chained assignment
col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);
yuid = Y.stamp(col);
// For backward compatibility
if (!col.id) {
// Implementers can shoot themselves in the foot by setting
// this config property to a non-unique value
col.id = yuid;
}
if (col.field) {
// Field is now known as "name" to avoid confusion with data
// fields or schema.resultFields
col.name = col.field;
}
if (parent) {
col._parent = parent;
} else {
delete col._parent;
}
// Unique id based on the column's configured name or key,
// falling back to the yuid. Duplicates will have a counter
// added to the end.
col._id = genId(col.name || col.key || col.id);
if (isArray(col.children)) {
col.children = process(col.children, col);
}
}
return columns;
}
return val && process(val);
},
/**
Relays attribute assignments of the deprecated `columnset` attribute to the
`columns` attribute. If a Columnset is object is passed, its basic object
structure is mined.
@method _setColumnset
@param {Array|Columnset} val The columnset value to relay
@deprecated This will be removed with the deprecated `columnset` attribute
in a later version.
@protected
@since 3.5.0
**/
_setColumnset: function (val) {
this.set('columns', val);
return isArray(val) ? val : INVALID;
},
/**
Accepts an object with `each` and `getAttrs` (preferably a ModelList or
subclass) or an array of data objects. If an array is passes, it will
create a ModelList to wrap the data. In doing so, it will set the created
ModelList's `model` property to the class in the `recordType` attribute,
which will be defaulted if not yet set.
If the `data` property is already set with a ModelList, passing an array as
the value will call the ModelList's `reset()` method with that array rather
than replacing the stored ModelList wholesale.
Any non-ModelList-ish and non-array value is invalid.
@method _setData
@protected
@since 3.5.0
**/
_setData: function (val) {
if (val === null) {
val = [];
}
if (isArray(val)) {
this._initDataProperty();
// silent to prevent subscribers to both reset and dataChange
// from reacting to the change twice.
// TODO: would it be better to return INVALID to silence the
// dataChange event, or even allow both events?
this.data.reset(val, { silent: true });
// Return the instance ModelList to avoid storing unprocessed
// data in the state and their vivified Model representations in
// the instance's data property. Decreases memory consumption.
val = this.data;
} else if (!val || !val.each || !val.toJSON) {
// ModelList/ArrayList duck typing
val = INVALID;
}
return val;
},
/**
Relays the value assigned to the deprecated `recordset` attribute to the
`data` attribute. If a Recordset instance is passed, the raw object data
will be culled from it.
@method _setRecordset
@param {Object[]|Recordset} val The recordset value to relay
@deprecated This will be removed with the deprecated `recordset` attribute
in a later version.
@protected
@since 3.5.0
**/
_setRecordset: function (val) {
var data;
if (val && Y.Recordset && val instanceof Y.Recordset) {
data = [];
val.each(function (record) {
data.push(record.get('data'));
});
val = data;
}
this.set('data', val);
return val;
},
/**
Accepts a Base subclass (preferably a Model subclass). Alternately, it will
generate a custom Model subclass from an array of attribute names or an
object defining attributes and their respective configurations (it is
assigned as the `ATTRS` of the new class).
Any other value is invalid.
@method _setRecordType
@param {Function|String[]|Object} val The Model subclass, array of
attribute names, or the `ATTRS` definition for a custom model
subclass
@return {Function} A Base/Model subclass
@protected
@since 3.5.0
**/
_setRecordType: function (val) {
var modelClass;
// Duck type based on known/likely consumed APIs
if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {
modelClass = val;
} else if (isObject(val)) {
modelClass = this._createRecordClass(val);
}
return modelClass || INVALID;
}
});
}, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
|
packages/icons/src/md/device/AccessAlarm.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdAccessAlarm(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M44 11.72l-9.19-7.71-2.57 3.06 9.19 7.71L44 11.72zM15.76 7.06L13.19 4 4 11.71l2.57 3.06 9.19-7.71zM25 16.28h-3v12l9.49 5.71L33 31.52l-8-4.74v-10.5zm-1.01-8c9.95 0 18.01 8.06 18.01 18s-8.06 18-18.01 18c-9.95 0-17.99-8.06-17.99-18s8.04-18 17.99-18zm.01 32c7.74 0 14-6.27 14-14s-6.27-14-14-14-14 6.27-14 14 6.27 14 14 14z" />
</IconBase>
);
}
export default MdAccessAlarm;
|
admin/client/App/screens/List/components/ListControl.js | jstockwin/keystone | import React from 'react';
import classnames from 'classnames';
var ListControl = React.createClass({
propTypes: {
dragSource: React.PropTypes.func,
onClick: React.PropTypes.func,
type: React.PropTypes.oneOf(['check', 'delete', 'sortable']).isRequired,
},
renderControl () {
var icon = 'octicon octicon-';
var className = classnames('ItemList__control ItemList__control--' + this.props.type, {
'is-active': this.props.active,
});
var tabindex = this.props.type === 'sortable' ? -1 : null;
if (this.props.type === 'check') {
icon += 'check';
}
if (this.props.type === 'delete') {
icon += 'trashcan';
}
if (this.props.type === 'sortable') {
icon += 'three-bars';
}
var renderButton = (
<button type="button" onClick={this.props.onClick} className={className} tabIndex={tabindex}>
<span className={icon} />
</button>
);
if (this.props.dragSource) {
return this.props.dragSource(renderButton);
} else {
return renderButton;
}
},
render () {
var className = 'ItemList__col--control ItemList__col--' + this.props.type;
return (
<td className={className}>
{this.renderControl()}
</td>
);
},
});
module.exports = ListControl;
|
node_modules/eslint/node_modules/inquirer/node_modules/rx/src/core/linq/observable/ambproto.js | artyomtrityak/ec-deploy-mobile | /**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
}, function (err) {
choiceL();
choice === leftChoice && observer.onError(err);
}, function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
}, function (err) {
choiceR();
choice === rightChoice && observer.onError(err);
}, function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
|
content/openLayers_v3.9.0/zeroclipboard/ZeroClipboard.Core.js | open-dis/DISWebGateway | /*!
* ZeroClipboard
* The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
* Copyright (c) 2009-2014 Jon Rohan, James M. Greene
* Licensed MIT
* http://zeroclipboard.org/
* v2.2.0
*/
(function(window, undefined) {
"use strict";
/**
* Store references to critically important global functions that may be
* overridden on certain web pages.
*/
var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _clearTimeout = _window.clearTimeout, _setInterval = _window.setInterval, _clearInterval = _window.clearInterval, _getComputedStyle = _window.getComputedStyle, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice, _unwrap = function() {
var unwrapper = function(el) {
return el;
};
if (typeof _window.wrap === "function" && typeof _window.unwrap === "function") {
try {
var div = _document.createElement("div");
var unwrappedDiv = _window.unwrap(div);
if (div.nodeType === 1 && unwrappedDiv && unwrappedDiv.nodeType === 1) {
unwrapper = _window.unwrap;
}
} catch (e) {}
}
return unwrapper;
}();
/**
* Convert an `arguments` object into an Array.
*
* @returns The arguments as an Array
* @private
*/
var _args = function(argumentsObj) {
return _slice.call(argumentsObj, 0);
};
/**
* Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`.
*
* @returns The target object, augmented
* @private
*/
var _extend = function() {
var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {};
for (i = 1, len = args.length; i < len; i++) {
if ((arg = args[i]) != null) {
for (prop in arg) {
if (_hasOwn.call(arg, prop)) {
src = target[prop];
copy = arg[prop];
if (target !== copy && copy !== undefined) {
target[prop] = copy;
}
}
}
}
}
return target;
};
/**
* Return a deep copy of the source object or array.
*
* @returns Object or Array
* @private
*/
var _deepCopy = function(source) {
var copy, i, len, prop;
if (typeof source !== "object" || source == null || typeof source.nodeType === "number") {
copy = source;
} else if (typeof source.length === "number") {
copy = [];
for (i = 0, len = source.length; i < len; i++) {
if (_hasOwn.call(source, i)) {
copy[i] = _deepCopy(source[i]);
}
}
} else {
copy = {};
for (prop in source) {
if (_hasOwn.call(source, prop)) {
copy[prop] = _deepCopy(source[prop]);
}
}
}
return copy;
};
/**
* Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep.
* The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to
* be kept.
*
* @returns A new filtered object.
* @private
*/
var _pick = function(obj, keys) {
var newObj = {};
for (var i = 0, len = keys.length; i < len; i++) {
if (keys[i] in obj) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
};
/**
* Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit.
* The inverse of `_pick`.
*
* @returns A new filtered object.
* @private
*/
var _omit = function(obj, keys) {
var newObj = {};
for (var prop in obj) {
if (keys.indexOf(prop) === -1) {
newObj[prop] = obj[prop];
}
}
return newObj;
};
/**
* Remove all owned, enumerable properties from an object.
*
* @returns The original object without its owned, enumerable properties.
* @private
*/
var _deleteOwnProperties = function(obj) {
if (obj) {
for (var prop in obj) {
if (_hasOwn.call(obj, prop)) {
delete obj[prop];
}
}
}
return obj;
};
/**
* Determine if an element is contained within another element.
*
* @returns Boolean
* @private
*/
var _containedBy = function(el, ancestorEl) {
if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) {
do {
if (el === ancestorEl) {
return true;
}
el = el.parentNode;
} while (el);
}
return false;
};
/**
* Get the URL path's parent directory.
*
* @returns String or `undefined`
* @private
*/
var _getDirPathOfUrl = function(url) {
var dir;
if (typeof url === "string" && url) {
dir = url.split("#")[0].split("?")[0];
dir = url.slice(0, url.lastIndexOf("/") + 1);
}
return dir;
};
/**
* Get the current script's URL by throwing an `Error` and analyzing it.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrlFromErrorStack = function(stack) {
var url, matches;
if (typeof stack === "string" && stack) {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
} else {
matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
}
}
}
return url;
};
/**
* Get the current script's URL by throwing an `Error` and analyzing it.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrlFromError = function() {
var url, err;
try {
throw new _Error();
} catch (e) {
err = e;
}
if (err) {
url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack);
}
return url;
};
/**
* Get the current script's URL.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrl = function() {
var jsPath, scripts, i;
if (_document.currentScript && (jsPath = _document.currentScript.src)) {
return jsPath;
}
scripts = _document.getElementsByTagName("script");
if (scripts.length === 1) {
return scripts[0].src || undefined;
}
if ("readyState" in scripts[0]) {
for (i = scripts.length; i--; ) {
if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) {
return jsPath;
}
}
}
if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) {
return jsPath;
}
if (jsPath = _getCurrentScriptUrlFromError()) {
return jsPath;
}
return undefined;
};
/**
* Get the unanimous parent directory of ALL script tags.
* If any script tags are either (a) inline or (b) from differing parent
* directories, this method must return `undefined`.
*
* @returns String or `undefined`
* @private
*/
var _getUnanimousScriptParentDir = function() {
var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script");
for (i = scripts.length; i--; ) {
if (!(jsPath = scripts[i].src)) {
jsDir = null;
break;
}
jsPath = _getDirPathOfUrl(jsPath);
if (jsDir == null) {
jsDir = jsPath;
} else if (jsDir !== jsPath) {
jsDir = null;
break;
}
}
return jsDir || undefined;
};
/**
* Get the presumed location of the "ZeroClipboard.swf" file, based on the location
* of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.).
*
* @returns String
* @private
*/
var _getDefaultSwfPath = function() {
var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || "";
return jsDir + "ZeroClipboard.swf";
};
/**
* Keep track of if the page is framed (in an `iframe`). This can never change.
* @private
*/
var _pageIsFramed = function() {
return window.opener == null && (!!window.top && window != window.top || !!window.parent && window != window.parent);
}();
/**
* Keep track of the state of the Flash object.
* @private
*/
var _flashState = {
bridge: null,
version: "0.0.0",
pluginType: "unknown",
disabled: null,
outdated: null,
sandboxed: null,
unavailable: null,
degraded: null,
deactivated: null,
overdue: null,
ready: null
};
/**
* The minimum Flash Player version required to use ZeroClipboard completely.
* @readonly
* @private
*/
var _minimumFlashVersion = "11.0.0";
/**
* The ZeroClipboard library version number, as reported by Flash, at the time the SWF was compiled.
*/
var _zcSwfVersion;
/**
* Keep track of all event listener registrations.
* @private
*/
var _handlers = {};
/**
* Keep track of the currently activated element.
* @private
*/
var _currentElement;
/**
* Keep track of the element that was activated when a `copy` process started.
* @private
*/
var _copyTarget;
/**
* Keep track of data for the pending clipboard transaction.
* @private
*/
var _clipData = {};
/**
* Keep track of data formats for the pending clipboard transaction.
* @private
*/
var _clipDataFormatMap = null;
/**
* Keep track of the Flash availability check timeout.
* @private
*/
var _flashCheckTimeout = 0;
/**
* Keep track of SWF network errors interval polling.
* @private
*/
var _swfFallbackCheckInterval = 0;
/**
* The `message` store for events
* @private
*/
var _eventMessages = {
ready: "Flash communication is established",
error: {
"flash-disabled": "Flash is disabled or not installed. May also be attempting to run Flash in a sandboxed iframe, which is impossible.",
"flash-outdated": "Flash is too outdated to support ZeroClipboard",
"flash-sandboxed": "Attempting to run Flash in a sandboxed iframe, which is impossible",
"flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript",
"flash-degraded": "Flash is unable to preserve data fidelity when communicating with JavaScript",
"flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate.\nThis may also mean that the ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity.\nMay also be attempting to run Flash in a sandboxed iframe, which is impossible.",
"flash-overdue": "Flash communication was established but NOT within the acceptable time limit",
"version-mismatch": "ZeroClipboard JS version number does not match ZeroClipboard SWF version number",
"clipboard-error": "At least one error was thrown while ZeroClipboard was attempting to inject your data into the clipboard",
"config-mismatch": "ZeroClipboard configuration does not match Flash's reality",
"swf-not-found": "The ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity"
}
};
/**
* The `name`s of `error` events that can only occur is Flash has at least
* been able to load the SWF successfully.
* @private
*/
var _errorsThatOnlyOccurAfterFlashLoads = [ "flash-unavailable", "flash-degraded", "flash-overdue", "version-mismatch", "config-mismatch", "clipboard-error" ];
/**
* The `name`s of `error` events that should likely result in the `_flashState`
* variable's property values being updated.
* @private
*/
var _flashStateErrorNames = [ "flash-disabled", "flash-outdated", "flash-sandboxed", "flash-unavailable", "flash-degraded", "flash-deactivated", "flash-overdue" ];
/**
* A RegExp to match the `name` property of `error` events related to Flash.
* @private
*/
var _flashStateErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.map(function(errorName) {
return errorName.replace(/^flash-/, "");
}).join("|") + ")$");
/**
* A RegExp to match the `name` property of `error` events related to Flash,
* which is enabled.
* @private
*/
var _flashStateEnabledErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.slice(1).map(function(errorName) {
return errorName.replace(/^flash-/, "");
}).join("|") + ")$");
/**
* ZeroClipboard configuration defaults for the Core module.
* @private
*/
var _globalConfig = {
swfPath: _getDefaultSwfPath(),
trustedDomains: window.location.host ? [ window.location.host ] : [],
cacheBust: true,
forceEnhancedClipboard: false,
flashLoadTimeout: 3e4,
autoActivate: true,
bubbleEvents: true,
containerId: "global-zeroclipboard-html-bridge",
containerClass: "global-zeroclipboard-container",
swfObjectId: "global-zeroclipboard-flash-bridge",
hoverClass: "zeroclipboard-is-hover",
activeClass: "zeroclipboard-is-active",
forceHandCursor: false,
title: null,
zIndex: 999999999
};
/**
* The underlying implementation of `ZeroClipboard.config`.
* @private
*/
var _config = function(options) {
if (typeof options === "object" && options !== null) {
for (var prop in options) {
if (_hasOwn.call(options, prop)) {
if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) {
_globalConfig[prop] = options[prop];
} else if (_flashState.bridge == null) {
if (prop === "containerId" || prop === "swfObjectId") {
if (_isValidHtml4Id(options[prop])) {
_globalConfig[prop] = options[prop];
} else {
throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
}
} else {
_globalConfig[prop] = options[prop];
}
}
}
}
}
if (typeof options === "string" && options) {
if (_hasOwn.call(_globalConfig, options)) {
return _globalConfig[options];
}
return;
}
return _deepCopy(_globalConfig);
};
/**
* The underlying implementation of `ZeroClipboard.state`.
* @private
*/
var _state = function() {
_detectSandbox();
return {
browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]),
flash: _omit(_flashState, [ "bridge" ]),
zeroclipboard: {
version: ZeroClipboard.version,
config: ZeroClipboard.config()
}
};
};
/**
* The underlying implementation of `ZeroClipboard.isFlashUnusable`.
* @private
*/
var _isFlashUnusable = function() {
return !!(_flashState.disabled || _flashState.outdated || _flashState.sandboxed || _flashState.unavailable || _flashState.degraded || _flashState.deactivated);
};
/**
* The underlying implementation of `ZeroClipboard.on`.
* @private
*/
var _on = function(eventType, listener) {
var i, len, events, added = {};
if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
ZeroClipboard.on(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
added[eventType] = true;
if (!_handlers[eventType]) {
_handlers[eventType] = [];
}
_handlers[eventType].push(listener);
}
if (added.ready && _flashState.ready) {
ZeroClipboard.emit({
type: "ready"
});
}
if (added.error) {
for (i = 0, len = _flashStateErrorNames.length; i < len; i++) {
if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")] === true) {
ZeroClipboard.emit({
type: "error",
name: _flashStateErrorNames[i]
});
break;
}
}
if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) {
ZeroClipboard.emit({
type: "error",
name: "version-mismatch",
jsVersion: ZeroClipboard.version,
swfVersion: _zcSwfVersion
});
}
}
}
return ZeroClipboard;
};
/**
* The underlying implementation of `ZeroClipboard.off`.
* @private
*/
var _off = function(eventType, listener) {
var i, len, foundIndex, events, perEventHandlers;
if (arguments.length === 0) {
events = _keys(_handlers);
} else if (typeof eventType === "string" && eventType) {
events = eventType.split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
ZeroClipboard.off(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].toLowerCase().replace(/^on/, "");
perEventHandlers = _handlers[eventType];
if (perEventHandlers && perEventHandlers.length) {
if (listener) {
foundIndex = perEventHandlers.indexOf(listener);
while (foundIndex !== -1) {
perEventHandlers.splice(foundIndex, 1);
foundIndex = perEventHandlers.indexOf(listener, foundIndex);
}
} else {
perEventHandlers.length = 0;
}
}
}
}
return ZeroClipboard;
};
/**
* The underlying implementation of `ZeroClipboard.handlers`.
* @private
*/
var _listeners = function(eventType) {
var copy;
if (typeof eventType === "string" && eventType) {
copy = _deepCopy(_handlers[eventType]) || null;
} else {
copy = _deepCopy(_handlers);
}
return copy;
};
/**
* The underlying implementation of `ZeroClipboard.emit`.
* @private
*/
var _emit = function(event) {
var eventCopy, returnVal, tmp;
event = _createEvent(event);
if (!event) {
return;
}
if (_preprocessEvent(event)) {
return;
}
if (event.type === "ready" && _flashState.overdue === true) {
return ZeroClipboard.emit({
type: "error",
name: "flash-overdue"
});
}
eventCopy = _extend({}, event);
_dispatchCallbacks.call(this, eventCopy);
if (event.type === "copy") {
tmp = _mapClipDataToFlash(_clipData);
returnVal = tmp.data;
_clipDataFormatMap = tmp.formatMap;
}
return returnVal;
};
/**
* The underlying implementation of `ZeroClipboard.create`.
* @private
*/
var _create = function() {
var previousState = _flashState.sandboxed;
_detectSandbox();
if (typeof _flashState.ready !== "boolean") {
_flashState.ready = false;
}
if (_flashState.sandboxed !== previousState && _flashState.sandboxed === true) {
_flashState.ready = false;
ZeroClipboard.emit({
type: "error",
name: "flash-sandboxed"
});
} else if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
var maxWait = _globalConfig.flashLoadTimeout;
if (typeof maxWait === "number" && maxWait >= 0) {
_flashCheckTimeout = _setTimeout(function() {
if (typeof _flashState.deactivated !== "boolean") {
_flashState.deactivated = true;
}
if (_flashState.deactivated === true) {
ZeroClipboard.emit({
type: "error",
name: "flash-deactivated"
});
}
}, maxWait);
}
_flashState.overdue = false;
_embedSwf();
}
};
/**
* The underlying implementation of `ZeroClipboard.destroy`.
* @private
*/
var _destroy = function() {
ZeroClipboard.clearData();
ZeroClipboard.blur();
ZeroClipboard.emit("destroy");
_unembedSwf();
ZeroClipboard.off();
};
/**
* The underlying implementation of `ZeroClipboard.setData`.
* @private
*/
var _setData = function(format, data) {
var dataObj;
if (typeof format === "object" && format && typeof data === "undefined") {
dataObj = format;
ZeroClipboard.clearData();
} else if (typeof format === "string" && format) {
dataObj = {};
dataObj[format] = data;
} else {
return;
}
for (var dataFormat in dataObj) {
if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
_clipData[dataFormat] = dataObj[dataFormat];
}
}
};
/**
* The underlying implementation of `ZeroClipboard.clearData`.
* @private
*/
var _clearData = function(format) {
if (typeof format === "undefined") {
_deleteOwnProperties(_clipData);
_clipDataFormatMap = null;
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
delete _clipData[format];
}
};
/**
* The underlying implementation of `ZeroClipboard.getData`.
* @private
*/
var _getData = function(format) {
if (typeof format === "undefined") {
return _deepCopy(_clipData);
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
return _clipData[format];
}
};
/**
* The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`.
* @private
*/
var _focus = function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
if (_currentElement) {
_removeClass(_currentElement, _globalConfig.activeClass);
if (_currentElement !== element) {
_removeClass(_currentElement, _globalConfig.hoverClass);
}
}
_currentElement = element;
_addClass(element, _globalConfig.hoverClass);
var newTitle = element.getAttribute("title") || _globalConfig.title;
if (typeof newTitle === "string" && newTitle) {
var htmlBridge = _getHtmlBridge(_flashState.bridge);
if (htmlBridge) {
htmlBridge.setAttribute("title", newTitle);
}
}
var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
_setHandCursor(useHandCursor);
_reposition();
};
/**
* The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`.
* @private
*/
var _blur = function() {
var htmlBridge = _getHtmlBridge(_flashState.bridge);
if (htmlBridge) {
htmlBridge.removeAttribute("title");
htmlBridge.style.left = "0px";
htmlBridge.style.top = "-9999px";
htmlBridge.style.width = "1px";
htmlBridge.style.height = "1px";
}
if (_currentElement) {
_removeClass(_currentElement, _globalConfig.hoverClass);
_removeClass(_currentElement, _globalConfig.activeClass);
_currentElement = null;
}
};
/**
* The underlying implementation of `ZeroClipboard.activeElement`.
* @private
*/
var _activeElement = function() {
return _currentElement || null;
};
/**
* Check if a value is a valid HTML4 `ID` or `Name` token.
* @private
*/
var _isValidHtml4Id = function(id) {
return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id);
};
/**
* Create or update an `event` object, based on the `eventType`.
* @private
*/
var _createEvent = function(event) {
var eventType;
if (typeof event === "string" && event) {
eventType = event;
event = {};
} else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
eventType = event.type;
}
if (!eventType) {
return;
}
eventType = eventType.toLowerCase();
if (!event.target && (/^(copy|aftercopy|_click)$/.test(eventType) || eventType === "error" && event.name === "clipboard-error")) {
event.target = _copyTarget;
}
_extend(event, {
type: eventType,
target: event.target || _currentElement || null,
relatedTarget: event.relatedTarget || null,
currentTarget: _flashState && _flashState.bridge || null,
timeStamp: event.timeStamp || _now() || null
});
var msg = _eventMessages[event.type];
if (event.type === "error" && event.name && msg) {
msg = msg[event.name];
}
if (msg) {
event.message = msg;
}
if (event.type === "ready") {
_extend(event, {
target: null,
version: _flashState.version
});
}
if (event.type === "error") {
if (_flashStateErrorNameMatchingRegex.test(event.name)) {
_extend(event, {
target: null,
minimumVersion: _minimumFlashVersion
});
}
if (_flashStateEnabledErrorNameMatchingRegex.test(event.name)) {
_extend(event, {
version: _flashState.version
});
}
}
if (event.type === "copy") {
event.clipboardData = {
setData: ZeroClipboard.setData,
clearData: ZeroClipboard.clearData
};
}
if (event.type === "aftercopy") {
event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
}
if (event.target && !event.relatedTarget) {
event.relatedTarget = _getRelatedTarget(event.target);
}
return _addMouseData(event);
};
/**
* Get a relatedTarget from the target's `data-clipboard-target` attribute
* @private
*/
var _getRelatedTarget = function(targetEl) {
var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
};
/**
* Add element and position data to `MouseEvent` instances
* @private
*/
var _addMouseData = function(event) {
if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
var srcElement = event.target;
var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
var pos = _getElementPosition(srcElement);
var screenLeft = _window.screenLeft || _window.screenX || 0;
var screenTop = _window.screenTop || _window.screenY || 0;
var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
var clientX = pageX - scrollLeft;
var clientY = pageY - scrollTop;
var screenX = screenLeft + clientX;
var screenY = screenTop + clientY;
var moveX = typeof event.movementX === "number" ? event.movementX : 0;
var moveY = typeof event.movementY === "number" ? event.movementY : 0;
delete event._stageX;
delete event._stageY;
_extend(event, {
srcElement: srcElement,
fromElement: fromElement,
toElement: toElement,
screenX: screenX,
screenY: screenY,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
x: clientX,
y: clientY,
movementX: moveX,
movementY: moveY,
offsetX: 0,
offsetY: 0,
layerX: 0,
layerY: 0
});
}
return event;
};
/**
* Determine if an event's registered handlers should be execute synchronously or asynchronously.
*
* @returns {boolean}
* @private
*/
var _shouldPerformAsync = function(event) {
var eventType = event && typeof event.type === "string" && event.type || "";
return !/^(?:(?:before)?copy|destroy)$/.test(eventType);
};
/**
* Control if a callback should be executed asynchronously or not.
*
* @returns `undefined`
* @private
*/
var _dispatchCallback = function(func, context, args, async) {
if (async) {
_setTimeout(function() {
func.apply(context, args);
}, 0);
} else {
func.apply(context, args);
}
};
/**
* Handle the actual dispatching of events to client instances.
*
* @returns `undefined`
* @private
*/
var _dispatchCallbacks = function(event) {
if (!(typeof event === "object" && event && event.type)) {
return;
}
var async = _shouldPerformAsync(event);
var wildcardTypeHandlers = _handlers["*"] || [];
var specificTypeHandlers = _handlers[event.type] || [];
var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
if (handlers && handlers.length) {
var i, len, func, context, eventCopy, originalContext = this;
for (i = 0, len = handlers.length; i < len; i++) {
func = handlers[i];
context = originalContext;
if (typeof func === "string" && typeof _window[func] === "function") {
func = _window[func];
}
if (typeof func === "object" && func && typeof func.handleEvent === "function") {
context = func;
func = func.handleEvent;
}
if (typeof func === "function") {
eventCopy = _extend({}, event);
_dispatchCallback(func, context, [ eventCopy ], async);
}
}
}
return this;
};
/**
* Check an `error` event's `name` property to see if Flash has
* already loaded, which rules out possible `iframe` sandboxing.
* @private
*/
var _getSandboxStatusFromErrorEvent = function(event) {
var isSandboxed = null;
if (_pageIsFramed === false || event && event.type === "error" && event.name && _errorsThatOnlyOccurAfterFlashLoads.indexOf(event.name) !== -1) {
isSandboxed = false;
}
return isSandboxed;
};
/**
* Preprocess any special behaviors, reactions, or state changes after receiving this event.
* Executes only once per event emitted, NOT once per client.
* @private
*/
var _preprocessEvent = function(event) {
var element = event.target || _currentElement || null;
var sourceIsSwf = event._source === "swf";
delete event._source;
switch (event.type) {
case "error":
var isSandboxed = event.name === "flash-sandboxed" || _getSandboxStatusFromErrorEvent(event);
if (typeof isSandboxed === "boolean") {
_flashState.sandboxed = isSandboxed;
}
if (_flashStateErrorNames.indexOf(event.name) !== -1) {
_extend(_flashState, {
disabled: event.name === "flash-disabled",
outdated: event.name === "flash-outdated",
unavailable: event.name === "flash-unavailable",
degraded: event.name === "flash-degraded",
deactivated: event.name === "flash-deactivated",
overdue: event.name === "flash-overdue",
ready: false
});
} else if (event.name === "version-mismatch") {
_zcSwfVersion = event.swfVersion;
_extend(_flashState, {
disabled: false,
outdated: false,
unavailable: false,
degraded: false,
deactivated: false,
overdue: false,
ready: false
});
}
_clearTimeoutsAndPolling();
break;
case "ready":
_zcSwfVersion = event.swfVersion;
var wasDeactivated = _flashState.deactivated === true;
_extend(_flashState, {
disabled: false,
outdated: false,
sandboxed: false,
unavailable: false,
degraded: false,
deactivated: false,
overdue: wasDeactivated,
ready: !wasDeactivated
});
_clearTimeoutsAndPolling();
break;
case "beforecopy":
_copyTarget = element;
break;
case "copy":
var textContent, htmlContent, targetEl = event.relatedTarget;
if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) {
event.clipboardData.clearData();
event.clipboardData.setData("text/plain", textContent);
if (htmlContent !== textContent) {
event.clipboardData.setData("text/html", htmlContent);
}
} else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) {
event.clipboardData.clearData();
event.clipboardData.setData("text/plain", textContent);
}
break;
case "aftercopy":
_queueEmitClipboardErrors(event);
ZeroClipboard.clearData();
if (element && element !== _safeActiveElement() && element.focus) {
element.focus();
}
break;
case "_mouseover":
ZeroClipboard.focus(element);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
_fireMouseEvent(_extend({}, event, {
type: "mouseenter",
bubbles: false,
cancelable: false
}));
}
_fireMouseEvent(_extend({}, event, {
type: "mouseover"
}));
}
break;
case "_mouseout":
ZeroClipboard.blur();
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
_fireMouseEvent(_extend({}, event, {
type: "mouseleave",
bubbles: false,
cancelable: false
}));
}
_fireMouseEvent(_extend({}, event, {
type: "mouseout"
}));
}
break;
case "_mousedown":
_addClass(element, _globalConfig.activeClass);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
case "_mouseup":
_removeClass(element, _globalConfig.activeClass);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
case "_click":
_copyTarget = null;
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
case "_mousemove":
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
}
if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
return true;
}
};
/**
* Check an "aftercopy" event for clipboard errors and emit a corresponding "error" event.
* @private
*/
var _queueEmitClipboardErrors = function(aftercopyEvent) {
if (aftercopyEvent.errors && aftercopyEvent.errors.length > 0) {
var errorEvent = _deepCopy(aftercopyEvent);
_extend(errorEvent, {
type: "error",
name: "clipboard-error"
});
delete errorEvent.success;
_setTimeout(function() {
ZeroClipboard.emit(errorEvent);
}, 0);
}
};
/**
* Dispatch a synthetic MouseEvent.
*
* @returns `undefined`
* @private
*/
var _fireMouseEvent = function(event) {
if (!(event && typeof event.type === "string" && event)) {
return;
}
var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
view: doc.defaultView || _window,
canBubble: true,
cancelable: true,
detail: event.type === "click" ? 1 : 0,
button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
}, args = _extend(defaults, event);
if (!target) {
return;
}
if (doc.createEvent && target.dispatchEvent) {
args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ];
e = doc.createEvent("MouseEvents");
if (e.initMouseEvent) {
e.initMouseEvent.apply(e, args);
e._source = "js";
target.dispatchEvent(e);
}
}
};
/**
* Continuously poll the DOM until either:
* (a) the fallback content becomes visible, or
* (b) we receive an event from SWF (handled elsewhere)
*
* IMPORTANT:
* This is NOT a necessary check but it can result in significantly faster
* detection of bad `swfPath` configuration and/or network/server issues [in
* supported browsers] than waiting for the entire `flashLoadTimeout` duration
* to elapse before detecting that the SWF cannot be loaded. The detection
* duration can be anywhere from 10-30 times faster [in supported browsers] by
* using this approach.
*
* @returns `undefined`
* @private
*/
var _watchForSwfFallbackContent = function() {
var maxWait = _globalConfig.flashLoadTimeout;
if (typeof maxWait === "number" && maxWait >= 0) {
var pollWait = Math.min(1e3, maxWait / 10);
var fallbackContentId = _globalConfig.swfObjectId + "_fallbackContent";
_swfFallbackCheckInterval = _setInterval(function() {
var el = _document.getElementById(fallbackContentId);
if (_isElementVisible(el)) {
_clearTimeoutsAndPolling();
_flashState.deactivated = null;
ZeroClipboard.emit({
type: "error",
name: "swf-not-found"
});
}
}, pollWait);
}
};
/**
* Create the HTML bridge element to embed the Flash object into.
* @private
*/
var _createHtmlBridge = function() {
var container = _document.createElement("div");
container.id = _globalConfig.containerId;
container.className = _globalConfig.containerClass;
container.style.position = "absolute";
container.style.left = "0px";
container.style.top = "-9999px";
container.style.width = "1px";
container.style.height = "1px";
container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
return container;
};
/**
* Get the HTML element container that wraps the Flash bridge object/element.
* @private
*/
var _getHtmlBridge = function(flashBridge) {
var htmlBridge = flashBridge && flashBridge.parentNode;
while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) {
htmlBridge = htmlBridge.parentNode;
}
return htmlBridge || null;
};
/**
* Create the SWF object.
*
* @returns The SWF object reference.
* @private
*/
var _embedSwf = function() {
var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
if (!flashBridge) {
var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
var flashvars = _vars(_extend({
jsVersion: ZeroClipboard.version
}, _globalConfig));
var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
container = _createHtmlBridge();
var divToBeReplaced = _document.createElement("div");
container.appendChild(divToBeReplaced);
_document.body.appendChild(container);
var tmpDiv = _document.createElement("div");
var usingActiveX = _flashState.pluginType === "activex";
tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (usingActiveX ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (usingActiveX ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + '<div id="' + _globalConfig.swfObjectId + '_fallbackContent"> </div>' + "</object>";
flashBridge = tmpDiv.firstChild;
tmpDiv = null;
_unwrap(flashBridge).ZeroClipboard = ZeroClipboard;
container.replaceChild(flashBridge, divToBeReplaced);
_watchForSwfFallbackContent();
}
if (!flashBridge) {
flashBridge = _document[_globalConfig.swfObjectId];
if (flashBridge && (len = flashBridge.length)) {
flashBridge = flashBridge[len - 1];
}
if (!flashBridge && container) {
flashBridge = container.firstChild;
}
}
_flashState.bridge = flashBridge || null;
return flashBridge;
};
/**
* Destroy the SWF object.
* @private
*/
var _unembedSwf = function() {
var flashBridge = _flashState.bridge;
if (flashBridge) {
var htmlBridge = _getHtmlBridge(flashBridge);
if (htmlBridge) {
if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
flashBridge.style.display = "none";
(function removeSwfFromIE() {
if (flashBridge.readyState === 4) {
for (var prop in flashBridge) {
if (typeof flashBridge[prop] === "function") {
flashBridge[prop] = null;
}
}
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
} else {
_setTimeout(removeSwfFromIE, 10);
}
})();
} else {
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
}
}
_clearTimeoutsAndPolling();
_flashState.ready = null;
_flashState.bridge = null;
_flashState.deactivated = null;
_zcSwfVersion = undefined;
}
};
/**
* Map the data format names of the "clipData" to Flash-friendly names.
*
* @returns A new transformed object.
* @private
*/
var _mapClipDataToFlash = function(clipData) {
var newClipData = {}, formatMap = {};
if (!(typeof clipData === "object" && clipData)) {
return;
}
for (var dataFormat in clipData) {
if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
switch (dataFormat.toLowerCase()) {
case "text/plain":
case "text":
case "air:text":
case "flash:text":
newClipData.text = clipData[dataFormat];
formatMap.text = dataFormat;
break;
case "text/html":
case "html":
case "air:html":
case "flash:html":
newClipData.html = clipData[dataFormat];
formatMap.html = dataFormat;
break;
case "application/rtf":
case "text/rtf":
case "rtf":
case "richtext":
case "air:rtf":
case "flash:rtf":
newClipData.rtf = clipData[dataFormat];
formatMap.rtf = dataFormat;
break;
default:
break;
}
}
}
return {
data: newClipData,
formatMap: formatMap
};
};
/**
* Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping).
*
* @returns A new transformed object.
* @private
*/
var _mapClipResultsFromFlash = function(clipResults, formatMap) {
if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) {
return clipResults;
}
var newResults = {};
for (var prop in clipResults) {
if (_hasOwn.call(clipResults, prop)) {
if (prop === "errors") {
newResults[prop] = clipResults[prop] ? clipResults[prop].slice() : [];
for (var i = 0, len = newResults[prop].length; i < len; i++) {
newResults[prop][i].format = formatMap[newResults[prop][i].format];
}
} else if (prop !== "success" && prop !== "data") {
newResults[prop] = clipResults[prop];
} else {
newResults[prop] = {};
var tmpHash = clipResults[prop];
for (var dataFormat in tmpHash) {
if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) {
newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat];
}
}
}
}
}
return newResults;
};
/**
* Will look at a path, and will create a "?noCache={time}" or "&noCache={time}"
* query param string to return. Does NOT append that string to the original path.
* This is useful because ExternalInterface often breaks when a Flash SWF is cached.
*
* @returns The `noCache` query param with necessary "?"/"&" prefix.
* @private
*/
var _cacheBust = function(path, options) {
var cacheBust = options == null || options && options.cacheBust === true;
if (cacheBust) {
return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now();
} else {
return "";
}
};
/**
* Creates a query string for the FlashVars param.
* Does NOT include the cache-busting query param.
*
* @returns FlashVars query string
* @private
*/
var _vars = function(options) {
var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
if (options.trustedDomains) {
if (typeof options.trustedDomains === "string") {
domains = [ options.trustedDomains ];
} else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
domains = options.trustedDomains;
}
}
if (domains && domains.length) {
for (i = 0, len = domains.length; i < len; i++) {
if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
domain = _extractDomain(domains[i]);
if (!domain) {
continue;
}
if (domain === "*") {
trustedOriginsExpanded.length = 0;
trustedOriginsExpanded.push(domain);
break;
}
trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
}
}
}
if (trustedOriginsExpanded.length) {
str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
}
if (options.forceEnhancedClipboard === true) {
str += (str ? "&" : "") + "forceEnhancedClipboard=true";
}
if (typeof options.swfObjectId === "string" && options.swfObjectId) {
str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
}
if (typeof options.jsVersion === "string" && options.jsVersion) {
str += (str ? "&" : "") + "jsVersion=" + _encodeURIComponent(options.jsVersion);
}
return str;
};
/**
* Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or
* URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/").
*
* @returns the domain
* @private
*/
var _extractDomain = function(originOrUrl) {
if (originOrUrl == null || originOrUrl === "") {
return null;
}
originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
if (originOrUrl === "") {
return null;
}
var protocolIndex = originOrUrl.indexOf("//");
originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
var pathIndex = originOrUrl.indexOf("/");
originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
return null;
}
return originOrUrl || null;
};
/**
* Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`.
*
* @returns The appropriate script access level.
* @private
*/
var _determineScriptAccess = function() {
var _extractAllDomains = function(origins) {
var i, len, tmp, resultsArray = [];
if (typeof origins === "string") {
origins = [ origins ];
}
if (!(typeof origins === "object" && origins && typeof origins.length === "number")) {
return resultsArray;
}
for (i = 0, len = origins.length; i < len; i++) {
if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) {
if (tmp === "*") {
resultsArray.length = 0;
resultsArray.push("*");
break;
}
if (resultsArray.indexOf(tmp) === -1) {
resultsArray.push(tmp);
}
}
}
return resultsArray;
};
return function(currentDomain, configOptions) {
var swfDomain = _extractDomain(configOptions.swfPath);
if (swfDomain === null) {
swfDomain = currentDomain;
}
var trustedDomains = _extractAllDomains(configOptions.trustedDomains);
var len = trustedDomains.length;
if (len > 0) {
if (len === 1 && trustedDomains[0] === "*") {
return "always";
}
if (trustedDomains.indexOf(currentDomain) !== -1) {
if (len === 1 && currentDomain === swfDomain) {
return "sameDomain";
}
return "always";
}
}
return "never";
};
}();
/**
* Get the currently active/focused DOM element.
*
* @returns the currently active/focused element, or `null`
* @private
*/
var _safeActiveElement = function() {
try {
return _document.activeElement;
} catch (err) {
return null;
}
};
/**
* Add a class to an element, if it doesn't already have it.
*
* @returns The element, with its new class added.
* @private
*/
var _addClass = function(element, value) {
var c, cl, className, classNames = [];
if (typeof value === "string" && value) {
classNames = value.split(/\s+/);
}
if (element && element.nodeType === 1 && classNames.length > 0) {
if (element.classList) {
for (c = 0, cl = classNames.length; c < cl; c++) {
element.classList.add(classNames[c]);
}
} else if (element.hasOwnProperty("className")) {
className = " " + element.className + " ";
for (c = 0, cl = classNames.length; c < cl; c++) {
if (className.indexOf(" " + classNames[c] + " ") === -1) {
className += classNames[c] + " ";
}
}
element.className = className.replace(/^\s+|\s+$/g, "");
}
}
return element;
};
/**
* Remove a class from an element, if it has it.
*
* @returns The element, with its class removed.
* @private
*/
var _removeClass = function(element, value) {
var c, cl, className, classNames = [];
if (typeof value === "string" && value) {
classNames = value.split(/\s+/);
}
if (element && element.nodeType === 1 && classNames.length > 0) {
if (element.classList && element.classList.length > 0) {
for (c = 0, cl = classNames.length; c < cl; c++) {
element.classList.remove(classNames[c]);
}
} else if (element.className) {
className = (" " + element.className + " ").replace(/[\r\n\t]/g, " ");
for (c = 0, cl = classNames.length; c < cl; c++) {
className = className.replace(" " + classNames[c] + " ", " ");
}
element.className = className.replace(/^\s+|\s+$/g, "");
}
}
return element;
};
/**
* Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`,
* then we assume that it should be a hand ("pointer") cursor if the element
* is an anchor element ("a" tag).
*
* @returns The computed style property.
* @private
*/
var _getStyle = function(el, prop) {
var value = _getComputedStyle(el, null).getPropertyValue(prop);
if (prop === "cursor") {
if (!value || value === "auto") {
if (el.nodeName === "A") {
return "pointer";
}
}
}
return value;
};
/**
* Get the absolutely positioned coordinates of a DOM element.
*
* @returns Object containing the element's position, width, and height.
* @private
*/
var _getElementPosition = function(el) {
var pos = {
left: 0,
top: 0,
width: 0,
height: 0
};
if (el.getBoundingClientRect) {
var elRect = el.getBoundingClientRect();
var pageXOffset = _window.pageXOffset;
var pageYOffset = _window.pageYOffset;
var leftBorderWidth = _document.documentElement.clientLeft || 0;
var topBorderWidth = _document.documentElement.clientTop || 0;
var leftBodyOffset = 0;
var topBodyOffset = 0;
if (_getStyle(_document.body, "position") === "relative") {
var bodyRect = _document.body.getBoundingClientRect();
var htmlRect = _document.documentElement.getBoundingClientRect();
leftBodyOffset = bodyRect.left - htmlRect.left || 0;
topBodyOffset = bodyRect.top - htmlRect.top || 0;
}
pos.left = elRect.left + pageXOffset - leftBorderWidth - leftBodyOffset;
pos.top = elRect.top + pageYOffset - topBorderWidth - topBodyOffset;
pos.width = "width" in elRect ? elRect.width : elRect.right - elRect.left;
pos.height = "height" in elRect ? elRect.height : elRect.bottom - elRect.top;
}
return pos;
};
/**
* Determine is an element is visible somewhere within the document (page).
*
* @returns Boolean
* @private
*/
var _isElementVisible = function(el) {
if (!el) {
return false;
}
var styles = _getComputedStyle(el, null);
var hasCssHeight = _parseFloat(styles.height) > 0;
var hasCssWidth = _parseFloat(styles.width) > 0;
var hasCssTop = _parseFloat(styles.top) >= 0;
var hasCssLeft = _parseFloat(styles.left) >= 0;
var cssKnows = hasCssHeight && hasCssWidth && hasCssTop && hasCssLeft;
var rect = cssKnows ? null : _getElementPosition(el);
var isVisible = styles.display !== "none" && styles.visibility !== "collapse" && (cssKnows || !!rect && (hasCssHeight || rect.height > 0) && (hasCssWidth || rect.width > 0) && (hasCssTop || rect.top >= 0) && (hasCssLeft || rect.left >= 0));
return isVisible;
};
/**
* Clear all existing timeouts and interval polling delegates.
*
* @returns `undefined`
* @private
*/
var _clearTimeoutsAndPolling = function() {
_clearTimeout(_flashCheckTimeout);
_flashCheckTimeout = 0;
_clearInterval(_swfFallbackCheckInterval);
_swfFallbackCheckInterval = 0;
};
/**
* Reposition the Flash object to cover the currently activated element.
*
* @returns `undefined`
* @private
*/
var _reposition = function() {
var htmlBridge;
if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
var pos = _getElementPosition(_currentElement);
_extend(htmlBridge.style, {
width: pos.width + "px",
height: pos.height + "px",
top: pos.top + "px",
left: pos.left + "px",
zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
});
}
};
/**
* Sends a signal to the Flash object to display the hand cursor if `true`.
*
* @returns `undefined`
* @private
*/
var _setHandCursor = function(enabled) {
if (_flashState.ready === true) {
if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
_flashState.bridge.setHandCursor(enabled);
} else {
_flashState.ready = false;
}
}
};
/**
* Get a safe value for `zIndex`
*
* @returns an integer, or "auto"
* @private
*/
var _getSafeZIndex = function(val) {
if (/^(?:auto|inherit)$/.test(val)) {
return val;
}
var zIndex;
if (typeof val === "number" && !_isNaN(val)) {
zIndex = val;
} else if (typeof val === "string") {
zIndex = _getSafeZIndex(_parseInt(val, 10));
}
return typeof zIndex === "number" ? zIndex : "auto";
};
/**
* Attempt to detect if ZeroClipboard is executing inside of a sandboxed iframe.
* If it is, Flash Player cannot be used, so ZeroClipboard is dead in the water.
*
* @see {@link http://lists.w3.org/Archives/Public/public-whatwg-archive/2014Dec/0002.html}
* @see {@link https://github.com/zeroclipboard/zeroclipboard/issues/511}
* @see {@link http://zeroclipboard.org/test-iframes.html}
*
* @returns `true` (is sandboxed), `false` (is not sandboxed), or `null` (uncertain)
* @private
*/
var _detectSandbox = function(doNotReassessFlashSupport) {
var effectiveScriptOrigin, frame, frameError, previousState = _flashState.sandboxed, isSandboxed = null;
doNotReassessFlashSupport = doNotReassessFlashSupport === true;
if (_pageIsFramed === false) {
isSandboxed = false;
} else {
try {
frame = window.frameElement || null;
} catch (e) {
frameError = {
name: e.name,
message: e.message
};
}
if (frame && frame.nodeType === 1 && frame.nodeName === "IFRAME") {
try {
isSandboxed = frame.hasAttribute("sandbox");
} catch (e) {
isSandboxed = null;
}
} else {
try {
effectiveScriptOrigin = document.domain || null;
} catch (e) {
effectiveScriptOrigin = null;
}
if (effectiveScriptOrigin === null || frameError && frameError.name === "SecurityError" && /(^|[\s\(\[@])sandbox(es|ed|ing|[\s\.,!\)\]@]|$)/.test(frameError.message.toLowerCase())) {
isSandboxed = true;
}
}
}
_flashState.sandboxed = isSandboxed;
if (previousState !== isSandboxed && !doNotReassessFlashSupport) {
_detectFlashSupport(_ActiveXObject);
}
return isSandboxed;
};
/**
* Detect the Flash Player status, version, and plugin type.
*
* @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code}
* @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript}
*
* @returns `undefined`
* @private
*/
var _detectFlashSupport = function(ActiveXObject) {
var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = "";
/**
* Derived from Apple's suggested sniffer.
* @param {String} desc e.g. "Shockwave Flash 7.0 r61"
* @returns {String} "7.0.61"
* @private
*/
function parseFlashVersion(desc) {
var matches = desc.match(/[\d]+/g);
matches.length = 3;
return matches.join(".");
}
function isPepperFlash(flashPlayerFileName) {
return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin");
}
function inspectPlugin(plugin) {
if (plugin) {
hasFlash = true;
if (plugin.version) {
flashVersion = parseFlashVersion(plugin.version);
}
if (!flashVersion && plugin.description) {
flashVersion = parseFlashVersion(plugin.description);
}
if (plugin.filename) {
isPPAPI = isPepperFlash(plugin.filename);
}
}
}
if (_navigator.plugins && _navigator.plugins.length) {
plugin = _navigator.plugins["Shockwave Flash"];
inspectPlugin(plugin);
if (_navigator.plugins["Shockwave Flash 2.0"]) {
hasFlash = true;
flashVersion = "2.0.0.11";
}
} else if (_navigator.mimeTypes && _navigator.mimeTypes.length) {
mimeType = _navigator.mimeTypes["application/x-shockwave-flash"];
plugin = mimeType && mimeType.enabledPlugin;
inspectPlugin(plugin);
} else if (typeof ActiveXObject !== "undefined") {
isActiveX = true;
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
hasFlash = true;
flashVersion = parseFlashVersion(ax.GetVariable("$version"));
} catch (e1) {
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
hasFlash = true;
flashVersion = "6.0.21";
} catch (e2) {
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
hasFlash = true;
flashVersion = parseFlashVersion(ax.GetVariable("$version"));
} catch (e3) {
isActiveX = false;
}
}
}
}
_flashState.disabled = hasFlash !== true;
_flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion);
_flashState.version = flashVersion || "0.0.0";
_flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown";
};
/**
* Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later.
*/
_detectFlashSupport(_ActiveXObject);
/**
* Always assess the `sandboxed` state of the page at important Flash-related moments.
*/
_detectSandbox(true);
/**
* A shell constructor for `ZeroClipboard` client instances.
*
* @constructor
*/
var ZeroClipboard = function() {
if (!(this instanceof ZeroClipboard)) {
return new ZeroClipboard();
}
if (typeof ZeroClipboard._createClient === "function") {
ZeroClipboard._createClient.apply(this, _args(arguments));
}
};
/**
* The ZeroClipboard library's version number.
*
* @static
* @readonly
* @property {string}
*/
_defineProperty(ZeroClipboard, "version", {
value: "2.2.0",
writable: false,
configurable: true,
enumerable: true
});
/**
* Update or get a copy of the ZeroClipboard global configuration.
* Returns a copy of the current/updated configuration.
*
* @returns Object
* @static
*/
ZeroClipboard.config = function() {
return _config.apply(this, _args(arguments));
};
/**
* Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard.
*
* @returns Object
* @static
*/
ZeroClipboard.state = function() {
return _state.apply(this, _args(arguments));
};
/**
* Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc.
*
* @returns Boolean
* @static
*/
ZeroClipboard.isFlashUnusable = function() {
return _isFlashUnusable.apply(this, _args(arguments));
};
/**
* Register an event listener.
*
* @returns `ZeroClipboard`
* @static
*/
ZeroClipboard.on = function() {
return _on.apply(this, _args(arguments));
};
/**
* Unregister an event listener.
* If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`.
* If no `eventType` is provided, it will unregister all listeners for every event type.
*
* @returns `ZeroClipboard`
* @static
*/
ZeroClipboard.off = function() {
return _off.apply(this, _args(arguments));
};
/**
* Retrieve event listeners for an `eventType`.
* If no `eventType` is provided, it will retrieve all listeners for every event type.
*
* @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null`
*/
ZeroClipboard.handlers = function() {
return _listeners.apply(this, _args(arguments));
};
/**
* Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners.
*
* @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`.
* @static
*/
ZeroClipboard.emit = function() {
return _emit.apply(this, _args(arguments));
};
/**
* Create and embed the Flash object.
*
* @returns The Flash object
* @static
*/
ZeroClipboard.create = function() {
return _create.apply(this, _args(arguments));
};
/**
* Self-destruct and clean up everything, including the embedded Flash object.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.destroy = function() {
return _destroy.apply(this, _args(arguments));
};
/**
* Set the pending data for clipboard injection.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.setData = function() {
return _setData.apply(this, _args(arguments));
};
/**
* Clear the pending data for clipboard injection.
* If no `format` is provided, all pending data formats will be cleared.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.clearData = function() {
return _clearData.apply(this, _args(arguments));
};
/**
* Get a copy of the pending data for clipboard injection.
* If no `format` is provided, a copy of ALL pending data formats will be returned.
*
* @returns `String` or `Object`
* @static
*/
ZeroClipboard.getData = function() {
return _getData.apply(this, _args(arguments));
};
/**
* Sets the current HTML object that the Flash object should overlay. This will put the global
* Flash object on top of the current element; depending on the setup, this may also set the
* pending clipboard text data as well as the Flash object's wrapping element's title attribute
* based on the underlying HTML element and ZeroClipboard configuration.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.focus = ZeroClipboard.activate = function() {
return _focus.apply(this, _args(arguments));
};
/**
* Un-overlays the Flash object. This will put the global Flash object off-screen; depending on
* the setup, this may also unset the Flash object's wrapping element's title attribute based on
* the underlying HTML element and ZeroClipboard configuration.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.blur = ZeroClipboard.deactivate = function() {
return _blur.apply(this, _args(arguments));
};
/**
* Returns the currently focused/"activated" HTML element that the Flash object is wrapping.
*
* @returns `HTMLElement` or `null`
* @static
*/
ZeroClipboard.activeElement = function() {
return _activeElement.apply(this, _args(arguments));
};
if (typeof define === "function" && define.amd) {
define(function() {
return ZeroClipboard;
});
} else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) {
module.exports = ZeroClipboard;
} else {
window.ZeroClipboard = ZeroClipboard;
}
})(function() {
return this || window;
}()); |
lib/components/term.js | AlmirKadric/hyperterm | /* global Blob,URL,requestAnimationFrame */
import React from 'react';
import Color from 'color';
import uuid from 'uuid';
import hterm from '../hterm';
import Component from '../component';
import getColorList from '../utils/colors';
import notify from '../utils/notify';
export default class Term extends Component {
constructor(props) {
super(props);
this.handleWheel = this.handleWheel.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleScrollEnter = this.handleScrollEnter.bind(this);
this.handleScrollLeave = this.handleScrollLeave.bind(this);
this.onHyperCaret = this.onHyperCaret.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleFocus = this.handleFocus.bind(this);
props.ref_(this);
}
componentDidMount() {
const {props} = this;
this.term = props.term || new hterm.Terminal(uuid.v4());
this.term.onHyperCaret(this.hyperCaret);
// the first term that's created has unknown size
// subsequent new tabs have size
if (props.cols && props.rows) {
this.term.realizeSize_(props.cols, props.rows);
}
const prefs = this.term.getPrefs();
prefs.set('font-family', props.fontFamily);
prefs.set('font-size', props.fontSize);
prefs.set('font-smoothing', props.fontSmoothing);
prefs.set('cursor-color', this.validateColor(props.cursorColor, 'rgba(255,255,255,0.5)'));
prefs.set('enable-clipboard-notice', false);
prefs.set('foreground-color', props.foregroundColor);
// hterm.ScrollPort.prototype.setBackgroundColor is overriden
// to make hterm's background transparent. we still need to set
// background-color for proper text rendering
prefs.set('background-color', props.backgroundColor);
prefs.set('color-palette-overrides', getColorList(props.colors));
prefs.set('user-css', this.getStylesheet(props.customCSS));
prefs.set('scrollbar-visible', false);
prefs.set('receive-encoding', 'raw');
prefs.set('send-encoding', 'raw');
prefs.set('alt-sends-what', 'browser-key');
if (props.bell === 'SOUND') {
prefs.set('audible-bell-sound', this.props.bellSoundURL);
} else {
prefs.set('audible-bell-sound', '');
}
if (props.copyOnSelect) {
prefs.set('copy-on-select', true);
} else {
prefs.set('copy-on-select', false);
}
this.term.onTerminalReady = () => {
const io = this.term.io.push();
io.onVTKeystroke = io.sendString = props.onData;
io.onTerminalResize = (cols, rows) => {
if (cols !== this.props.cols || rows !== this.props.rows) {
props.onResize(cols, rows);
}
};
this.term.modifierKeys = props.modifierKeys;
// this.term.CursorNode_ is available at this point.
this.term.setCursorShape(props.cursorShape);
// emit onTitle event when hterm instance
// wants to set the title of its tab
this.term.setWindowTitle = props.onTitle;
this.term.focusHyperCaret();
};
this.term.decorate(this.termRef);
this.term.installKeyboard();
if (this.props.onTerminal) {
this.props.onTerminal(this.term);
}
const iframeWindow = this.getTermDocument().defaultView;
iframeWindow.addEventListener('wheel', this.handleWheel);
this.getScreenNode().addEventListener('mouseup', this.handleMouseUp);
}
handleWheel(e) {
if (this.props.onWheel) {
this.props.onWheel(e);
}
const prefs = this.term.getPrefs();
prefs.set('scrollbar-visible', true);
clearTimeout(this.scrollbarsHideTimer);
if (!this.scrollMouseEnter) {
this.scrollbarsHideTimer = setTimeout(() => {
prefs.set('scrollbar-visible', false);
}, 1000);
}
}
handleScrollEnter() {
clearTimeout(this.scrollbarsHideTimer);
const prefs = this.term.getPrefs();
prefs.set('scrollbar-visible', true);
this.scrollMouseEnter = true;
}
handleScrollLeave() {
const prefs = this.term.getPrefs();
prefs.set('scrollbar-visible', false);
this.scrollMouseEnter = false;
}
handleMouseUp() {
this.props.onActive();
// this makes sure that we focus the hyper caret only
// if a click on the term does not result in a selection
// otherwise, if we focus without such check, it'd be
// impossible to select a piece of text
if (this.term.document_.getSelection().type !== 'Range') {
this.term.focusHyperCaret();
}
}
handleFocus() {
// This will in turn result in `this.focus()` being
// called, which is unecessary.
// Should investigate if it matters.
this.props.onActive();
}
handleKeyDown(e) {
if (e.ctrlKey && e.key === 'c') {
this.props.onURLAbort();
}
}
onHyperCaret(caret) {
this.hyperCaret = caret;
}
write(data) {
// sometimes the preference set above for
// `receive-encoding` is not known by the vt
// before we type to write (since the preference
// manager is asynchronous), so we force it to
// avoid buffering
// this fixes a race condition where sometimes
// opening new sessions results in broken
// output due to the term attempting to decode
// as `utf-8` instead of `raw`
if (this.term.vt.characterEncoding !== 'raw') {
this.term.vt.characterEncoding = 'raw';
}
this.term.io.writeUTF8(data);
}
focus() {
this.term.focusHyperCaret();
}
clear() {
this.term.clearPreserveCursorRow();
// If cursor is still not at the top, a command is probably
// running and we'd like to delete the whole screen.
// Move cursor to top
if (this.term.getCursorRow() !== 0) {
this.write('\x1B[0;0H\x1B[2J');
}
}
moveWordLeft() {
this.term.onVTKeystroke('\x1bb');
}
moveWordRight() {
this.term.onVTKeystroke('\x1bf');
}
deleteWordLeft() {
this.term.onVTKeystroke('\x1b\x7f');
}
deleteWordRight() {
this.term.onVTKeystroke('\x1bd');
}
deleteLine() {
this.term.onVTKeystroke('\x1bw');
}
moveToStart() {
this.term.onVTKeystroke('\x01');
}
moveToEnd() {
this.term.onVTKeystroke('\x05');
}
selectAll() {
this.term.selectAll();
}
getScreenNode() {
return this.term.scrollPort_.getScreenNode();
}
getTermDocument() {
return this.term.document_;
}
getStylesheet(css) {
const hyperCaret = `
.hyper-caret {
outline: none;
display: inline-block;
color: transparent;
text-shadow: 0 0 0 black;
font-family: ${this.props.fontFamily};
font-size: ${this.props.fontSize}px;
}
`;
let osSpecificCss = '';
if (process.platform === 'win32') {
osSpecificCss = `::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
background: ${this.props.borderColor};
}
::-webkit-scrollbar-thumb:window-inactive {
background: ${this.props.borderColor};
}`;
} else if (process.platform === 'darwin') {
osSpecificCss = `::-webkit-scrollbar {
width: 9px;
background: transparent;
}
::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: inset 0 0 0 1px ${this.props.borderColor};
}`;
}
return URL.createObjectURL(new Blob([`
.cursor-node[focus="false"] {
border-width: 1px !important;
}
.cursor-node[focus="true"] {
border-left-width: 1px;
border-bottom-width: 2px;
}
${hyperCaret}
${osSpecificCss}
${css}
`], {type: 'text/css'}));
}
validateColor(color, alternative = 'rgb(255,255,255)') {
try {
return Color(color).rgbString();
} catch (err) {
notify(`color "${color}" is invalid`);
}
return alternative;
}
handleMouseDown(ev) {
// we prevent losing focus when clicking the boundary
// wrappers of the main terminal element
if (ev.target === this.termWrapperRef ||
ev.target === this.termRef) {
ev.preventDefault();
}
}
componentWillReceiveProps(nextProps) {
if (this.props.url !== nextProps.url) {
// when the url prop changes, we make sure
// the terminal starts or stops ignoring
// key input so that it doesn't conflict
// with the <webview>
if (nextProps.url) {
this.term.io.push();
window.addEventListener('keydown', this.handleKeyDown);
} else {
window.removeEventListener('keydown', this.handleKeyDown);
this.term.io.pop();
}
}
if (!this.props.cleared && nextProps.cleared) {
this.clear();
}
const prefs = this.term.getPrefs();
if (this.props.fontSize !== nextProps.fontSize) {
prefs.set('font-size', nextProps.fontSize);
this.hyperCaret.style.fontSize = nextProps.fontSize + 'px';
}
if (this.props.foregroundColor !== nextProps.foregroundColor) {
prefs.set('foreground-color', nextProps.foregroundColor);
}
if (this.props.fontFamily !== nextProps.fontFamily) {
prefs.set('font-family', nextProps.fontFamily);
this.hyperCaret.style.fontFamily = nextProps.fontFamily;
}
if (this.props.fontSmoothing !== nextProps.fontSmoothing) {
prefs.set('font-smoothing', nextProps.fontSmoothing);
}
if (this.props.cursorColor !== nextProps.cursorColor) {
prefs.set('cursor-color', this.validateColor(nextProps.cursorColor, 'rgba(255,255,255,0.5)'));
}
if (this.props.cursorShape !== nextProps.cursorShape) {
this.term.setCursorShape(nextProps.cursorShape);
}
if (this.props.colors !== nextProps.colors) {
prefs.set('color-palette-overrides', getColorList(nextProps.colors));
}
if (this.props.customCSS !== nextProps.customCSS) {
prefs.set('user-css', this.getStylesheet(nextProps.customCSS));
}
if (this.props.bell === 'SOUND') {
prefs.set('audible-bell-sound', this.props.bellSoundURL);
} else {
prefs.set('audible-bell-sound', '');
}
if (this.props.copyOnSelect) {
prefs.set('copy-on-select', true);
} else {
prefs.set('copy-on-select', false);
}
}
componentWillUnmount() {
clearTimeout(this.scrollbarsHideTimer);
this.props.ref_(null);
}
template(css) {
return (<div
ref={component => {
this.termWrapperRef = component;
}}
className={css('fit', this.props.isTermActive && 'active')}
onMouseDown={this.handleMouseDown}
style={{padding: this.props.padding}}
>
{ this.props.customChildrenBefore }
<div
ref={component => {
this.termRef = component;
}}
className={css('fit', 'term')}
/>
{ this.props.url ?
<webview
key="hyper-webview"
src={this.props.url}
onFocus={this.handleFocus}
style={{
background: '#fff',
position: 'absolute',
top: 0,
left: 0,
display: 'inline-flex',
width: '100%',
height: '100%'
}}
/> :
<div // eslint-disable-line react/jsx-indent
key="scrollbar"
className={css('scrollbarShim')}
onMouseEnter={this.handleScrollEnter}
onMouseLeave={this.handleScrollLeave}
/>
}
<div key="hyper-caret" contentEditable className="hyper-caret" ref={this.onHyperCaret}/>
{ this.props.customChildren }
</div>);
}
styles() {
return {
fit: {
display: 'block',
width: '100%',
height: '100%'
},
term: {
position: 'relative'
},
scrollbarShim: {
position: 'fixed',
right: 0,
width: '50px',
top: 0,
bottom: 0,
pointerEvents: 'none'
}
};
}
}
|
ajax/libs/primereact/6.3.2/components/skeleton/Skeleton.min.js | cdnjs/cdnjs | "use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.Skeleton=void 0;var _react=_interopRequireWildcard(require("react")),_propTypes=_interopRequireDefault(require("prop-types")),_ClassNames=require("../utils/ClassNames");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return _getRequireWildcardCache=function(){return e},e}function _interopRequireWildcard(e){if(e&&e.__esModule)return e;if(null===e||"object"!==_typeof(e)&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache();if(t&&t.has(e))return t.get(e);var r,o,n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&((o=i?Object.getOwnPropertyDescriptor(e,r):null)&&(o.get||o.set)?Object.defineProperty(n,r,o):n[r]=e[r]);return n.default=e,t&&t.set(e,n),n}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _createSuper(r){var o=_isNativeReflectConstruct();return function(){var e,t=_getPrototypeOf(r);return _possibleConstructorReturn(this,o?(e=_getPrototypeOf(this).constructor,Reflect.construct(t,arguments,e)):t.apply(this,arguments))}}function _possibleConstructorReturn(e,t){return!t||"object"!==_typeof(t)&&"function"!=typeof t?_assertThisInitialized(e):t}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var Skeleton=function(){_inherits(t,_react.Component);var e=_createSuper(t);function t(){return _classCallCheck(this,t),e.apply(this,arguments)}return _createClass(t,[{key:"skeletonStyle",value:function(){return this.props.size?{width:this.props.size,height:this.props.size,borderRadius:this.props.borderRadius}:{width:this.props.width,height:this.props.height,borderRadius:this.props.borderRadius}}},{key:"render",value:function(){var e=(0,_ClassNames.classNames)("p-skeleton p-component",{"p-skeleton-circle":"circle"===this.props.shape,"p-skeleton-none":"none"===this.props.animation},this.props.className),t=this.skeletonStyle();return _react.default.createElement("div",{style:t,className:e})}}]),t}();_defineProperty(exports.Skeleton=Skeleton,"defaultProps",{shape:"rectangle",size:null,width:"100%",height:"1rem",borderRadius:null,animation:"wave",style:null,className:null}),_defineProperty(Skeleton,"propTypes",{shape:_propTypes.default.string,size:_propTypes.default.string,width:_propTypes.default.string,height:_propTypes.default.string,borderRadius:_propTypes.default.string,animation:_propTypes.default.string,style:_propTypes.default.object,className:_propTypes.default.string}); |
packages/cf-component-card/test/CardToolbar.js | mdno/mdno.github.io | import React from 'react';
import renderer from 'react-test-renderer';
import CardToolbar from '../src/CardToolbar';
test('should render', () => {
const component = renderer.create(
<CardToolbar controls={'Controls'} links={'Links'} />
);
expect(component.toJSON()).toMatchSnapshot();
});
|
fixtures/packaging/systemjs-builder/dev/input.js | joecritch/react | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
|
jenkins-design-language/src/js/components/material-ui/svg-icons/device/signal-wifi-off.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const DeviceSignalWifiOff = (props) => (
<SvgIcon {...props}>
<path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z"/>
</SvgIcon>
);
DeviceSignalWifiOff.displayName = 'DeviceSignalWifiOff';
DeviceSignalWifiOff.muiName = 'SvgIcon';
export default DeviceSignalWifiOff;
|
app/components/Toggle/index.js | abasalilov/react-boilerplate | /**
*
* LocaleToggle
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: PropTypes.func,
values: PropTypes.array,
value: PropTypes.string,
messages: PropTypes.object,
};
export default Toggle;
|
src/HstWbInstaller.Imager.GuiApp/ClientApp/src/components/Content.js | henrikstengaard/hstwb-installer | import React from 'react';
import Box from '@mui/material/Box';
import {Route} from 'react-router';
import Start from "../pages/Start";
import Read from "../pages/Read";
import Write from "../pages/Write";
import Info from "../pages/Info";
import Convert from "../pages/Convert";
import Verify from "../pages/Verify";
import Blank from "../pages/Blank";
import Optimize from "../pages/Optimize";
import Partition from "../pages/Partition";
import About from "../pages/About";
import Settings from "../pages/Settings";
export default function Content() {
return (
<Box component="main" sx={{flexGrow: 1, marginTop: '32px', p: 3}}>
<Route exact path='/' component={Start}/>
<Route path='/read' component={Read}/>
<Route path='/write' component={Write}/>
<Route path='/info' component={Info}/>
<Route path='/convert' component={Convert}/>
<Route path='/verify' component={Verify}/>
<Route path='/blank' component={Blank}/>
<Route path='/optimize' component={Optimize}/>
<Route path='/partition' component={Partition}/>
<Route path='/settings' component={Settings}/>
<Route path='/about' component={About}/>
</Box>
)
} |
src/icons/_3dRotationIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class _3dRotationIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M15.03 42.97C8.5 39.87 3.81 33.52 3.1 26h-3C1.12 38.32 11.42 48 24 48c.45 0 .88-.04 1.32-.07L17.7 40.3l-2.67 2.67zm1.78-13.05c-.38 0-.73-.05-1.05-.17-.31-.11-.58-.27-.8-.47-.22-.2-.39-.45-.51-.73-.12-.29-.18-.6-.18-.94h-2.6c0 .72.14 1.35.42 1.9.28.55.65 1.01 1.12 1.37.47.37 1.01.64 1.63.83.62.2 1.26.29 1.94.29.74 0 1.43-.1 2.07-.3.64-.2 1.19-.5 1.66-.89s.83-.87 1.1-1.44c.26-.57.4-1.22.4-1.95 0-.39-.05-.76-.14-1.12-.1-.36-.25-.7-.45-1.02-.21-.32-.48-.6-.81-.86-.33-.25-.74-.46-1.21-.63.4-.18.75-.4 1.05-.66.3-.26.55-.54.75-.83.2-.3.35-.6.45-.92.1-.32.15-.64.15-.95 0-.73-.12-1.37-.36-1.92-.24-.55-.58-1.01-1.02-1.38-.44-.37-.96-.65-1.58-.84-.64-.2-1.32-.29-2.06-.29-.72 0-1.39.11-2 .32-.61.21-1.13.51-1.57.89-.44.38-.78.83-1.03 1.35-.25.52-.37 1.09-.37 1.7h2.6c0-.34.06-.64.18-.9.12-.27.29-.5.5-.68.21-.19.47-.34.76-.44.29-.1.61-.16.95-.16.8 0 1.39.21 1.78.62.39.41.58.99.58 1.73 0 .36-.05.68-.16.97-.11.29-.27.54-.49.75-.22.21-.5.37-.82.49-.33.12-.72.18-1.16.18h-1.54v2.05h1.54c.44 0 .84.05 1.19.15.35.1.65.25.9.47.25.21.44.48.58.8.13.32.2.7.2 1.14 0 .81-.23 1.43-.7 1.86-.45.42-1.08.63-1.89.63zm17.12-11.85c-.63-.66-1.39-1.17-2.27-1.53-.89-.36-1.86-.54-2.93-.54H24v16h4.59c1.11 0 2.11-.18 3.02-.54.91-.36 1.68-.87 2.32-1.53.64-.66 1.14-1.46 1.48-2.39.35-.93.52-1.98.52-3.14v-.79c0-1.16-.18-2.2-.53-3.14-.35-.94-.84-1.74-1.47-2.4zm-.79 6.34c0 .83-.09 1.59-.29 2.25-.19.67-.47 1.23-.85 1.69-.38.46-.85.81-1.42 1.06-.57.24-1.23.37-1.99.37h-1.81V18.24h1.95c1.44 0 2.53.46 3.29 1.37.75.92 1.13 2.24 1.13 3.98v.82zM24 0c-.45 0-.88.04-1.32.07L30.3 7.7l2.66-2.66C39.5 8.13 44.19 14.48 44.9 22h3C46.88 9.68 36.58 0 24 0z"/></svg>;}
}; |
docs/src/layouts/wrapper.js | balloob/nuclear-js | import React from 'react'
import { BASE_URL } from '../globals'
const PRISM_PATH = BASE_URL + 'assets/js/prism.js'
const CSS_PATH = BASE_URL + 'assets/css/output.css'
const JS_PATH = BASE_URL + 'app.js'
const GA_SCRIPT = `(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-64060472-1', 'auto');
ga('send', 'pageview');`
export default React.createClass({
render() {
let pageTitle = "NuclearJS"
if (this.props.title) {
pageTitle += " | " + this.props.title
}
return (
<html lang="en">
<head>
<meta httpEquiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
<title>{pageTitle}</title>
<link href={CSS_PATH} type="text/css" rel="stylesheet" media="screen,projection"/>
<script src="//cdn.optimizely.com/js/3006700484.js"></script>
<script dangerouslySetInnerHTML={{__html: GA_SCRIPT}}></script>
</head>
<body>
{this.props.children}
<script src={PRISM_PATH}></script>
<script src={JS_PATH}></script>
</body>
</html>
)
}
})
|
src/Grid/__tests__/Grid-test.js | tleunen/react-mdl | /* eslint-env mocha */
import chai, { expect } from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow } from 'enzyme';
import React from 'react';
import Grid from '../Grid';
chai.use(chaiEnzyme());
describe('Grid', () => {
it('should render a MDL grid <div>', () => {
const wrapper = shallow(<Grid />);
expect(wrapper)
.to.have.tagName('div')
.to.have.className('mdl-grid');
});
it('should allow custom css class', () => {
const wrapper = shallow(<Grid className="my-grid" />);
expect(wrapper)
.to.have.className('mdl-grid')
.to.have.className('my-grid');
});
it('should allow a custom component', () => {
const wrapper = shallow(<Grid component="section" />);
expect(wrapper).to.have.tagName('section');
});
it('should allow a complex custom component', () => {
const Comp = (p) => <article {...p} />;
const wrapper = shallow(<Grid component={Comp} />);
expect(wrapper.find(Comp)).to.have.length(1);
});
});
|
src/svg-icons/file/cloud-download.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudDownload = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z"/>
</SvgIcon>
);
FileCloudDownload = pure(FileCloudDownload);
FileCloudDownload.displayName = 'FileCloudDownload';
export default FileCloudDownload;
|
docs/src/app/components/pages/components/Table/ExampleComplex.js | kittyjumbalaya/material-components-web | import React, {Component} from 'react';
import {
Table,
TableBody,
TableFooter,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';
const styles = {
propContainer: {
width: 200,
overflow: 'hidden',
margin: '20px auto 0',
},
propToggleHeader: {
margin: '20px auto 10px',
},
};
const tableData = [
{
name: 'John Smith',
status: 'Employed',
},
{
name: 'Randal White',
status: 'Unemployed',
},
{
name: 'Stephanie Sanders',
status: 'Employed',
},
{
name: 'Steve Brown',
status: 'Employed',
},
{
name: 'Joyce Whitten',
status: 'Employed',
},
{
name: 'Samuel Roberts',
status: 'Employed',
},
{
name: 'Adam Moore',
status: 'Employed',
},
];
/**
* A more complex example, allowing the table height to be set, and key boolean properties to be toggled.
*/
export default class TableExampleComplex extends Component {
state = {
fixedHeader: true,
fixedFooter: true,
stripedRows: false,
showRowHover: false,
selectable: true,
multiSelectable: false,
enableSelectAll: false,
deselectOnClickaway: true,
showCheckboxes: true,
height: '300px',
};
handleToggle = (event, toggled) => {
this.setState({
[event.target.name]: toggled,
});
};
handleChange = (event) => {
this.setState({height: event.target.value});
};
render() {
return (
<div>
<Table
height={this.state.height}
fixedHeader={this.state.fixedHeader}
fixedFooter={this.state.fixedFooter}
selectable={this.state.selectable}
multiSelectable={this.state.multiSelectable}
>
<TableHeader
displaySelectAll={this.state.showCheckboxes}
adjustForCheckbox={this.state.showCheckboxes}
enableSelectAll={this.state.enableSelectAll}
>
<TableRow>
<TableHeaderColumn colSpan="3" tooltip="Super Header" style={{textAlign: 'center'}}>
Super Header
</TableHeaderColumn>
</TableRow>
<TableRow>
<TableHeaderColumn tooltip="The ID">ID</TableHeaderColumn>
<TableHeaderColumn tooltip="The Name">Name</TableHeaderColumn>
<TableHeaderColumn tooltip="The Status">Status</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={this.state.showCheckboxes}
deselectOnClickaway={this.state.deselectOnClickaway}
showRowHover={this.state.showRowHover}
stripedRows={this.state.stripedRows}
>
{tableData.map( (row, index) => (
<TableRow key={index}>
<TableRowColumn>{index}</TableRowColumn>
<TableRowColumn>{row.name}</TableRowColumn>
<TableRowColumn>{row.status}</TableRowColumn>
</TableRow>
))}
</TableBody>
<TableFooter
adjustForCheckbox={this.state.showCheckboxes}
>
<TableRow>
<TableRowColumn>ID</TableRowColumn>
<TableRowColumn>Name</TableRowColumn>
<TableRowColumn>Status</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn colSpan="3" style={{textAlign: 'center'}}>
Super Footer
</TableRowColumn>
</TableRow>
</TableFooter>
</Table>
<div style={styles.propContainer}>
<h3>Table Properties</h3>
<TextField
floatingLabelText="Table Body Height"
defaultValue={this.state.height}
onChange={this.handleChange}
/>
<Toggle
name="fixedHeader"
label="Fixed Header"
onToggle={this.handleToggle}
defaultToggled={this.state.fixedHeader}
/>
<Toggle
name="fixedFooter"
label="Fixed Footer"
onToggle={this.handleToggle}
defaultToggled={this.state.fixedFooter}
/>
<Toggle
name="selectable"
label="Selectable"
onToggle={this.handleToggle}
defaultToggled={this.state.selectable}
/>
<Toggle
name="multiSelectable"
label="Multi-Selectable"
onToggle={this.handleToggle}
defaultToggled={this.state.multiSelectable}
/>
<Toggle
name="enableSelectAll"
label="Enable Select All"
onToggle={this.handleToggle}
defaultToggled={this.state.enableSelectAll}
/>
<h3 style={styles.propToggleHeader}>TableBody Properties</h3>
<Toggle
name="deselectOnClickaway"
label="Deselect On Clickaway"
onToggle={this.handleToggle}
defaultToggled={this.state.deselectOnClickaway}
/>
<Toggle
name="stripedRows"
label="Stripe Rows"
onToggle={this.handleToggle}
defaultToggled={this.state.stripedRows}
/>
<Toggle
name="showRowHover"
label="Show Row Hover"
onToggle={this.handleToggle}
defaultToggled={this.state.showRowHover}
/>
<h3 style={styles.propToggleHeader}>Multiple Properties</h3>
<Toggle
name="showCheckboxes"
label="Show Checkboxes"
onToggle={this.handleToggle}
defaultToggled={this.state.showCheckboxes}
/>
</div>
</div>
);
}
}
|
tests/layouts/CoreLayout.spec.js | davecarlson/reacty | import React from 'react'
import TestUtils from 'react-addons-test-utils'
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<CoreLayout {...props} />)
}
describe('(Layout) Core', function () {
let _component
let _props
let _child
beforeEach(function () {
_child = <h1 className='child'>Child</h1>
_props = {
children: _child
}
_component = shallowRenderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
})
|
packager/src/ModuleGraph/types.flow.js | htc2u/react-native | /**
* Copyright (c) 2016-present, 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.
*
* @flow
*/
'use strict';
import type {SourceMap} from './output/source-map';
import type {Ast} from 'babel-core';
import type {Console} from 'console';
export type Callback<A = void, B = void>
= (Error => void)
& ((null | void, A, B) => void);
type Dependency = {|
id: string,
path: string,
|};
export type File = {|
code: string,
map?: ?Object,
path: string,
type: FileTypes,
|};
type FileTypes = 'module' | 'script';
export type GraphFn = (
entryPoints: Iterable<string>,
platform: string,
options?: ?GraphOptions,
callback?: Callback<GraphResult>,
) => void;
type GraphOptions = {|
cwd?: string,
log?: Console,
optimize?: boolean,
skip?: Set<string>,
|};
export type GraphResult = {
entryModules: Array<Module>,
modules: Array<Module>,
};
export type IdForPathFn = {path: string} => number;
export type LoadFn = (
file: string,
options: LoadOptions,
callback: Callback<File, Array<string>>,
) => void;
type LoadOptions = {|
log?: Console,
optimize?: boolean,
platform?: string,
|};
export type Module = {|
dependencies: Array<Dependency>,
file: File,
|};
export type OutputFn = (
modules: Iterable<Module>,
filename?: string,
idForPath: IdForPathFn,
) => OutputResult;
type OutputResult = {
code: string,
map: SourceMap,
};
export type PackageData = {|
browser?: Object | string,
main?: string,
name?: string,
'react-native'?: Object | string,
|};
export type ResolveFn = (
id: string,
source: string,
platform: string,
options?: ResolveOptions,
callback: Callback<string>,
) => void;
type ResolveOptions = {
log?: Console,
};
export type TransformerResult = {
ast: ?Ast,
code: string,
map: ?SourceMap,
};
export type Transformer = {
transform: (
sourceCode: string,
filename: string,
options: ?{},
plugins?: Array<string | Object | [string | Object, any]>,
) => {ast: ?Ast, code: string, map: ?SourceMap}
};
export type TransformResult = {|
code: string,
dependencies: Array<string>,
dependencyMapName?: string,
map: ?Object,
|};
export type TransformResults = {[string]: TransformResult};
export type TransformVariants = {[key: string]: Object};
export type TransformedFile = {
code: string,
file: string,
hasteID: ?string,
package?: PackageData,
transformed: TransformResults,
type: FileTypes,
};
|
packages/react-ui-core/src/Gmap/GmapSpinner.js | rentpath/react-ui | import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import themed from '@rentpath/react-themed'
import clsx from 'clsx'
import BounceLoader from './spinners/BounceLoader'
@themed(['Gmap_Spinner'], { pure: true })
export default class GmapSpinner extends PureComponent {
static propTypes = {
loading: PropTypes.bool,
theme: PropTypes.object,
className: PropTypes.string,
closeDelay: PropTypes.number,
color: PropTypes.string,
}
static defaultProps = {
closeDelay: 0,
loading: false,
theme: {},
color: '#000',
}
constructor(props) {
super(props)
this.state = {
loading: this.props.loading,
}
this.closeTimer = null
}
componentDidUpdate(nextProps) {
if (this.props.loading !== nextProps.loading && nextProps.loading) {
this.close()
}
}
componentWillUnmount() {
window.clearTimeout(this.closeTimer)
}
close() {
const { closeDelay } = this.props
// add timeout so the gray background isn't the only thing we see
this.closeTimer = window.setTimeout(() => {
this.setState({ loading: false })
}, closeDelay)
}
render() {
const { loading } = this.state
const {
theme,
className,
closeDelay,
...rest
} = this.props
return (
<div className={clsx(
className,
theme.Gmap_Spinner,
)}
>
<BounceLoader {...rest} loading={loading} />
</div>
)
}
}
|
src/components/Tagline/Tagline.js | kdrabek/exchange_rates_frontend | import React from 'react';
import { Row, Col, PageHeader } from 'react-bootstrap';
const Tagline = (props) => {
return (
<Row>
<Col xs={12} md={12}>
<PageHeader>
Kursy walut NBP <br /><small>Według tabeli A</small>
</PageHeader>
</Col>
</Row>
);
};
export default Tagline;
|
src/components/Markup.js | NuCivic/react-dashboard | import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';
import Card from './Card';
import { isArray } from 'lodash';
export default class Markup extends BaseComponent {
getContent() {
if (this.props.data && isArray(this.props.data) && this.props.data.length > 0) {
return this.props.data[0];
};
if (this.props.data && !isArray(this.props.data)) {
return this.props.data;
};
if (this.props.content) {
return this.props.content;
}
return '';
}
render() {
return (
<Card {...this.state.cardVariables}>
<div dangerouslySetInnerHTML={ {__html: this.getContent()}}></div>
</Card>
)
}
}
Registry.set('Markup', Markup);
|
ajax/libs/yui/3.18.0/datatable-body/datatable-body-debug.js | manorius/cdnjs | YUI.add('datatable-body', function (Y, NAME) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object,
valueRegExp = /\{value\}/g,
EV_CONTENT_UPDATE = 'contentUpdate',
shiftMap = {
above: [-1, 0],
below: [1, 0],
next: [0, 1],
prev: [0, -1],
previous: [0, -1]
};
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or amended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
A column `formatter` can be:
* a function, as described below.
* a string which can be:
* the name of a pre-defined formatter function
which can be located in the `Y.DataTable.BodyView.Formatters` hash using the
value of the `formatter` property as the index.
* A template that can use the `{value}` placeholder to include the value
for the current cell or the name of any field in the underlaying model
also enclosed in curly braces. Any number and type of these placeholders
can be used.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {String}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {String}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `host` property of
the configuration object passed to the constructor.
@property host
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//host: null,
/**
HTML templates used to create the `<tbody>` containing the table rows.
@property TBODY_TEMPLATE
@type {String}
@default '<tbody class="{className}">{content}</tbody>'
@since 3.6.0
**/
TBODY_TEMPLATE: '<tbody class="{className}"></tbody>',
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.target, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.tbodyNode,
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (seed._node) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
if (!shiftMap[shift]) {
Y.error('Unrecognized shift: ' + shift, null, 'datatable-body');
}
shift = shiftMap[shift];
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Returns the generated CSS classname based on the input. If the `host`
attribute is configured, it will attempt to relay to its `getClassName`
or use its static `NAME` property as a string base.
If `host` is absent or has neither method nor `NAME`, a CSS classname
will be generated using this class's `NAME`.
@method getClassName
@param {String} token* Any number of token strings to assemble the
classname from.
@return {String}
@protected
@since 3.5.0
**/
getClassName: function () {
var host = this.host,
args;
if (host && host.getClassName) {
return host.getClassName.apply(host, arguments);
} else {
args = toArray(arguments);
args.unshift(this.constructor.NAME);
return Y.ClassNameManager.getClassName
.apply(Y.ClassNameManager, args);
}
},
/**
Returns the Model associated to the row Node or id provided. Passing the
Node or id for a descendant of the row also works.
If no Model can be found, `null` is returned.
@method getRecord
@param {String|Node} seed Row Node or `id`, or one for a descendant of a row
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.tbodyNode,
row = null,
record;
if (tbody) {
if (isString(seed)) {
seed = tbody.one('#' + seed);
}
if (seed && seed._node) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.tbodyNode,
row = null;
if (tbody) {
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
row = isNumber(id) ?
tbody.get('children').item(id) :
tbody.one('#' + id);
}
return row;
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` and `modelList` attributes.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` attribute (see
`_createRowTemplate`)
2. An HTML string is built up by concatenating the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@chainable
@since 3.5.0
**/
render: function () {
var table = this.get('container'),
data = this.get('modelList'),
displayCols = this.get('columns'),
tbody = this.tbodyNode ||
(this.tbodyNode = this._createTBodyNode());
// Needed for mutation
this._createRowTemplate(displayCols);
if (data) {
tbody.setHTML(this._createDataHTML(displayCols));
this._applyNodeFormatters(tbody, displayCols);
}
if (tbody.get('parentNode') !== table) {
table.appendChild(tbody);
}
this.bindUI();
return this;
},
/**
Refreshes the provided row against the provided model and the Array of
columns to be updated.
@method refreshRow
@param {Node} row
@param {Model} model Y.Model representation of the row
@param {String[]} colKeys Array of column keys
@chainable
*/
refreshRow: function (row, model, colKeys) {
var col,
cell,
len = colKeys.length,
i;
for (i = 0; i < len; i++) {
col = this.getColumn(colKeys[i]);
if (col !== null) {
cell = row.one('.' + this.getClassName('col', col._id || col.key));
this.refreshCell(cell, model);
}
}
return this;
},
/**
Refreshes the given cell with the provided model data and the provided
column configuration.
Uses the provided column formatter if aviable.
@method refreshCell
@param {Node} cell Y.Node pointer to the cell element to be updated
@param {Model} [model] Y.Model representation of the row
@param {Object} [col] Column configuration object for the cell
@chainable
*/
refreshCell: function (cell, model, col) {
var content,
formatterFn,
formatterData,
data = model.toJSON();
cell = this.getCell(cell);
/* jshint -W030 */
model || (model = this.getRecord(cell));
col || (col = this.getColumn(cell));
/* jshint +W030 */
if (col.nodeFormatter) {
formatterData = {
cell: cell.one('.' + this.getClassName('liner')) || cell,
column: col,
data: data,
record: model,
rowIndex: this._getRowIndex(cell.ancestor('tr')),
td: cell,
value: data[col.key]
};
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
} else if (col.formatter) {
if (!col._formatterFn) {
col = this._setColumnsFormatterFn([col])[0];
}
formatterFn = col._formatterFn || null;
if (formatterFn) {
formatterData = {
value : data[col.key],
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : this._getRowIndex(cell.ancestor('tr'))
};
// Formatters can either return a value ...
content = formatterFn.call(this.get('host'), formatterData);
// ... or update the value property of the data obj passed
if (content === undefined) {
content = formatterData.value;
}
}
if (content === undefined || content === null || content === '') {
content = col.emptyCellValue || '';
}
} else {
content = data[col.key] || col.emptyCellValue || '';
}
cell.setHTML(col.allowHTML ? content : Y.Escape.html(content));
return this;
},
/**
Returns column data from this.get('columns'). If a Y.Node is provided as
the key, will try to determine the key from the classname
@method getColumn
@param {String|Node} name
@return {Object} Returns column configuration
*/
getColumn: function (name) {
if (name && name._node) {
// get column name from node
name = name.get('className').match(
new RegExp( this.getClassName('col') +'-([^ ]*)' )
)[1];
}
if (this.host) {
return this.host._columnMap[name] || null;
}
var displayCols = this.get('columns'),
col = null;
Y.Array.some(displayCols, function (_col) {
if ((_col._id || _col.key) === name) {
col = _col;
return true;
}
});
return col;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function () {
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var type = (e.type.match(/:(add|change|remove)$/) || [])[1],
index = e.index,
displayCols = this.get('columns'),
col,
changed = e.changed && Y.Object.keys(e.changed),
key,
row,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++ ) {
col = displayCols[i];
// since nodeFormatters typcially make changes outside of it's
// cell, we need to see if there are any columns that have a
// nodeFormatter and if so, we need to do a full render() of the
// tbody
if (col.hasOwnProperty('nodeFormatter')) {
this.render();
this.fire(EV_CONTENT_UPDATE);
return;
}
}
// TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping?
switch (type) {
case 'change':
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
key = col.key;
if (col.formatter && !e.changed[key]) {
changed.push(key);
}
}
this.refreshRow(this.getRow(e.target), e.target, changed);
break;
case 'add':
// we need to make sure we don't have an index larger than the data we have
index = Math.min(index, this.get('modelList').size() - 1);
// updates the columns with formatter functions
this._setColumnsFormatterFn(displayCols);
row = Y.Node.create(this._createRowHTML(e.model, index, displayCols));
this.tbodyNode.insert(row, index);
this._restripe(index);
break;
case 'remove':
this.getRow(index).remove(true);
// we removed a row, so we need to back up our index to stripe
this._restripe(index - 1);
break;
default:
this.render();
}
// Event fired to tell users when we are done updating after the data
// was changed
this.fire(EV_CONTENT_UPDATE);
},
/**
Toggles the odd/even classname of the row after the given index. This method
is used to update rows after a row is inserted into or removed from the table.
Note this event is delayed so the table is only restriped once when multiple
rows are updated at one time.
@protected
@method _restripe
@param {Number} [index] Index of row to start restriping after
@since 3.11.0
*/
_restripe: function (index) {
var task = this._restripeTask,
self;
// index|0 to force int, avoid NaN. Math.max() to avoid neg indexes.
index = Math.max((index|0), 0);
if (!task) {
self = this;
this._restripeTask = {
timer: setTimeout(function () {
// Check for self existence before continuing
if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) {
self._restripeTask = null;
return;
}
var odd = [self.CLASS_ODD, self.CLASS_EVEN],
even = [self.CLASS_EVEN, self.CLASS_ODD],
index = self._restripeTask.index;
self.tbodyNode.get('childNodes')
.slice(index)
.each(function (row, i) { // TODO: each vs batch
row.replaceClass.apply(row, (index + i) % 2 ? even : odd);
});
self._restripeTask = null;
}, 0),
index: index
};
} else {
task.index = Math.min(task.index, index);
}
},
/**
Handles replacement of the modelList.
Rerenders the `<tbody>` contents.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.6.0
**/
_afterModelListChange: function () {
var handles = this._eventHandles;
if (handles.dataChange) {
handles.dataChange.detach();
delete handles.dataChange;
this.bindUI();
}
if (this.tbodyNode) {
this.render();
}
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} displayCols The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, displayCols) {
var host = this.host || this,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = displayCols.length; i < len; ++i) {
if (displayCols[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = displayCols[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the host (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles,
modelList = this.get('modelList'),
changeEvent = modelList.model.NAME + ':change';
if (!handles.columnsChange) {
handles.columnsChange = this.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (modelList && !handles.dataChange) {
handles.dataChange = modelList.after(
['add', 'remove', 'reset', changeEvent],
bind('_afterDataChange', this));
}
},
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} displayCols The column configurations to customize the
generated cell content or class names
@return {String} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (displayCols) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index, displayCols);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@param {Object[]} displayCols The column configurations
@return {String} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index, displayCols) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
host = this.host || this,
i, len, col, token, value, formatterData;
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
value = data[col.key];
token = col._id || col.key;
values[token + '-className'] = '';
if (col._formatterFn) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
// Formatters can either return a value
value = col._formatterFn.call(host, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
// if the token missing OR is the value a legit value
if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) {
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
}
}
// replace consecutive whitespace with a single space
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
return fromTemplate(this._rowTemplate, values);
},
/**
Locates the row within the tbodyNode and returns the found index, or Null
if it is not found in the tbodyNode
@param {Node} row
@return {Number} Index of row in tbodyNode
*/
_getRowIndex: function (row) {
var tbody = this.tbodyNode,
index = 1;
if (tbody && row) {
//if row is not in the tbody, return
if (row.ancestor('tbody') !== tbody) {
return null;
}
// increment until we no longer have a previous node
/*jshint boss: true*/
while (row = row.previous()) { // NOTE: assignment
/*jshint boss: false*/
index++;
}
}
return index;
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} displayCols Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (displayCols) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues, formatter;
this._setColumnsFormatterFn(displayCols);
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
key = col.key;
token = col._id || key;
formatter = col._formatterFn;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (!formatter && col.formatter) {
tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content);
}
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Parses the columns array and defines the column's _formatterFn if there
is a formatter available on the column
@protected
@method _setColumnsFormatterFn
@param {Object[]} displayCols Array of column configuration objects
@return {Object[]} Returns modified displayCols configuration Array
*/
_setColumnsFormatterFn: function (displayCols) {
var Formatters = Y.DataTable.BodyView.Formatters,
formatter,
col,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
formatter = col.formatter;
if (!col._formatterFn && formatter) {
if (Lang.isFunction(formatter)) {
col._formatterFn = formatter;
} else if (formatter in Formatters) {
col._formatterFn = Formatters[formatter].call(this.host || this, col);
}
}
}
return displayCols;
},
/**
Creates the `<tbody>` node that will store the data rows.
@method _createTBodyNode
@return {Node}
@protected
@since 3.6.0
**/
_createTBodyNode: function () {
return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {
className: this.getClassName('data')
}));
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `host` - The object to serve as source of truth for column info and
for generating class names
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
this.host = config.host;
this._eventHandles = {
modelListChange: this.after('modelListChange',
bind('_afterModelListChange', this))
};
this._idMap = {};
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {String}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
},{
/**
Hash of formatting functions for cell contents.
This property can be populated with a hash of formatting functions by the developer
or a set of pre-defined functions can be loaded via the `datatable-formatters` module.
See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html)
@property Formatters
@type Object
@since 3.8.0
@static
**/
Formatters: {}
});
}, '3.18.0', {"requires": ["datatable-core", "view", "classnamemanager"]});
|
ajax/libs/clappr/0.0.62/clappr.js | jackdoyle/cdnjs | require=(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){
(function (global){
"use strict";
var Player = require('./components/player');
var IframePlayer = require('./components/iframe_player');
var Mediator = require('mediator');
var version = require('../package.json').version;
global.DEBUG = false;
window.Clappr = {
Player: Player,
Mediator: Mediator,
IframePlayer: IframePlayer
};
window.Clappr.version = version;
module.exports = window.Clappr;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":7,"./components/iframe_player":19,"./components/player":23,"mediator":"mediator"}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canMutationObserver = typeof window !== 'undefined'
&& window.MutationObserver;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
var queue = [];
if (canMutationObserver) {
var hiddenDiv = document.createElement("div");
var observer = new MutationObserver(function () {
var queueList = queue.slice();
queue.length = 0;
queueList.forEach(function (fn) {
fn();
});
});
observer.observe(hiddenDiv, { attributes: true });
return function nextTick(fn) {
if (!queue.length) {
hiddenDiv.setAttribute('yes', 'no');
}
queue.push(fn);
};
}
if (canPost) {
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
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');
};
},{}],3:[function(require,module,exports){
(function (process,global){
(function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function checkObjectCoercible(argument) {
if (argument == null) {
throw new TypeError('Value cannot be converted to an Object');
}
return argument;
}
function setupGlobals(global) {
global.Symbol = Symbol;
global.Reflect = global.Reflect || {};
global.Reflect.global = global.Reflect.global || global;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
isObject: isObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
checkObjectCoercible: checkObjectCoercible,
hasOwnProperty: function(o, p) {
return hasOwnProperty.call(o, p);
},
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
function spread() {
var rv = [],
j = 0,
iterResult;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]);
if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {
throw new TypeError('Cannot spread non-iterable object.');
}
var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();
while (!(iterResult = iter.next()).done) {
rv[j++] = iterResult.value;
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
throw new $TypeError('super prototype must be an Object or null');
}
if (superClass === null)
return null;
throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + "."));
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw x;
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime,
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) {
this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName;
if (!(cause instanceof $ModuleEvaluationError) && cause.stack)
this.stack = this.stripStack(cause.stack);
else
this.stack = '';
};
var $ModuleEvaluationError = ModuleEvaluationError;
($traceurRuntime.createClass)(ModuleEvaluationError, {
stripError: function(message) {
return message.replace(/.*Error:/, this.constructor.name + ':');
},
stripCause: function(cause) {
if (!cause)
return '';
if (!cause.message)
return cause + '';
return this.stripError(cause.message);
},
loadedBy: function(moduleName) {
this.stack += '\n loaded by ' + moduleName;
},
stripStack: function(causeStack) {
var stack = [];
causeStack.split('\n').some((function(frame) {
if (/UncoatedModuleInstantiator/.test(frame))
return true;
stack.push(frame);
}));
stack[0] = this.stripError(stack[0]);
return stack.join('\n');
}
}, {}, Error);
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
try {
return this.value_ = this.func.call(global);
} catch (ex) {
if (ex instanceof ModuleEvaluationError) {
ex.loadedBy(this.url);
throw ex;
}
throw new ModuleEvaluationError(this.url, ex);
}
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("[email protected]/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/utils";
var $ceil = Math.ceil;
var $floor = Math.floor;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $pow = Math.pow;
var $min = Math.min;
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x >>> 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function isNumber(x) {
return typeof x === 'number';
}
function toInteger(x) {
x = +x;
if ($isNaN(x))
return 0;
if (x === 0 || !$isFinite(x))
return x;
return x > 0 ? $floor(x) : $ceil(x);
}
var MAX_SAFE_LENGTH = $pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);
}
function checkIterable(x) {
return !isObject(x) ? undefined : x[Symbol.iterator];
}
function isConstructor(x) {
return isCallable(x);
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function maybeDefine(object, name, descr) {
if (!(name in object)) {
Object.defineProperty(object, name, descr);
}
}
function maybeDefineMethod(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
function maybeDefineConst(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: false,
enumerable: false,
writable: false
});
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function maybeAddConsts(object, consts) {
for (var i = 0; i < consts.length; i += 2) {
var name = consts[i];
var value = consts[i + 1];
maybeDefineConst(object, name, value);
}
}
function maybeAddIterator(object, func, Symbol) {
if (!Symbol || !Symbol.iterator || object[Symbol.iterator])
return;
if (object['@@iterator'])
func = object['@@iterator'];
Object.defineProperty(object, Symbol.iterator, {
value: func,
configurable: true,
enumerable: false,
writable: true
});
}
var polyfills = [];
function registerPolyfill(func) {
polyfills.push(func);
}
function polyfillAll(global) {
polyfills.forEach((function(f) {
return f(global);
}));
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get isNumber() {
return isNumber;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
},
get checkIterable() {
return checkIterable;
},
get isConstructor() {
return isConstructor;
},
get createIteratorResultObject() {
return createIteratorResultObject;
},
get maybeDefine() {
return maybeDefine;
},
get maybeDefineMethod() {
return maybeDefineMethod;
},
get maybeDefineConst() {
return maybeDefineConst;
},
get maybeAddFunctions() {
return maybeAddFunctions;
},
get maybeAddConsts() {
return maybeAddConsts;
},
get maybeAddIterator() {
return maybeAddIterator;
},
get registerPolyfill() {
return registerPolyfill;
},
get polyfillAll() {
return polyfillAll;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Map";
var $__3 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__3.isObject,
maybeAddIterator = $__3.maybeAddIterator,
registerPolyfill = $__3.registerPolyfill;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Map called on incompatible type');
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError('Map can not be reentrantly initialised');
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
for (var $__5 = iterable[Symbol.iterator](),
$__6; !($__6 = $__5.next()).done; ) {
var $__7 = $__6.value,
key = $__7[0],
value = $__7[1];
{
this.set(key, value);
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
return true;
}
return false;
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0; i < this.entries_.length; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
},
entries: $traceurRuntime.initGeneratorFunction(function $__8() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return [key, value];
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__8, this);
}),
keys: $traceurRuntime.initGeneratorFunction(function $__9() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return key;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__9, this);
}),
values: $traceurRuntime.initGeneratorFunction(function $__10() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return value;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__10, this);
})
}, {});
Object.defineProperty(Map.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Map.prototype.entries
});
function polyfillMap(global) {
var $__7 = global,
Object = $__7.Object,
Symbol = $__7.Symbol;
if (!global.Map)
global.Map = Map;
var mapPrototype = global.Map.prototype;
if (mapPrototype.entries) {
maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillMap);
return {
get Map() {
return Map;
},
get polyfillMap() {
return polyfillMap;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Map" + '');
System.register("[email protected]/src/runtime/polyfills/Set", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Set";
var $__11 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__11.isObject,
maybeAddIterator = $__11.maybeAddIterator,
registerPolyfill = $__11.registerPolyfill;
var Map = System.get("[email protected]/src/runtime/polyfills/Map").Map;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
function initSet(set) {
set.map_ = new Map();
}
var Set = function Set() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Set called on incompatible type');
if ($hasOwnProperty.call(this, 'map_')) {
throw new TypeError('Set can not be reentrantly initialised');
}
initSet(this);
if (iterable !== null && iterable !== undefined) {
for (var $__15 = iterable[Symbol.iterator](),
$__16; !($__16 = $__15.next()).done; ) {
var item = $__16.value;
{
this.add(item);
}
}
}
};
($traceurRuntime.createClass)(Set, {
get size() {
return this.map_.size;
},
has: function(key) {
return this.map_.has(key);
},
add: function(key) {
this.map_.set(key, key);
return this;
},
delete: function(key) {
return this.map_.delete(key);
},
clear: function() {
return this.map_.clear();
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
var $__13 = this;
return this.map_.forEach((function(value, key) {
callbackFn.call(thisArg, key, key, $__13);
}));
},
values: $traceurRuntime.initGeneratorFunction(function $__18() {
var $__19,
$__20;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__19 = this.map_.keys()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__20.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__20.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__20.value;
default:
return $ctx.end();
}
}, $__18, this);
}),
entries: $traceurRuntime.initGeneratorFunction(function $__21() {
var $__22,
$__23;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__22 = this.map_.entries()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__23.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__23.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__23.value;
default:
return $ctx.end();
}
}, $__21, this);
})
}, {});
Object.defineProperty(Set.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Set.prototype.values
});
Object.defineProperty(Set.prototype, 'keys', {
configurable: true,
writable: true,
value: Set.prototype.values
});
function polyfillSet(global) {
var $__17 = global,
Object = $__17.Object,
Symbol = $__17.Symbol;
if (!global.Set)
global.Set = Set;
var setPrototype = global.Set.prototype;
if (setPrototype.values) {
maybeAddIterator(setPrototype, setPrototype.values, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillSet);
return {
get Set() {
return Set;
},
get polyfillSet() {
return polyfillSet;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Set" + '');
System.register("[email protected]/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "[email protected]/node_modules/rsvp/lib/rsvp/asap";
var len = 0;
function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
scheduleFlush();
}
}
var $__default = asap;
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("[email protected]/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Promise";
var async = System.get("[email protected]/node_modules/rsvp/lib/rsvp/asap").default;
var registerPolyfill = System.get("[email protected]/src/runtime/polyfills/utils").registerPolyfill;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
if (isPromise(x)) {
return x;
}
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
registerPolyfill(polyfillPromise);
return {
get Promise() {
return Promise;
},
get polyfillPromise() {
return polyfillPromise;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Promise" + '');
System.register("[email protected]/src/runtime/polyfills/StringIterator", [], function() {
"use strict";
var $__29;
var __moduleName = "[email protected]/src/runtime/polyfills/StringIterator";
var $__27 = System.get("[email protected]/src/runtime/polyfills/utils"),
createIteratorResultObject = $__27.createIteratorResultObject,
isObject = $__27.isObject;
var $__30 = $traceurRuntime,
hasOwnProperty = $__30.hasOwnProperty,
toProperty = $__30.toProperty;
var iteratedString = Symbol('iteratedString');
var stringIteratorNextIndex = Symbol('stringIteratorNextIndex');
var StringIterator = function StringIterator() {};
($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, "next", {
value: function() {
var o = this;
if (!isObject(o) || !hasOwnProperty(o, iteratedString)) {
throw new TypeError('this must be a StringIterator object');
}
var s = o[toProperty(iteratedString)];
if (s === undefined) {
return createIteratorResultObject(undefined, true);
}
var position = o[toProperty(stringIteratorNextIndex)];
var len = s.length;
if (position >= len) {
o[toProperty(iteratedString)] = undefined;
return createIteratorResultObject(undefined, true);
}
var first = s.charCodeAt(position);
var resultString;
if (first < 0xD800 || first > 0xDBFF || position + 1 === len) {
resultString = String.fromCharCode(first);
} else {
var second = s.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) {
resultString = String.fromCharCode(first);
} else {
resultString = String.fromCharCode(first) + String.fromCharCode(second);
}
}
o[toProperty(stringIteratorNextIndex)] = position + resultString.length;
return createIteratorResultObject(resultString, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__29, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__29), {});
function createStringIterator(string) {
var s = String(string);
var iterator = Object.create(StringIterator.prototype);
iterator[toProperty(iteratedString)] = s;
iterator[toProperty(stringIteratorNextIndex)] = 0;
return iterator;
}
return {get createStringIterator() {
return createStringIterator;
}};
});
System.register("[email protected]/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/String";
var createStringIterator = System.get("[email protected]/src/runtime/polyfills/StringIterator").createStringIterator;
var $__32 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__32.maybeAddFunctions,
maybeAddIterator = $__32.maybeAddIterator,
registerPolyfill = $__32.registerPolyfill;
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
function stringPrototypeIterator() {
var o = $traceurRuntime.checkObjectCoercible(this);
var s = String(o);
return createStringIterator(s);
}
function polyfillString(global) {
var String = global.String;
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol);
}
registerPolyfill(polyfillString);
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
},
get stringPrototypeIterator() {
return stringPrototypeIterator;
},
get polyfillString() {
return polyfillString;
}
};
});
System.get("[email protected]/src/runtime/polyfills/String" + '');
System.register("[email protected]/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__36;
var __moduleName = "[email protected]/src/runtime/polyfills/ArrayIterator";
var $__34 = System.get("[email protected]/src/runtime/polyfills/utils"),
toObject = $__34.toObject,
toUint32 = $__34.toUint32,
createIteratorResultObject = $__34.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__36, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__36), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Array";
var $__37 = System.get("[email protected]/src/runtime/polyfills/ArrayIterator"),
entries = $__37.entries,
keys = $__37.keys,
values = $__37.values;
var $__38 = System.get("[email protected]/src/runtime/polyfills/utils"),
checkIterable = $__38.checkIterable,
isCallable = $__38.isCallable,
isConstructor = $__38.isConstructor,
maybeAddFunctions = $__38.maybeAddFunctions,
maybeAddIterator = $__38.maybeAddIterator,
registerPolyfill = $__38.registerPolyfill,
toInteger = $__38.toInteger,
toLength = $__38.toLength,
toObject = $__38.toObject;
function from(arrLike) {
var mapFn = arguments[1];
var thisArg = arguments[2];
var C = this;
var items = toObject(arrLike);
var mapping = mapFn !== undefined;
var k = 0;
var arr,
len;
if (mapping && !isCallable(mapFn)) {
throw TypeError();
}
if (checkIterable(items)) {
arr = isConstructor(C) ? new C() : [];
for (var $__39 = items[Symbol.iterator](),
$__40; !($__40 = $__39.next()).done; ) {
var item = $__40.value;
{
if (mapping) {
arr[k] = mapFn.call(thisArg, item, k);
} else {
arr[k] = item;
}
k++;
}
}
arr.length = k;
return arr;
}
len = toLength(items.length);
arr = isConstructor(C) ? new C(len) : new Array(len);
for (; k < len; k++) {
if (mapping) {
arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k);
} else {
arr[k] = items[k];
}
}
arr.length = len;
return arr;
}
function of() {
for (var items = [],
$__41 = 0; $__41 < arguments.length; $__41++)
items[$__41] = arguments[$__41];
var C = this;
var len = items.length;
var arr = isConstructor(C) ? new C(len) : new Array(len);
for (var k = 0; k < len; k++) {
arr[k] = items[k];
}
arr.length = len;
return arr;
}
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
function polyfillArray(global) {
var $__42 = global,
Array = $__42.Array,
Object = $__42.Object,
Symbol = $__42.Symbol;
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
maybeAddFunctions(Array, ['from', from, 'of', of]);
maybeAddIterator(Array.prototype, values, Symbol);
maybeAddIterator(Object.getPrototypeOf([].values()), function() {
return this;
}, Symbol);
}
registerPolyfill(polyfillArray);
return {
get from() {
return from;
},
get of() {
return of;
},
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
},
get polyfillArray() {
return polyfillArray;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Array" + '');
System.register("[email protected]/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Object";
var $__43 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__43.maybeAddFunctions,
registerPolyfill = $__43.registerPolyfill;
var $__44 = $traceurRuntime,
defineProperty = $__44.defineProperty,
getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor,
getOwnPropertyNames = $__44.getOwnPropertyNames,
keys = $__44.keys,
privateNames = $__44.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
function polyfillObject(global) {
var Object = global.Object;
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
registerPolyfill(polyfillObject);
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
},
get polyfillObject() {
return polyfillObject;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Object" + '');
System.register("[email protected]/src/runtime/polyfills/Number", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Number";
var $__46 = System.get("[email protected]/src/runtime/polyfills/utils"),
isNumber = $__46.isNumber,
maybeAddConsts = $__46.maybeAddConsts,
maybeAddFunctions = $__46.maybeAddFunctions,
registerPolyfill = $__46.registerPolyfill,
toInteger = $__46.toInteger;
var $abs = Math.abs;
var $isFinite = isFinite;
var $isNaN = isNaN;
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;
var EPSILON = Math.pow(2, -52);
function NumberIsFinite(number) {
return isNumber(number) && $isFinite(number);
}
;
function isInteger(number) {
return NumberIsFinite(number) && toInteger(number) === number;
}
function NumberIsNaN(number) {
return isNumber(number) && $isNaN(number);
}
;
function isSafeInteger(number) {
if (NumberIsFinite(number)) {
var integral = toInteger(number);
if (integral === number)
return $abs(integral) <= MAX_SAFE_INTEGER;
}
return false;
}
function polyfillNumber(global) {
var Number = global.Number;
maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);
maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]);
}
registerPolyfill(polyfillNumber);
return {
get MAX_SAFE_INTEGER() {
return MAX_SAFE_INTEGER;
},
get MIN_SAFE_INTEGER() {
return MIN_SAFE_INTEGER;
},
get EPSILON() {
return EPSILON;
},
get isFinite() {
return NumberIsFinite;
},
get isInteger() {
return isInteger;
},
get isNaN() {
return NumberIsNaN;
},
get isSafeInteger() {
return isSafeInteger;
},
get polyfillNumber() {
return polyfillNumber;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Number" + '');
System.register("[email protected]/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/polyfills";
var polyfillAll = System.get("[email protected]/src/runtime/polyfills/utils").polyfillAll;
polyfillAll(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfillAll(global);
};
return {};
});
System.get("[email protected]/src/runtime/polyfills/polyfills" + '');
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2}],4:[function(require,module,exports){
/**
* Copyright 2012 Craig Campbell
*
* 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.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.1.2
* @url craig.is/killing/mice
*/
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
},
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
_KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
_SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
},
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
_SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc'
},
/**
* variable to store the flipped version of _MAP from above
* needed to check if we should use keypress or not when no action
* is specified
*
* @type {Object|undefined}
*/
_REVERSE_MAP,
/**
* a list of all the callbacks setup via Mousetrap.bind()
*
* @type {Object}
*/
_callbacks = {},
/**
* direct map of string combinations to callbacks used for trigger()
*
* @type {Object}
*/
_direct_map = {},
/**
* keeps track of what level each sequence is at since multiple
* sequences can start out with the same sequence
*
* @type {Object}
*/
_sequence_levels = {},
/**
* variable to store the setTimeout call
*
* @type {null|number}
*/
_reset_timer,
/**
* temporary state where we will ignore the next keyup
*
* @type {boolean|string}
*/
_ignore_next_keyup = false,
/**
* are we currently inside of a sequence?
* type of action ("keyup" or "keydown" or "keypress") or false
*
* @type {boolean|string}
*/
_inside_sequence = false;
/**
* loop through the f keys, f1 to f19 and add them to the map
* programatically
*/
for (var i = 1; i < 20; ++i) {
_MAP[111 + i] = 'f' + i;
}
/**
* loop through to map numbers on the numeric keypad
*/
for (i = 0; i <= 9; ++i) {
_MAP[i + 96] = i;
}
/**
* cross browser add event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _addEvent(object, type, callback) {
if (object.addEventListener) {
return object.addEventListener(type, callback, false);
}
object.attachEvent('on' + type, callback);
}
/**
* takes the event and returns the key character
*
* @param {Event} e
* @return {string}
*/
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
return String.fromCharCode(e.which);
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
return String.fromCharCode(e.which).toLowerCase();
}
/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @return {boolean}
*/
function _stop(e) {
var element = e.target || e.srcElement,
tag_name = element.tagName;
// if the element has the class "mousetrap" then no need to stop
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
return false;
}
// stop for input, select, and textarea
return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
}
/**
* checks if two arrays are equal
*
* @param {Array} modifiers1
* @param {Array} modifiers2
* @returns {boolean}
*/
function _modifiersMatch(modifiers1, modifiers2) {
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
}
/**
* resets all sequence counters except for the ones passed in
*
* @param {Object} do_not_reset
* @returns void
*/
function _resetSequences(do_not_reset) {
do_not_reset = do_not_reset || {};
var active_sequences = false,
key;
for (key in _sequence_levels) {
if (do_not_reset[key]) {
active_sequences = true;
continue;
}
_sequence_levels[key] = 0;
}
if (!active_sequences) {
_inside_sequence = false;
}
}
/**
* finds all callbacks that match based on the keycode, modifiers,
* and action
*
* @param {string} character
* @param {Array} modifiers
* @param {string} action
* @param {boolean=} remove - should we remove any matches
* @param {string=} combination
* @returns {Array}
*/
function _getMatches(character, modifiers, action, remove, combination) {
var i,
callback,
matches = [];
// if there are no events related to this keycode
if (!_callbacks[character]) {
return [];
}
// if a modifier key is coming up on its own we should allow it
if (action == 'keyup' && _isModifier(character)) {
modifiers = [character];
}
// loop through all callbacks for the key that was pressed
// and see if any of them match
for (i = 0; i < _callbacks[character].length; ++i) {
callback = _callbacks[character][i];
// if this is a sequence but it is not at the right level
// then move onto the next match
if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
continue;
}
// if the action we are looking for doesn't match the action we got
// then we should keep going
if (action != callback.action) {
continue;
}
// if this is a keypress event that means that we need to only
// look at the character, otherwise check the modifiers as
// well
if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
// remove is used so if you change your mind and call bind a
// second time with a new function the first one is overwritten
if (remove && callback.combo == combination) {
_callbacks[character].splice(i, 1);
}
matches.push(callback);
}
}
return matches;
}
/**
* takes a key event and figures out what the modifiers are
*
* @param {Event} e
* @returns {Array}
*/
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
/**
* actually calls the callback function
*
* if your callback function returns false this will use the jquery
* convention - prevent default and stop propogation on the event
*
* @param {Function} callback
* @param {Event} e
* @returns void
*/
function _fireCallback(callback, e) {
if (callback(e) === false) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
}
/**
* handles a character key event
*
* @param {string} character
* @param {Event} e
* @returns void
*/
function _handleCharacter(character, e) {
// if this event should not happen stop here
if (_stop(e)) {
return;
}
var callbacks = _getMatches(character, _eventModifiers(e), e.type),
i,
do_not_reset = {},
processed_sequence_callback = false;
// loop through matching callbacks for this key event
for (i = 0; i < callbacks.length; ++i) {
// fire for all sequence callbacks
// this is because if for example you have multiple sequences
// bound such as "g i" and "g t" they both need to fire the
// callback for matching g cause otherwise you can only ever
// match the first one
if (callbacks[i].seq) {
processed_sequence_callback = true;
// keep a list of which sequences were matches for later
do_not_reset[callbacks[i].seq] = 1;
_fireCallback(callbacks[i].callback, e);
continue;
}
// if there were no sequence matches but we are still here
// that means this is a regular match so we should fire that
if (!processed_sequence_callback && !_inside_sequence) {
_fireCallback(callbacks[i].callback, e);
}
}
// if you are inside of a sequence and the key you are pressing
// is not a modifier key then we should reset all sequences
// that were not matched by this key event
if (e.type == _inside_sequence && !_isModifier(character)) {
_resetSequences(do_not_reset);
}
}
/**
* handles a keydown event
*
* @param {Event} e
* @returns void
*/
function _handleKey(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
e.which = typeof e.which == "number" ? e.which : e.keyCode;
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
if (e.type == 'keyup' && _ignore_next_keyup == character) {
_ignore_next_keyup = false;
return;
}
_handleCharacter(character, e);
}
/**
* determines if the keycode specified is a modifier key or not
*
* @param {string} key
* @returns {boolean}
*/
function _isModifier(key) {
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
}
/**
* called to set a 1 second timeout on the specified sequence
*
* this is so after each key press in the sequence you have 1 second
* to press the next key before you have to start over
*
* @returns void
*/
function _resetSequenceTimer() {
clearTimeout(_reset_timer);
_reset_timer = setTimeout(_resetSequences, 1000);
}
/**
* reverses the map lookup so that we can look for specific keys
* to see what can and can't use keypress
*
* @return {Object}
*/
function _getReverseMap() {
if (!_REVERSE_MAP) {
_REVERSE_MAP = {};
for (var key in _MAP) {
// pull out the numeric keypad from here cause keypress should
// be able to detect the keys from the character
if (key > 95 && key < 112) {
continue;
}
if (_MAP.hasOwnProperty(key)) {
_REVERSE_MAP[_MAP[key]] = key;
}
}
}
return _REVERSE_MAP;
}
/**
* picks the best action based on the key combination
*
* @param {string} key - character for key
* @param {Array} modifiers
* @param {string=} action passed in
*/
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
/**
* binds a key sequence to an event
*
* @param {string} combo - combo specified in bind call
* @param {Array} keys
* @param {Function} callback
* @param {string=} action
* @returns void
*/
function _bindSequence(combo, keys, callback, action) {
// start off by adding a sequence level record for this combination
// and setting the level to 0
_sequence_levels[combo] = 0;
// if there is no action pick the best one for the first key
// in the sequence
if (!action) {
action = _pickBestAction(keys[0], []);
}
/**
* callback to increase the sequence level for this sequence and reset
* all other sequences that were active
*
* @param {Event} e
* @returns void
*/
var _increaseSequence = function(e) {
_inside_sequence = action;
++_sequence_levels[combo];
_resetSequenceTimer();
},
/**
* wraps the specified callback inside of another function in order
* to reset all sequence counters as soon as this sequence is done
*
* @param {Event} e
* @returns void
*/
_callbackAndReset = function(e) {
_fireCallback(callback, e);
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
_ignore_next_keyup = _characterFromEvent(e);
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(_resetSequences, 10);
},
i;
// loop through keys one at a time and bind the appropriate callback
// function. for any key leading up to the final one it should
// increase the sequence. after the final, it should reset all sequences
for (i = 0; i < keys.length; ++i) {
_bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
}
}
/**
* binds a single keyboard combination
*
* @param {string} combination
* @param {Function} callback
* @param {string=} action
* @param {string=} sequence_name - name of sequence if part of sequence
* @param {number=} level - what part of the sequence the command is
* @returns void
*/
function _bindSingle(combination, callback, action, sequence_name, level) {
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' '),
i,
key,
keys,
modifiers = [];
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
return _bindSequence(combination, sequence, callback, action);
}
// take the keys from this pattern and figure out what the actual
// pattern is all about
keys = combination === '+' ? ['+'] : combination.split('+');
for (i = 0; i < keys.length; ++i) {
key = keys[i];
// normalize key names
if (_SPECIAL_ALIASES[key]) {
key = _SPECIAL_ALIASES[key];
}
// if this is not a keypress event then we should
// be smart about using shift keys
// this will only work for US keyboards however
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
key = _SHIFT_MAP[key];
modifiers.push('shift');
}
// if this key is a modifier then add it to the list of modifiers
if (_isModifier(key)) {
modifiers.push(key);
}
}
// depending on what the key combination is
// we will try to pick the best event for it
action = _pickBestAction(key, modifiers, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
if (!_callbacks[key]) {
_callbacks[key] = [];
}
// remove an existing match if there is one
_getMatches(key, modifiers, action, !sequence_name, combination);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
_callbacks[key][sequence_name ? 'unshift' : 'push']({
callback: callback,
modifiers: modifiers,
action: action,
seq: sequence_name,
level: level,
combo: combination
});
}
/**
* binds multiple combinations to the same callback
*
* @param {Array} combinations
* @param {Function} callback
* @param {string|undefined} action
* @returns void
*/
function _bindMultiple(combinations, callback, action) {
for (var i = 0; i < combinations.length; ++i) {
_bindSingle(combinations[i], callback, action);
}
}
// start!
_addEvent(document, 'keypress', _handleKey);
_addEvent(document, 'keydown', _handleKey);
_addEvent(document, 'keyup', _handleKey);
var mousetrap = {
/**
* binds an event to mousetrap
*
* can be a single key, a combination of keys separated with +,
* a comma separated list of keys, an array of keys, or
* a sequence of keys separated by spaces
*
* be sure to list the modifier keys first to make sure that the
* correct key ends up getting bound (the last key in the pattern)
*
* @param {string|Array} keys
* @param {Function} callback
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
* @returns void
*/
bind: function(keys, callback, action) {
_bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
_direct_map[keys + ':' + action] = callback;
return this;
},
/**
* unbinds an event to mousetrap
*
* the unbinding sets the callback function of the specified key combo
* to an empty function and deletes the corresponding key in the
* _direct_map dict.
*
* the keycombo+action has to be exactly the same as
* it was defined in the bind method
*
* TODO: actually remove this from the _callbacks dictionary instead
* of binding an empty function
*
* @param {string|Array} keys
* @param {string} action
* @returns void
*/
unbind: function(keys, action) {
if (_direct_map[keys + ':' + action]) {
delete _direct_map[keys + ':' + action];
this.bind(keys, function() {}, action);
}
return this;
},
/**
* triggers an event that has already been bound
*
* @param {string} keys
* @param {string=} action
* @returns void
*/
trigger: function(keys, action) {
_direct_map[keys + ':' + action]();
return this;
},
/**
* resets the library back to its initial state. this is useful
* if you want to clear out the current keyboard shortcuts and bind
* new ones - for example if you switch to another page
*
* @returns void
*/
reset: function() {
_callbacks = {};
_direct_map = {};
return this;
}
};
module.exports = mousetrap;
},{}],5:[function(require,module,exports){
(function( factory ) {
if (typeof define !== 'undefined' && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
window.scrollMonitor = factory();
}
})(function() {
var scrollTop = function() {
return window.pageYOffset ||
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
};
var exports = {};
var watchers = [];
var VISIBILITYCHANGE = 'visibilityChange';
var ENTERVIEWPORT = 'enterViewport';
var FULLYENTERVIEWPORT = 'fullyEnterViewport';
var EXITVIEWPORT = 'exitViewport';
var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';
var LOCATIONCHANGE = 'locationChange';
var STATECHANGE = 'stateChange';
var eventTypes = [
VISIBILITYCHANGE,
ENTERVIEWPORT,
FULLYENTERVIEWPORT,
EXITVIEWPORT,
PARTIALLYEXITVIEWPORT,
LOCATIONCHANGE,
STATECHANGE
];
var defaultOffsets = {top: 0, bottom: 0};
var getViewportHeight = function() {
return window.innerHeight || document.documentElement.clientHeight;
};
var getDocumentHeight = function() {
// jQuery approach
// whichever is greatest
return Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
};
exports.viewportTop = null;
exports.viewportBottom = null;
exports.documentHeight = null;
exports.viewportHeight = getViewportHeight();
var previousDocumentHeight;
var latestEvent;
var calculateViewportI;
function calculateViewport() {
exports.viewportTop = scrollTop();
exports.viewportBottom = exports.viewportTop + exports.viewportHeight;
exports.documentHeight = getDocumentHeight();
if (exports.documentHeight !== previousDocumentHeight) {
calculateViewportI = watchers.length;
while( calculateViewportI-- ) {
watchers[calculateViewportI].recalculateLocation();
}
previousDocumentHeight = exports.documentHeight;
}
}
function recalculateWatchLocationsAndTrigger() {
exports.viewportHeight = getViewportHeight();
calculateViewport();
updateAndTriggerWatchers();
}
var recalculateAndTriggerTimer;
function debouncedRecalcuateAndTrigger() {
clearTimeout(recalculateAndTriggerTimer);
recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );
}
var updateAndTriggerWatchersI;
function updateAndTriggerWatchers() {
// update all watchers then trigger the events so one can rely on another being up to date.
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].update();
}
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].triggerCallbacks();
}
}
function ElementWatcher( watchItem, offsets ) {
var self = this;
this.watchItem = watchItem;
if (!offsets) {
this.offsets = defaultOffsets;
} else if (offsets === +offsets) {
this.offsets = {top: offsets, bottom: offsets};
} else {
this.offsets = {
top: offsets.top || defaultOffsets.top,
bottom: offsets.bottom || defaultOffsets.bottom
};
}
this.callbacks = {}; // {callback: function, isOne: true }
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]] = [];
}
this.locked = false;
var wasInViewport;
var wasFullyInViewport;
var wasAboveViewport;
var wasBelowViewport;
var listenerToTriggerListI;
var listener;
function triggerCallbackArray( listeners ) {
if (listeners.length === 0) {
return;
}
listenerToTriggerListI = listeners.length;
while( listenerToTriggerListI-- ) {
listener = listeners[listenerToTriggerListI];
listener.callback.call( self, latestEvent );
if (listener.isOne) {
listeners.splice(listenerToTriggerListI, 1);
}
}
}
this.triggerCallbacks = function triggerCallbacks() {
if (this.isInViewport && !wasInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
}
if (this.isFullyInViewport && !wasFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
}
if (this.isAboveViewport !== wasAboveViewport &&
this.isBelowViewport !== wasBelowViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
// if you skip completely past this element
if (!wasFullyInViewport && !this.isFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!wasInViewport && !this.isInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
}
if (!this.isFullyInViewport && wasFullyInViewport) {
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!this.isInViewport && wasInViewport) {
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
if (this.isInViewport !== wasInViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
}
switch( true ) {
case wasInViewport !== this.isInViewport:
case wasFullyInViewport !== this.isFullyInViewport:
case wasAboveViewport !== this.isAboveViewport:
case wasBelowViewport !== this.isBelowViewport:
triggerCallbackArray( this.callbacks[STATECHANGE] );
}
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
};
this.recalculateLocation = function() {
if (this.locked) {
return;
}
var previousTop = this.top;
var previousBottom = this.bottom;
if (this.watchItem.nodeName) { // a dom element
var cachedDisplay = this.watchItem.style.display;
if (cachedDisplay === 'none') {
this.watchItem.style.display = '';
}
var boundingRect = this.watchItem.getBoundingClientRect();
this.top = boundingRect.top + exports.viewportTop;
this.bottom = boundingRect.bottom + exports.viewportTop;
if (cachedDisplay === 'none') {
this.watchItem.style.display = cachedDisplay;
}
} else if (this.watchItem === +this.watchItem) { // number
if (this.watchItem > 0) {
this.top = this.bottom = this.watchItem;
} else {
this.top = this.bottom = exports.documentHeight - this.watchItem;
}
} else { // an object with a top and bottom property
this.top = this.watchItem.top;
this.bottom = this.watchItem.bottom;
}
this.top -= this.offsets.top;
this.bottom += this.offsets.bottom;
this.height = this.bottom - this.top;
if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {
triggerCallbackArray( this.callbacks[LOCATIONCHANGE] );
}
};
this.recalculateLocation();
this.update();
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
}
ElementWatcher.prototype = {
on: function( event, callback, isOne ) {
// trigger the event if it applies to the element right now.
switch( true ) {
case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:
case event === ENTERVIEWPORT && this.isInViewport:
case event === FULLYENTERVIEWPORT && this.isFullyInViewport:
case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:
case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:
callback.call( this, latestEvent );
if (isOne) {
return;
}
}
if (this.callbacks[event]) {
this.callbacks[event].push({callback: callback, isOne: isOne||false});
} else {
throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
off: function( event, callback ) {
if (this.callbacks[event]) {
for (var i = 0, item; item = this.callbacks[event][i]; i++) {
if (item.callback === callback) {
this.callbacks[event].splice(i, 1);
break;
}
}
} else {
throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
one: function( event, callback ) {
this.on( event, callback, true);
},
recalculateSize: function() {
this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;
this.bottom = this.top + this.height;
},
update: function() {
this.isAboveViewport = this.top < exports.viewportTop;
this.isBelowViewport = this.bottom > exports.viewportBottom;
this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);
this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||
(this.isAboveViewport && this.isBelowViewport);
},
destroy: function() {
var index = watchers.indexOf(this),
self = this;
watchers.splice(index, 1);
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]].length = 0;
}
},
// prevent recalculating the element location
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
}
};
var eventHandlerFactory = function (type) {
return function( callback, isOne ) {
this.on.call(this, type, callback, isOne);
};
};
for (var i = 0, j = eventTypes.length; i < j; i++) {
var type = eventTypes[i];
ElementWatcher.prototype[type] = eventHandlerFactory(type);
}
try {
calculateViewport();
} catch (e) {
try {
window.$(calculateViewport);
} catch (e) {
throw new Error('If you must put scrollMonitor in the <head>, you must use jQuery.');
}
}
function scrollMonitorListener(event) {
latestEvent = event;
calculateViewport();
updateAndTriggerWatchers();
}
if (window.addEventListener) {
window.addEventListener('scroll', scrollMonitorListener);
window.addEventListener('resize', debouncedRecalcuateAndTrigger);
} else {
// Old IE support
window.attachEvent('onscroll', scrollMonitorListener);
window.attachEvent('onresize', debouncedRecalcuateAndTrigger);
}
exports.beget = exports.create = function( element, offsets ) {
if (typeof element === 'string') {
element = document.querySelector(element);
} else if (element && element.length > 0) {
element = element[0];
}
var watcher = new ElementWatcher( element, offsets );
watchers.push(watcher);
watcher.update();
return watcher;
};
exports.update = function() {
latestEvent = null;
calculateViewport();
updateAndTriggerWatchers();
};
exports.recalculateLocations = function() {
exports.documentHeight = 0;
exports.update();
};
return exports;
});
},{}],6:[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return obj.length === +obj.length ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(slice.call(arguments, 1), true, true, []);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],7:[function(require,module,exports){
module.exports={
"name": "clappr",
"version": "0.0.62",
"description": "An extensible media player for the web",
"main": "dist/clappr.min.js",
"scripts": {
"test": "./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox"
},
"repository": {
"type": "git",
"url": "[email protected]:globocom/clappr.git"
},
"author": "Globo.com",
"license": "ISC",
"bugs": {
"url": "https://github.com/globocom/clappr/issues"
},
"browserify-shim": "./shim.js",
"browserify": {
"transform": [
"browserify-shim"
]
},
"homepage": "https://github.com/globocom/clappr",
"devDependencies": {
"browserify": "^6.3.2",
"browserify-shim": "^3.8.0",
"chai": "latest",
"compass-mixins": "latest",
"dotenv": "^0.4.0",
"es6ify": "~1.4.0",
"exorcist": "^0.1.6",
"express": "^4.6.1",
"express-alias": "latest",
"glob": "^4.0.2",
"gulp": "^3.8.1",
"gulp-compressor": "^0.1.0",
"gulp-jshint": "latest",
"gulp-livereload": "^2.1.0",
"gulp-minify-css": "~0.3.5",
"gulp-rename": "^1.2.0",
"gulp-sass": "1.0.0",
"gulp-streamify": "0.0.5",
"gulp-uglify": "^1.0.1",
"gulp-util": "latest",
"karma": "^0.12.17",
"karma-browserify": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^0.1.4",
"karma-cli": "0.0.4",
"karma-firefox-launcher": "^0.1.3",
"karma-jasmine": "^0.2.2",
"karma-jquery": "^0.1.0",
"karma-mocha": "^0.1.4",
"karma-safari-launcher": "^0.1.1",
"karma-sinon": "^1.0.3",
"karma-sinon-chai": "^0.2.0",
"mkdirp": "^0.5.0",
"s3": "^4.1.1",
"scp": "latest",
"sinon": "^1.10.2",
"traceur": "0.0.72",
"vinyl-source-stream": "^1.0.0",
"vinyl-transform": "0.0.1",
"watchify": "^2.0.0",
"yargs": "latest"
},
"dependencies": {
"underscore": "1.7.0",
"jquery": "~2.1.0",
"mousetrap": "0.0.1",
"scrollmonitor": "^1.0.8"
}
}
},{}],8:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var Log = require('../plugins/log').getInstance();
var slice = Array.prototype.slice;
var Events = function Events() {};
($traceurRuntime.createClass)(Events, {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain,
ev,
events,
names,
i,
l,
j,
k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
events = this._events[name];
if (events) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length)
delete this._events[name];
}
}
return this;
},
trigger: function(name) {
var klass = arguments[arguments.length - 1];
Log.info(klass, name);
if (!this._events)
return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args))
return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events)
triggerEvents(events, args);
if (allEvents)
triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo)
return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object')
callback = this;
if (obj)
(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events))
delete this._listeningTo[id];
}
return this;
}
}, {});
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name)
return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0,
l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev,
i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)
(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
_.each(listenMethods, function(implementation, method) {
Events.prototype[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object')
callback = this;
obj[implementation](name, callback, this);
return this;
};
});
module.exports = Events;
},{"../plugins/log":40,"underscore":6}],9:[function(require,module,exports){
"use strict";
var _ = require('underscore');
module.exports = {
'iframe_player': _.template('<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><script type="text/javascript" charset="utf-8" src="http://cdn.clappr.io/j/vendor/jquery.min.js"></script><script type="text/javascript" charset="utf-8" src="http://cdn.clappr.io/j/vendor/underscore-min.js"></script><script type="text/javascript" charset="utf-8" src="http://flavio.globoi.com/clappr.js"></script><script type="text/javascript" charset="utf-8"></script><style>body {margin:0}</style></head><body><div id="player-wrapper" style="border: 0px;border-radius: 0px;width: 100%;height: 100%"></div></body></html>'),
'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %><div class="bar-container" data-<%= name %>><% for (var i = 0; i < segments; i++) { %><div class="segmented-bar-element" data-<%= name %>></div><% } %></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'),
'seek_time': _.template('<span data-seek-time></span>'),
'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'),
'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'),
'background_button': _.template('<div class="background-button-wrapper" data-background-button><button class="background-button-icon" data-background-button></button></div>'),
'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'),
'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'),
'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'),
'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'),
CSS: {
'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}',
'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}',
'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}',
'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',
'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',
'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',
'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',
'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}',
'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}',
'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,"Open Sans",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,"Open Sans",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:"|";margin-right:7px}',
'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}',
'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',
'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'
}
};
},{"underscore":6}],10:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var JST = require('./jst');
var Styler = {getStyleFor: function(name, options) {
options = options || {};
return $('<style class="clappr-style"></style>').html(_.template(JST.CSS[name])(options));
}};
module.exports = Styler;
},{"./jst":9,"jquery":"jquery","underscore":6}],11:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps)
_.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
child.super = function(name) {
return parent.prototype[name];
};
child.prototype.getClass = function() {
return child;
};
return child;
};
var formatTime = function(time) {
time = time * 1000;
time = parseInt(time / 1000);
var seconds = time % 60;
time = parseInt(time / 60);
var minutes = time % 60;
time = parseInt(time / 60);
var hours = time % 24;
var out = "";
if (hours && hours > 0)
out += ("0" + hours).slice(-2) + ":";
out += ("0" + minutes).slice(-2) + ":";
out += ("0" + seconds).slice(-2);
return out.trim();
};
var Fullscreen = {
isFullscreen: function() {
return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen;
},
requestFullscreen: function(el) {
if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
},
cancelFullscreen: function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
};
var seekStringToSeconds = function(url) {
var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse();
var seconds = 0;
var factor = 1;
_.each(elements, function(el) {
seconds += (parseInt(el) * factor);
factor = factor * 60;
}, this);
return seconds;
};
module.exports = {
extend: extend,
formatTime: formatTime,
Fullscreen: Fullscreen,
seekStringToSeconds: seekStringToSeconds
};
},{"underscore":6}],12:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var _ = require('underscore');
var Container = function Container(options) {
$traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]);
this.playback = options.playback;
this.settings = this.playback.settings;
this.isReady = false;
this.mediaControlDisabled = false;
this.plugins = [this.playback];
this.bindEvents();
};
var $Container = Container;
($traceurRuntime.createClass)(Container, {
get name() {
return 'Container';
},
get attributes() {
return {
class: 'container',
'data-container': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.playback, 'playback:progress', this.progress);
this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated);
this.listenTo(this.playback, 'playback:ready', this.ready);
this.listenTo(this.playback, 'playback:buffering', this.buffering);
this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull);
this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate);
this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata);
this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.playback, 'playback:bitrate', this.updateBitrate);
this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged);
this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged);
this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl);
this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl);
this.listenTo(this.playback, 'playback:ended', this.ended);
this.listenTo(this.playback, 'playback:play', this.playing);
this.listenTo(this.playback, 'playback:error', this.error);
},
with: function(klass) {
_.extend(this, klass);
return this;
},
playbackStateChanged: function() {
this.trigger('container:playbackstate');
},
playbackDvrStateChanged: function(dvrInUse) {
this.settings = this.playback.settings;
this.dvrInUse = dvrInUse;
this.trigger('container:dvr', dvrInUse);
},
updateBitrate: function(newBitrate) {
this.trigger('container:bitrate', newBitrate);
},
statsReport: function(metrics) {
this.trigger('container:stats:report', metrics);
},
getPlaybackType: function() {
return this.playback.getPlaybackType();
},
isDvrEnabled: function() {
return !!this.playback.dvrEnabled;
},
isDvrInUse: function() {
return !!this.dvrInUse;
},
destroy: function() {
this.trigger('container:destroyed', this, this.name);
this.playback.destroy();
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
},
setStyle: function(style) {
this.$el.css(style);
},
animate: function(style, duration) {
return this.$el.animate(style, duration).promise();
},
ready: function() {
this.isReady = true;
this.trigger('container:ready', this.name);
},
isPlaying: function() {
return this.playback.isPlaying();
},
getDuration: function() {
return this.playback.getDuration();
},
error: function(errorObj) {
this.$el.append(errorObj.render().el);
this.trigger('container:error', {
error: errorObj,
container: this
}, this.name);
},
loadedMetadata: function(duration) {
this.trigger('container:loadedmetadata', duration);
},
timeUpdated: function(position, duration) {
this.trigger('container:timeupdate', position, duration, this.name);
},
progress: function(startPosition, endPosition, duration) {
this.trigger('container:progress', startPosition, endPosition, duration, this.name);
},
playing: function() {
this.trigger('container:play', this.name);
},
play: function() {
this.playback.play();
},
stop: function() {
this.trigger('container:stop', this.name);
this.playback.stop();
},
pause: function() {
this.trigger('container:pause', this.name);
this.playback.pause();
},
ended: function() {
this.trigger('container:ended', this, this.name);
},
clicked: function() {
this.trigger('container:click', this, this.name);
},
setCurrentTime: function(time) {
this.trigger('container:seek', time, this.name);
this.playback.seek(time);
},
setVolume: function(value) {
this.trigger('container:volume', value, this.name);
this.playback.volume(value);
},
fullscreen: function() {
this.trigger('container:fullscreen', this.name);
},
buffering: function() {
this.trigger('container:state:buffering', this.name);
},
bufferfull: function() {
this.trigger('container:state:bufferfull', this.name);
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find(function(plugin) {
return plugin.name === name;
});
},
settingsUpdate: function() {
this.settings = this.playback.settings;
this.trigger('container:settingsupdate');
},
highDefinitionUpdate: function() {
this.trigger('container:highdefinitionupdate');
},
isHighDefinitionInUse: function() {
return this.playback.isHighDefinitionInUse();
},
disableMediaControl: function() {
this.mediaControlDisabled = true;
this.trigger('container:mediacontrol:disable');
},
enableMediaControl: function() {
this.mediaControlDisabled = false;
this.trigger('container:mediacontrol:enable');
},
render: function() {
var style = Styler.getStyleFor('container');
this.$el.append(style);
this.$el.append(this.playback.render().el);
return this;
}
}, {}, UIObject);
module.exports = Container;
},{"../../base/styler":10,"ui_object":"ui_object","underscore":6}],13:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Container = require('container');
var $ = require('jquery');
var ContainerFactory = function ContainerFactory(options, loader) {
$traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]);
this.options = options;
this.loader = loader;
};
var $ContainerFactory = ContainerFactory;
($traceurRuntime.createClass)(ContainerFactory, {
createContainers: function() {
var $__0 = this;
return $.Deferred((function(promise) {
promise.resolve(_.map($__0.options.sources, (function(source) {
return $__0.createContainer(source);
}), $__0));
}));
},
findPlaybackPlugin: function(source) {
return _.find(this.loader.playbackPlugins, (function(p) {
return p.canPlay(source.toString());
}), this);
},
createContainer: function(source) {
var playbackPlugin = this.findPlaybackPlugin(source);
var options = _.extend({}, this.options, {
src: source,
autoPlay: !!this.options.autoPlay
});
var playback = new playbackPlugin(options);
var container = new Container({playback: playback});
var defer = $.Deferred();
defer.promise(container);
this.addContainerPlugins(container, source);
this.listenToOnce(container, 'container:ready', (function() {
return defer.resolve(container);
}));
return container;
},
addContainerPlugins: function(container, source) {
_.each(this.loader.containerPlugins, function(Plugin) {
var options = _.extend(this.options, {
container: container,
src: source
});
container.addPlugin(new Plugin(options));
}, this);
}
}, {}, BaseObject);
module.exports = ContainerFactory;
},{"base_object":"base_object","container":"container","jquery":"jquery","underscore":6}],14:[function(require,module,exports){
"use strict";
module.exports = require('./container_factory');
},{"./container_factory":13}],15:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var UIObject = require('ui_object');
var ContainerFactory = require('../container_factory');
var Fullscreen = require('../../base/utils').Fullscreen;
var Styler = require('../../base/styler');
var MediaControl = require('media_control');
var PlayerInfo = require('player_info');
var Mediator = require('mediator');
var Core = function Core(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]);
PlayerInfo.options = options;
this.options = options;
this.plugins = [];
this.containers = [];
this.createContainers(options);
document.addEventListener('fullscreenchange', (function() {
return $__0.exit();
}));
document.addEventListener('MSFullscreenChange', (function() {
return $__0.exit();
}));
document.addEventListener('mozfullscreenchange', (function() {
return $__0.exit();
}));
};
var $Core = Core;
($traceurRuntime.createClass)(Core, {
get events() {
return {
'webkitfullscreenchange': 'exit',
'mousemove': 'showMediaControl',
'mouseleave': 'hideMediaControl'
};
},
get attributes() {
return {'data-player': ''};
},
createContainers: function(options) {
var $__0 = this;
this.defer = $.Deferred();
this.defer.promise(this);
this.containerFactory = new ContainerFactory(options, options.loader);
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
})).then((function(containers) {
return $__0.resolveOnContainersReady(containers);
}));
},
updateSize: function() {
if (Fullscreen.isFullscreen()) {
this.setFullscreen();
} else {
this.setPlayerSize();
}
Mediator.trigger('player:resize');
},
setFullscreen: function() {
this.$el.addClass('fullscreen');
this.$el.removeAttr('style');
if (!_.isEqual(PlayerInfo.currentSize, PlayerInfo.currentSize)) {
PlayerInfo.previousSize = PlayerInfo.currentSize;
}
PlayerInfo.currentSize = {
width: $(window).width(),
height: $(window).height()
};
},
setPlayerSize: function() {
this.resize(PlayerInfo.previousSize);
this.$el.removeClass('fullscreen');
},
resize: function(options) {
var size = _.pick(options, 'width', 'height');
this.$el.css(size);
PlayerInfo.previousSize = PlayerInfo.currentSize;
PlayerInfo.currentSize = size;
},
resolveOnContainersReady: function(containers) {
var $__0 = this;
$.when.apply($, containers).done((function() {
return $__0.defer.resolve($__0);
}));
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find((function(plugin) {
return plugin.name === name;
}));
},
load: function(sources) {
var $__0 = this;
sources = _.isArray(sources) ? sources : [sources.toString()];
_(this.containers).each((function(container) {
return container.destroy();
}));
this.containerFactory.options = _(this.options).extend({sources: sources});
this.containerFactory.createContainers().then((function(containers) {
$__0.setupContainers(containers);
}));
},
destroy: function() {
_(this.containers).each((function(container) {
return container.destroy();
}));
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
},
exit: function() {
this.updateSize();
this.mediaControl.show();
},
setMediaControlContainer: function(container) {
this.mediaControl.setContainer(container);
this.mediaControl.render();
},
disableMediaControl: function() {
this.mediaControl.disable();
this.$el.removeClass('nocursor');
},
enableMediaControl: function() {
this.mediaControl.enable();
},
removeContainer: function(container) {
this.stopListening(container);
this.containers = _.without(this.containers, container);
},
appendContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.el.appendChild(container.render().el);
this.containers.push(container);
},
prependContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.$el.append(container.render().el);
this.containers.unshift(container);
},
setupContainers: function(containers) {
_.map(containers, this.appendContainer, this);
this.setupMediaControl(this.getCurrentContainer());
this.render();
this.$el.appendTo(this.options.parentElement);
return containers;
},
createContainer: function(source) {
var container = this.containerFactory.createContainer(source);
this.appendContainer(container);
return container;
},
setupMediaControl: function(container) {
if (this.mediaControl) {
this.mediaControl.setContainer(container);
} else {
this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));
this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen);
this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true));
this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false));
}
},
createMediaControl: function(options) {
if (options.mediacontrol && options.mediacontrol.external) {
return new options.mediacontrol.external(options);
} else {
return new MediaControl(options);
}
},
getCurrentContainer: function() {
return this.containers[0];
},
toggleFullscreen: function() {
if (!Fullscreen.isFullscreen()) {
Fullscreen.requestFullscreen(this.el);
this.$el.addClass('fullscreen');
} else {
Fullscreen.cancelFullscreen();
this.$el.removeClass('fullscreen nocursor');
}
this.mediaControl.show();
},
showMediaControl: function(event) {
this.mediaControl.show(event);
},
hideMediaControl: function(event) {
this.mediaControl.hide(event);
},
onMediaControlShow: function(showing) {
if (showing)
this.$el.removeClass('nocursor');
else if (Fullscreen.isFullscreen())
this.$el.addClass('nocursor');
},
render: function() {
var style = Styler.getStyleFor('core');
this.$el.append(style);
this.$el.append(this.mediaControl.render().el);
this.options.width = this.options.width || this.$el.width();
this.options.height = this.options.height || this.$el.height();
PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height');
this.updateSize();
return this;
}
}, {}, UIObject);
module.exports = Core;
},{"../../base/styler":10,"../../base/utils":11,"../container_factory":14,"jquery":"jquery","media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":6}],16:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Core = require('core');
var CoreFactory = function CoreFactory(player, loader) {
this.player = player;
this.options = player.options;
this.loader = loader;
this.options.loader = this.loader;
};
($traceurRuntime.createClass)(CoreFactory, {
create: function() {
this.core = new Core(this.options);
this.core.then(this.addCorePlugins.bind(this));
return this.core;
},
addCorePlugins: function() {
_.each(this.loader.corePlugins, function(Plugin) {
var plugin = new Plugin(this.core);
this.core.addPlugin(plugin);
this.setupExternalInterface(plugin);
}, this);
return this.core;
},
setupExternalInterface: function(plugin) {
_.each(plugin.getExternalInterface(), function(value, key) {
this.player[key] = value.bind(plugin);
}, this);
}
}, {}, BaseObject);
module.exports = CoreFactory;
},{"base_object":"base_object","core":"core","underscore":6}],17:[function(require,module,exports){
"use strict";
module.exports = require('./core_factory');
},{"./core_factory":16}],18:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var $ = require('jquery');
var Player = require('../player');
var IframePlayer = function IframePlayer(options) {
$traceurRuntime.superCall(this, $IframePlayer.prototype, "constructor", [options]);
this.options = options;
this.createIframe();
};
var $IframePlayer = IframePlayer;
($traceurRuntime.createClass)(IframePlayer, {
createIframe: function() {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("frameborder", 0);
this.iframe.setAttribute("id", this.uniqueId);
this.iframe.setAttribute("allowfullscreen", true);
this.iframe.setAttribute("scrolling", "no");
this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString());
this.iframe.setAttribute('width', this.options.width);
this.iframe.setAttribute('height', this.options.height);
},
attachTo: function(element) {
element.appendChild(this.iframe);
},
addEventListeners: function() {
var $__0 = this;
this.iframe.contentWindow.addEventListener("fullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("webkitfullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("mozfullscreenchange", (function() {
return $__0.updateSize();
}));
},
buildQueryString: function() {
var result = "";
for (var param in this.options) {
result += !!result ? "&" : "?";
result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param]);
}
return result;
}
}, {}, BaseObject);
module.exports = IframePlayer;
},{"../player":23,"base_object":"base_object","jquery":"jquery"}],19:[function(require,module,exports){
"use strict";
module.exports = require('./iframe_player');
},{"./iframe_player":18}],20:[function(require,module,exports){
"use strict";
module.exports = require('./loader');
},{"./loader":21}],21:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var _ = require('underscore');
var PlayerInfo = require('player_info');
var HTML5VideoPlayback = require('html5_video');
var FlashVideoPlayback = require('flash');
var HTML5AudioPlayback = require('html5_audio');
var HLSVideoPlayback = require('hls');
var NoOp = require('../../playbacks/no_op');
var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');
var StatsPlugin = require('../../plugins/stats');
var WaterMarkPlugin = require('../../plugins/watermark');
var PosterPlugin = require('../../plugins/poster');
var GoogleAnalyticsPlugin = require('../../plugins/google_analytics');
var ClickToPausePlugin = require('../../plugins/click_to_pause');
var BackgroundButton = require('../../plugins/background_button');
var DVRControls = require('../../plugins/dvr_controls');
var Loader = function Loader(externalPlugins) {
$traceurRuntime.superCall(this, $Loader.prototype, "constructor", []);
this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp];
this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin];
this.corePlugins = [BackgroundButton, DVRControls];
if (externalPlugins) {
this.addExternalPlugins(externalPlugins);
}
};
var $Loader = Loader;
($traceurRuntime.createClass)(Loader, {
addExternalPlugins: function(plugins) {
var pluginName = function(plugin) {
return plugin.prototype.name;
};
if (plugins.playback) {
this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);
}
if (plugins.container) {
this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);
}
if (plugins.core) {
this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);
}
PlayerInfo.playbackPlugins = this.playbackPlugins;
},
getPlugin: function(name) {
var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);
return _.find(allPlugins, function(plugin) {
return plugin.prototype.name === name;
});
}
}, {}, BaseObject);
module.exports = Loader;
},{"../../playbacks/no_op":30,"../../plugins/background_button":33,"../../plugins/click_to_pause":35,"../../plugins/dvr_controls":37,"../../plugins/google_analytics":39,"../../plugins/poster":42,"../../plugins/spinner_three_bounce":44,"../../plugins/stats":46,"../../plugins/watermark":48,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","player_info":"player_info","underscore":6}],22:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var UIObject = require('ui_object');
var Utils = require('../../base/utils');
var Mousetrap = require('mousetrap');
var SeekTime = require('../seek_time');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var MediaControl = function MediaControl(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]);
this.seekTime = new SeekTime(this);
this.options = options;
this.mute = this.options.mute;
this.currentVolume = this.options.mute ? 0 : 100;
this.container = options.container;
this.container.setVolume(this.currentVolume);
this.keepVisible = false;
this.addEventListeners();
this.settings = {
left: ['play', 'stop', 'pause'],
right: ['volume'],
default: ['position', 'seekbar', 'duration']
};
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.disabled = false;
if (this.container.mediaControlDisabled || this.options.chromeless) {
this.disable();
}
$(document).bind('mouseup', (function(event) {
return $__0.stopDrag(event);
}));
$(document).bind('mousemove', (function(event) {
return $__0.updateDrag(event);
}));
Mediator.on('player:resize', (function() {
return $__0.playerResize();
}));
};
var $MediaControl = MediaControl;
($traceurRuntime.createClass)(MediaControl, {
get name() {
return 'MediaControl';
},
get attributes() {
return {
class: 'media-control',
'data-media-control': ''
};
},
get events() {
return {
'click [data-play]': 'play',
'click [data-pause]': 'pause',
'click [data-playpause]': 'togglePlayPause',
'click [data-stop]': 'stop',
'click [data-playstop]': 'togglePlayStop',
'click [data-fullscreen]': 'toggleFullscreen',
'click .bar-container[data-seekbar]': 'seek',
'click .bar-container[data-volume]': 'volume',
'click .drawer-icon[data-volume]': 'toggleMute',
'mouseenter .drawer-container[data-volume]': 'showVolumeBar',
'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',
'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',
'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',
'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',
'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',
'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',
'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'
};
},
get template() {
return JST.media_control;
},
addEventListeners: function() {
this.listenTo(this.container, 'container:play', this.changeTogglePlay);
this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar);
this.listenTo(this.container, 'container:progress', this.updateProgressBar);
this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.container, 'container:mediacontrol:disable', this.disable);
this.listenTo(this.container, 'container:mediacontrol:enable', this.enable);
this.listenTo(this.container, 'container:ended', this.ended);
},
disable: function() {
this.disabled = true;
this.hide();
this.$el.hide();
},
enable: function() {
if (this.options.chromeless)
return;
this.disabled = false;
this.show();
},
play: function() {
this.container.play();
},
pause: function() {
this.container.pause();
},
stop: function() {
this.container.stop();
},
changeTogglePlay: function() {
if (this.container.isPlaying()) {
this.$playPauseToggle.removeClass('paused').addClass('playing');
this.$playStopToggle.removeClass('stopped').addClass('playing');
this.trigger('mediacontrol:playing');
} else {
this.$playPauseToggle.removeClass('playing').addClass('paused');
this.$playStopToggle.removeClass('playing').addClass('stopped');
this.trigger('mediacontrol:notplaying');
}
},
mousemoveOnSeekBar: function(event) {
if (this.container.settings.seekEnabled) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);
this.$seekBarHover.css({left: offsetX});
}
this.trigger('mediacontrol:mousemove:seekbar', event);
},
mouseleaveOnSeekBar: function(event) {
this.trigger('mediacontrol:mouseleave:seekbar', event);
},
playerResize: function() {
if (Utils.Fullscreen.isFullscreen()) {
this.$fullscreenToggle.addClass('shrink');
} else {
this.$fullscreenToggle.removeClass('shrink');
}
this.$el.removeClass('w320');
if (PlayerInfo.currentSize.width <= 320) {
this.$el.addClass('w320');
}
},
togglePlayPause: function() {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
this.changeTogglePlay();
},
togglePlayStop: function() {
if (this.container.isPlaying()) {
this.container.stop();
} else {
this.container.play();
}
this.changeTogglePlay();
},
startSeekDrag: function(event) {
if (!this.container.settings.seekEnabled)
return;
this.draggingSeekBar = true;
this.$el.addClass('dragging');
this.$seekBarLoaded.addClass('media-control-notransition');
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (event) {
event.preventDefault();
}
},
startVolumeDrag: function(event) {
this.draggingVolumeBar = true;
this.$el.addClass('dragging');
if (event) {
event.preventDefault();
}
},
stopDrag: function(event) {
if (this.draggingSeekBar) {
this.seek(event);
}
this.$el.removeClass('dragging');
this.$seekBarLoaded.removeClass('media-control-notransition');
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition dragging');
this.draggingSeekBar = false;
this.draggingVolumeBar = false;
},
updateDrag: function(event) {
if (event) {
event.preventDefault();
}
if (this.draggingSeekBar) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.setSeekPercentage(pos);
} else if (this.draggingVolumeBar) {
this.volume(event);
}
},
volume: function(event) {
var offsetY = event.pageX - this.$volumeBarContainer.offset().left;
this.currentVolume = (offsetY / this.$volumeBarContainer.width()) * 100;
this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0));
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
},
toggleMute: function() {
if (this.mute) {
if (this.currentVolume <= 0) {
this.currentVolume = 100;
}
this.setVolume(this.currentVolume);
} else {
this.setVolume(0);
}
},
setVolume: function(value) {
this.container.setVolume(value);
this.setVolumeLevel(value);
if (value === 0) {
this.mute = true;
} else {
this.mute = false;
}
},
toggleFullscreen: function() {
this.trigger('mediacontrol:fullscreen', this.name);
this.container.fullscreen();
this.resetKeepVisible();
},
setContainer: function(container) {
this.stopListening(this.container);
this.container = container;
this.changeTogglePlay();
this.addEventListeners();
this.settingsUpdate();
this.container.trigger('container:dvr', this.container.isDvrInUse());
this.container.setVolume(this.currentVolume);
if (this.container.mediaControlDisabled) {
this.disable();
}
this.trigger("mediacontrol:containerchanged");
},
showVolumeBar: function() {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.$volumeBarContainer.removeClass('volume-bar-hide');
},
hideVolumeBar: function() {
var $__0 = this;
var timeout = 400;
if (!this.$volumeBarContainer)
return;
if (this.draggingVolumeBar) {
this.hideVolumeId = setTimeout((function() {
return $__0.hideVolumeBar();
}), timeout);
} else {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.hideVolumeId = setTimeout((function() {
return $__0.$volumeBarContainer.addClass('volume-bar-hide');
}), timeout);
}
},
ended: function() {
this.changeTogglePlay();
},
updateProgressBar: function(startPosition, endPosition, duration) {
var loadedStart = startPosition / duration * 100;
var loadedEnd = endPosition / duration * 100;
this.$seekBarLoaded.css({
left: loadedStart + '%',
width: (loadedEnd - loadedStart) + '%'
});
},
updateSeekBar: function(position, duration) {
if (this.draggingSeekBar)
return;
if (position < 0)
position = duration;
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
var seekbarValue = (100 / duration) * position;
this.setSeekPercentage(seekbarValue);
this.$('[data-position]').html(Utils.formatTime(position));
this.$('[data-duration]').html(Utils.formatTime(duration));
},
seek: function(event) {
if (!this.container.settings.seekEnabled)
return;
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.container.setCurrentTime(pos);
this.setSeekPercentage(pos);
return false;
},
setKeepVisible: function() {
this.keepVisible = true;
},
resetKeepVisible: function() {
this.keepVisible = false;
},
isVisible: function() {
return !this.$el.hasClass('media-control-hide');
},
show: function(event) {
var $__0 = this;
if (this.disabled || this.isVisible() || this.container.getPlaybackType() === null)
return;
var timeout = 2000;
if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {
if (this.hideId) {
clearTimeout(this.hideId);
}
this.$el.show();
this.trigger('mediacontrol:show', this.name);
this.$el.removeClass('media-control-hide');
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (event) {
this.lastMouseX = event.clientX;
this.lastMouseY = event.clientY;
}
}
},
hide: function() {
var $__0 = this;
var timeout = 2000;
if (this.hideId) {
clearTimeout(this.hideId);
}
if (!this.isVisible())
return;
if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) {
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
} else {
this.trigger('mediacontrol:hide', this.name);
this.$el.addClass('media-control-hide');
this.hideVolumeBar();
}
},
settingsUpdate: function() {
if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) {
this.settings = this.container.settings;
this.render();
this.enable();
} else {
this.disable();
}
},
highDefinitionUpdate: function() {
if (this.container.isHighDefinitionInUse()) {
this.$el.find('button[data-hd-indicator]').addClass("enabled");
} else {
this.$el.find('button[data-hd-indicator]').removeClass("enabled");
}
},
createCachedElements: function() {
this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');
this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');
this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]');
this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');
this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');
this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');
this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');
this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');
this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');
this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');
},
setVolumeLevel: function(value) {
var $__0 = this;
if (!this.container.isReady) {
this.listenToOnce(this.container, "container:ready", (function() {
return $__0.setVolumeLevel(value);
}));
} else {
this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill');
var item = Math.ceil(value / 10.0);
this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill');
if (value > 0) {
this.$volumeIcon.removeClass('muted');
} else {
this.$volumeIcon.addClass('muted');
}
}
},
setSeekPercentage: function(value) {
if (value > 100)
return;
var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);
this.currentSeekPercentage = value;
this.$seekBarPosition.css({width: value + '%'});
this.$seekBarScrubber.css({left: pos});
},
bindKeyEvents: function() {
var $__0 = this;
Mousetrap.bind(['space'], (function() {
return $__0.togglePlayPause();
}));
},
parseColors: function() {
if (this.options.mediacontrol) {
var buttonsColor = this.options.mediacontrol.buttons;
var seekbarColor = this.options.mediacontrol.seekbar;
this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor);
this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor);
this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', "inset 2px 0 0 " + buttonsColor);
}
},
render: function() {
var $__0 = this;
var timeout = 1000;
var style = Styler.getStyleFor('media_control');
this.$el.html(this.template({settings: this.settings}));
this.$el.append(style);
this.createCachedElements();
this.$playPauseToggle.addClass('paused');
this.$playStopToggle.addClass('stopped');
this.changeTogglePlay();
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (this.disabled) {
this.hide();
}
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (!this.currentSeekPercentage) {
this.currentSeekPercentage = 0;
}
this.setSeekPercentage(this.currentSeekPercentage);
this.$el.ready((function() {
if (!$__0.container.settings.seekEnabled) {
$__0.$seekBarContainer.addClass('seek-disabled');
}
$__0.setVolumeLevel($__0.currentVolume);
$__0.bindKeyEvents();
$__0.hideVolumeBar();
}));
this.parseColors();
this.seekTime.render();
this.trigger('mediacontrol:rendered');
return this;
}
}, {}, UIObject);
module.exports = MediaControl;
},{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"../seek_time":24,"jquery":"jquery","mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":6}],23:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CoreFactory = require('./core_factory');
var Loader = require('./loader');
var _ = require('underscore');
var ScrollMonitor = require('scrollmonitor');
var PlayerInfo = require('player_info');
var Player = function Player(options) {
$traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]);
window.p = this;
this.options = options;
this.options.sources = this.normalizeSources(options);
this.loader = new Loader(this.options.plugins || []);
this.coreFactory = new CoreFactory(this, this.loader);
options.height || (options.height = 360);
options.width || (options.width = 640);
PlayerInfo.currentSize = {
width: options.width,
height: options.height
};
};
var $Player = Player;
($traceurRuntime.createClass)(Player, {
attachTo: function(element) {
this.options.parentElement = element;
this.core = this.coreFactory.create();
if (this.options.autoPlayVisible) {
this.bindAutoPlayVisible(this.options.autoPlayVisible);
}
},
bindAutoPlayVisible: function(option) {
var $__0 = this;
this.elementWatcher = ScrollMonitor.create(this.core.$el);
if (option === 'full') {
this.elementWatcher.fullyEnterViewport((function() {
return $__0.enterViewport();
}));
} else if (option === 'partial') {
this.elementWatcher.enterViewport((function() {
return $__0.enterViewport();
}));
}
},
enterViewport: function() {
if (this.elementWatcher.top !== 0 && !this.isPlaying()) {
this.play();
}
},
normalizeSources: function(options) {
return _.compact(_.flatten([options.source, options.sources]));
},
resize: function(size) {
this.core.resize(size);
},
load: function(sources) {
this.core.load(sources);
},
destroy: function() {
this.core.destroy();
},
play: function() {
this.core.mediaControl.container.play();
},
pause: function() {
this.core.mediaControl.container.pause();
},
stop: function() {
this.core.mediaControl.container.stop();
},
seek: function(time) {
this.core.mediaControl.container.setCurrentTime(time);
},
setVolume: function(volume) {
this.core.mediaControl.container.setVolume(volume);
},
mute: function() {
this.core.mediaControl.container.setVolume(0);
},
unmute: function() {
this.core.mediaControl.container.setVolume(100);
},
isPlaying: function() {
return this.core.mediaControl.container.isPlaying();
}
}, {}, BaseObject);
module.exports = Player;
},{"./core_factory":17,"./loader":20,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":6}],24:[function(require,module,exports){
"use strict";
module.exports = require('./seek_time');
},{"./seek_time":25}],25:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var formatTime = require('../../base/utils').formatTime;
var SeekTime = function SeekTime(mediaControl) {
$traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []);
this.mediaControl = mediaControl;
this.addEventListeners();
};
var $SeekTime = SeekTime;
($traceurRuntime.createClass)(SeekTime, {
get name() {
return 'seek_time';
},
get template() {
return JST.seek_time;
},
get attributes() {
return {
'class': 'seek-time hidden',
'data-seek-time': ''
};
},
addEventListeners: function() {
this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime);
this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime);
},
showTime: function(event) {
var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left;
var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0));
var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2);
pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width());
var currentTime = timePosition * this.mediaControl.container.getDuration() / 100;
var options = {
timestamp: currentTime,
formattedTime: formatTime(currentTime),
pointerPosition: pointerPosition
};
this.update(options);
},
hideTime: function() {
this.$el.addClass('hidden');
this.$el.css('left', '-100%');
},
update: function(options) {
if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) {
this.$el.find('[data-seek-time]').text(options.formattedTime);
this.$el.css('left', options.pointerPosition);
this.$el.removeClass('hidden');
}
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.mediaControl.$el.append(this.el);
}
}, {}, UIObject);
module.exports = SeekTime;
},{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"ui_object":"ui_object"}],26:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('mediator');
var _ = require('underscore');
var $ = require('jquery');
var Browser = require('browser');
var Mousetrap = require('mousetrap');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var Flash = function Flash(options) {
$traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]);
this.src = options.src;
this.isRTMP = (this.src.indexOf("rtmp") > -1);
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf";
this.autoPlay = options.autoPlay;
this.settings = {default: ['seekbar']};
if (this.isRTMP) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
this.isReady = false;
this.addListeners();
};
var $Flash = Flash;
($traceurRuntime.createClass)(Flash, {
get name() {
return 'flash';
},
get tagName() {
return 'object';
},
get template() {
return JST.flash;
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
if (this.currentState === 'PLAYING') {
this.firstPlay();
} else {
this.currentState = "IDLE";
this.autoPlay && this.play();
}
$('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el);
this.trigger('playback:ready', this.name);
},
getPlaybackType: function() {
return this.isRTMP ? 'live' : 'vod';
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-flash', '');
this.setElement($el[0]);
},
isHighDefinitionInUse: function() {
return false;
},
updateTime: function() {
this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name);
},
addListeners: function() {
Mediator.on(this.uniqueId + ':progress', this.progress, this);
Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this);
Mediator.on(this.uniqueId + ':statechanged', this.checkState, this);
Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this);
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
stopListening: function() {
$traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':progress');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':statechanged');
Mediator.off(this.uniqueId + ':flashready');
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.unbind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
checkState: function() {
if (this.currentState === "PAUSED") {
return;
} else if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") {
this.trigger('playback:buffering', this.name);
this.currentState = "PLAYING_BUFFERING";
} else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") {
this.trigger('playback:bufferfull', this.name);
this.currentState = "PLAYING";
} else if (this.el.getState() === "IDLE") {
this.currentState = "IDLE";
} else if (this.el.getState() === "ENDED") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name);
this.currentState = "ENDED";
}
},
progress: function() {
if (this.currentState !== "IDLE" && this.currentState !== "ENDED") {
this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);
}
},
firstPlay: function() {
var $__0 = this;
this.currentState = "PLAYING";
if (_.isFunction(this.el.playerPlay)) {
this.el.playerPlay(this.src);
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.checkInitialSeek();
}));
}
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
play: function() {
if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') {
this.currentState = "PLAYING";
this.el.playerResume();
} else if (this.el.getState() !== 'PLAYING') {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.playerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
this.currentState = "PAUSED";
this.el.playerPause();
},
stop: function() {
this.el.playerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
return !!(this.isReady && this.currentState === "PLAYING");
},
getDuration: function() {
return this.el.getDuration();
},
seek: function(seekBarValue) {
var seekTo = this.el.getDuration() * (seekBarValue / 100);
this.seekSeconds(seekTo);
},
seekSeconds: function(seekTo) {
this.el.playerSeek(seekTo);
this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name);
if (this.currentState === "PAUSED") {
this.el.playerPause();
}
},
destroy: function() {
clearInterval(this.bootstrapId);
this.stopListening();
this.$el.remove();
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isLegacyIE) {
this.setupIE();
}
this.$el.append(style);
return this;
}
}, {}, Playback);
Flash.canPlay = function(resource) {
if (resource.indexOf('rtmp') > -1) {
return true;
} else if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) {
return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/);
} else {
return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/);
}
};
module.exports = Flash;
},{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"browser":"browser","jquery":"jquery","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":6}],27:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var _ = require("underscore");
var Mediator = require('mediator');
var Browser = require('browser');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var HLS = function HLS(options) {
$traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]);
this.src = options.src;
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf";
this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache;
this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage;
this.highDefinition = false;
this.autoPlay = options.autoPlay;
this.defaultSettings = {
left: ["playstop"],
default: ['seekbar'],
right: ["fullscreen", "volume", "hd-indicator"],
seekEnabled: false
};
this.settings = _.extend({}, this.defaultSettings);
this.playbackType = 'live';
this.addListeners();
};
var $HLS = HLS;
($traceurRuntime.createClass)(HLS, {
get name() {
return 'hls';
},
get tagName() {
return 'object';
},
get template() {
return JST.hls;
},
get attributes() {
return {
'class': 'hls-playback',
'data-hls': '',
'type': 'application/x-shockwave-flash'
};
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':playbackstate', (function(state) {
return $__0.setPlaybackState(state);
}));
Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {
return $__0.updateHighDefinition(isHD);
}));
Mediator.on(this.uniqueId + ':playbackerror', (function() {
return $__0.flashPlaybackError();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':flashready');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':playbackstate');
Mediator.off(this.uniqueId + ':highdefinition');
Mediator.off(this.uniqueId + ':playbackerror');
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger('playback:ready', this.name);
this.currentState = "IDLE";
this.setFlashSettings();
this.autoPlay && this.play();
},
setFlashSettings: function() {
this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache);
this.el.globoPlayerCapLeveltoStage(this.capLevelToStage);
this.el.globoPlayerSetmaxBufferLength(0);
},
updateHighDefinition: function(isHD) {
this.highDefinition = (isHD === "true");
this.trigger('playback:highdefinitionupdate');
this.trigger('playback:bitrate', {'bitrate': this.getCurrentBitrate()});
},
updateTime: function() {
var duration = this.getDuration();
var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration);
var previousDVRStatus = this.dvrEnabled;
var livePlayback = (this.playbackType === 'live');
this.dvrEnabled = (livePlayback && duration > 240);
if (duration === 100 || livePlayback === undefined) {
return;
}
if (this.dvrEnabled !== previousDVRStatus) {
this.updateSettings();
this.trigger('playback:settingsupdate', this.name);
}
if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {
position = duration;
}
this.trigger('playback:timeupdate', position, duration, this.name);
},
play: function() {
if (this.currentState === 'PAUSED') {
this.el.globoPlayerResume();
} else if (this.currentState !== "PLAYING") {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
getPlaybackType: function() {
return this.playbackType ? this.playbackType : null;
},
getCurrentBitrate: function() {
var currentLevel = this.getLevels()[this.el.globoGetLevel()];
return currentLevel.bitrate;
},
getLastProgramDate: function() {
var programDate = this.el.globoGetLastProgramDate();
return programDate - 1.08e+7;
},
isHighDefinitionInUse: function() {
return this.highDefinition;
},
getLevels: function() {
if (!this.levels || this.levels.length === 0) {
this.levels = this.el.globoGetLevels();
}
return this.levels;
},
setPlaybackState: function(state) {
var bufferLength = this.el.globoGetbufferLength();
if (state === "PLAYING_BUFFERING" && bufferLength < 1) {
this.trigger('playback:buffering', this.name);
this.updateCurrentState(state);
} else if (state === "PLAYING") {
if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) {
this.trigger('playback:bufferfull', this.name);
this.updateCurrentState(state);
}
} else if (state === "PAUSED") {
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name);
this.updateCurrentState(state);
}
this.lastBufferLength = bufferLength;
},
updateCurrentState: function(state) {
this.currentState = state;
this.updatePlaybackType();
},
updatePlaybackType: function() {
this.playbackType = this.el.globoGetType();
if (this.playbackType) {
this.playbackType = this.playbackType.toLowerCase();
if (this.playbackType === 'vod') {
this.startReportingProgress();
} else {
this.stopReportingProgress();
}
}
this.trigger('playback:playbackstate');
},
startReportingProgress: function() {
if (!this.reportingProgress) {
this.reportingProgress = true;
Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded);
}
},
stopReportingProgress: function() {
Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this);
},
onFragmentLoaded: function() {
var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength();
this.trigger('playback:progress', this.el.globoGetPosition(), buffered, this.getDuration(), this.name);
},
firstPlay: function() {
this.el.globoPlayerLoad(this.src);
this.el.globoPlayerPlay();
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.globoPlayerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
if (this.playbackType !== 'live' || this.dvrEnabled) {
this.el.globoPlayerPause();
if (this.playbackType === 'live' && this.dvrEnabled) {
this.updateDvr(true);
}
}
},
stop: function() {
this.el.globoPlayerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
if (this.currentState) {
return !!(this.currentState.match(/playing/i));
}
return false;
},
getDuration: function() {
var duration = this.el.globoGetDuration();
if (this.playbackType === 'live') {
duration = duration - 10;
}
return duration;
},
seek: function(time) {
var duration = this.getDuration();
if (time > 0) {
time = duration * time / 100;
}
if (this.playbackType === 'live') {
var dvrInUse = (time >= 0 && duration - time > 5);
if (!dvrInUse) {
time = -1;
}
this.updateDvr(dvrInUse);
}
this.el.globoPlayerSeek(time);
this.trigger('playback:timeupdate', time, duration, this.name);
},
updateDvr: function(dvrInUse) {
var previousDvrInUse = !!this.dvrInUse;
this.dvrInUse = dvrInUse;
if (this.dvrInUse !== previousDvrInUse) {
this.updateSettings();
this.trigger('playback:dvr', this.dvrInUse);
this.trigger('playback:stats:add', {'dvr': this.dvrInUse});
}
},
flashPlaybackError: function() {
this.trigger('playback:stop');
},
timeUpdate: function(time, duration) {
this.trigger('playback:timeupdate', time, duration, this.name);
},
destroy: function() {
this.stopListening();
this.$el.remove();
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-hls', '');
this.setElement($el);
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
updateSettings: function() {
this.settings = _.extend({}, this.defaultSettings);
if (this.playbackType === "vod" || this.dvrInUse) {
this.settings.left = ["playpause", "position", "duration"];
this.settings.seekEnabled = true;
} else if (this.dvrEnabled) {
this.settings.left = ["playpause"];
this.settings.seekEnabled = true;
} else {
this.settings.seekEnabled = false;
}
},
setElement: function(element) {
this.$el = element;
this.el = element[0];
},
render: function() {
var style = Styler.getStyleFor(this.name);
if (Browser.isLegacyIE) {
this.setupIE();
} else {
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isIE) {
this.$('embed').remove();
}
}
this.el.id = this.cid;
this.$el.append(style);
return this;
}
}, {}, Playback);
HLS.canPlay = function(resource) {
return !!resource.match(/^http(.*).m3u8?/);
};
module.exports = HLS;
},{"../../base/jst":9,"../../base/styler":10,"browser":"browser","mediator":"mediator","playback":"playback","underscore":6}],28:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var HTML5Audio = function HTML5Audio(params) {
$traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]);
this.el.src = params.src;
this.settings = {
left: ['playpause', 'position', 'duration'],
right: ['fullscreen', 'volume'],
default: ['seekbar']
};
this.render();
params.autoPlay && this.play();
};
var $HTML5Audio = HTML5Audio;
($traceurRuntime.createClass)(HTML5Audio, {
get name() {
return 'html5_audio';
},
get tagName() {
return 'audio';
},
get events() {
return {
'timeupdate': 'timeUpdated',
'ended': 'ended'
};
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.play);
this.listenTo(this.container, 'container:pause', this.pause);
this.listenTo(this.container, 'container:seek', this.seek);
this.listenTo(this.container, 'container:volume', this.volume);
this.listenTo(this.container, 'container:stop', this.stop);
},
getPlaybackType: function() {
return "aod";
},
play: function() {
this.el.play();
this.trigger('playback:play');
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger('container:timeupdate', 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
timeUpdated: function() {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
},
render: function() {
return this;
}
}, {}, Playback);
HTML5Audio.canPlay = function(resource) {
return !!resource.match(/(.*).mp3/);
};
module.exports = HTML5Audio;
},{"playback":"playback"}],29:[function(require,module,exports){
(function (process){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('browser');
var Mousetrap = require('mousetrap');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var _ = require('underscore');
var HTML5Video = function HTML5Video(options) {
$traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]);
this.options = options;
this.src = options.src;
this.el.src = options.src;
this.el.loop = options.loop;
this.firstBuffer = true;
this.isHLS = (this.src.indexOf('m3u8') > -1);
this.settings = {default: ['seekbar']};
if (this.isHLS) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
this.bindEvents();
};
var $HTML5Video = HTML5Video;
($traceurRuntime.createClass)(HTML5Video, {
get name() {
return 'html5_video';
},
get tagName() {
return 'video';
},
get template() {
return JST.html5_video;
},
get attributes() {
return {'data-html5-video': ''};
},
get events() {
return {
'timeupdate': 'timeUpdated',
'progress': 'progress',
'ended': 'ended',
'stalled': 'stalled',
'waiting': 'waiting',
'canplaythrough': 'bufferFull',
'loadedmetadata': 'loadedMetadata'
};
},
bindEvents: function() {
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
loadedMetadata: function(e) {
this.trigger('playback:loadedmetadata', e.target.duration);
this.trigger('playback:settingsupdate');
this.checkInitialSeek();
},
getPlaybackType: function() {
return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod';
},
isHighDefinitionInUse: function() {
return false;
},
play: function() {
this.el.play();
this.trigger('playback:play');
if (this.isHLS) {
this.trigger('playback:timeupdate', 1, 1, this.name);
}
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
if (this.el.readyState !== 0) {
this.el.currentTime = 0;
}
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
ended: function() {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.duration, this.name);
},
stalled: function() {
if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger('playback:buffering', this.name);
}
},
waiting: function() {
if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger('playback:buffering', this.name);
}
},
bufferFull: function() {
if (this.getPlaybackType() === 'vod' && this.options.poster && this.firstBuffer) {
this.firstBuffer = false;
this.el.poster = this.options.poster;
} else {
this.el.poster = '';
}
this.trigger('playback:bufferfull', this.name);
},
destroy: function() {
this.stop();
this.el.src = '';
this.$el.remove();
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.seekSeconds(time);
},
seekSeconds: function(time) {
this.el.currentTime = time;
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
if (this.getPlaybackType() !== 'live') {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
}
},
progress: function() {
if (!this.el.buffered.length)
return;
var bufferedPos = 0;
for (var i = 0; i < this.el.buffered.length; i++) {
if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
bufferedPos = i;
break;
}
}
this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
},
typeFor: function(src) {
return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
src: this.src,
type: this.typeFor(this.src)
}));
this.$el.append(style);
this.trigger('playback:ready', this.name);
process.nextTick((function() {
return $__0.options.autoPlay && $__0.play();
}));
return this;
}
}, {}, Playback);
HTML5Video.canPlay = function(resource) {
if (Browser.isChrome || Browser.isFirefox || Browser.isIE) {
return (!!resource.match(/(.*).(mp4|webm)/));
} else if (Browser.isSafari || Browser.isMobile || Browser.isWin8App || Browser.isLegacyIE) {
return (!!resource.match(/(.*).mp4/));
}
};
module.exports = HTML5Video;
}).call(this,require('_process'))
},{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"_process":2,"browser":"browser","mousetrap":4,"playback":"playback","underscore":6}],30:[function(require,module,exports){
"use strict";
module.exports = require('./no_op');
},{"./no_op":31}],31:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var NoOp = function NoOp(options) {
$traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]);
};
var $NoOp = NoOp;
($traceurRuntime.createClass)(NoOp, {
get name() {
return 'no_op';
},
get template() {
return JST.no_op;
},
get attributes() {
return {'data-no-op': ''};
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
return this;
}
}, {}, Playback);
NoOp.canPlay = (function(source) {
return true;
});
module.exports = NoOp;
},{"../../base/jst":9,"../../base/styler":10,"playback":"playback"}],32:[function(require,module,exports){
(function (process){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('browser');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var BackgroundButton = function BackgroundButton(core) {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $BackgroundButton = BackgroundButton;
($traceurRuntime.createClass)(BackgroundButton, {
get template() {
return JST.background_button;
},
get name() {
return 'background_button';
},
get attributes() {
return {
'class': 'background-button',
'data-background-button': ''
};
},
get events() {
return {'click .background-button-icon': 'click'};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide);
this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show);
this.listenTo(this.core.mediaControl, 'mediacontrol:rendered', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.updateSize);
this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing);
this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying);
Mediator.on('player:resize', this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []);
Mediator.off('player:resize', this.updateSize, this);
},
settingsUpdate: function() {
this.stopListening();
if (this.shouldRender()) {
this.render();
this.bindEvents();
if (this.core.mediaControl.container.isPlaying()) {
this.playing();
} else {
this.notplaying();
}
} else {
this.$el.remove();
this.$playPauseButton.show();
this.$playStopButton.show();
this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate);
}
},
shouldRender: function() {
var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton;
return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0);
},
click: function() {
this.core.mediaControl.show();
if (this.shouldStop) {
this.core.mediaControl.togglePlayStop();
} else {
this.core.mediaControl.togglePlayPause();
}
},
show: function() {
this.$el.removeClass('hide');
},
hide: function() {
this.$el.addClass('hide');
},
enable: function() {
this.stopListening();
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []);
this.settingsUpdate();
},
disable: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []);
this.$playPauseButton.show();
this.$playStopButton.show();
},
playing: function() {
this.$buttonIcon.removeClass('notplaying').addClass('playing');
},
notplaying: function() {
this.$buttonIcon.removeClass('playing').addClass('notplaying');
},
getExternalInterface: function() {},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)});
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]');
this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]');
this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]');
this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]');
this.shouldStop = this.$playStopButton.length > 0;
this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]'));
this.$el.click((function() {
return $__0.click($__0.$el);
}));
process.nextTick((function() {
return $__0.updateSize();
}));
if (this.core.options.useBackgroundButton) {
this.$playPauseButton.hide();
this.$playStopButton.hide();
}
if (this.shouldStop) {
this.$buttonIcon.addClass('playstop');
}
if (this.core.mediaControl.isVisible()) {
this.show();
}
return this;
}
}, {}, UICorePlugin);
module.exports = BackgroundButton;
}).call(this,require('_process'))
},{"../../base/jst":9,"../../base/styler":10,"_process":2,"browser":"browser","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],33:[function(require,module,exports){
"use strict";
module.exports = require('./background_button');
},{"./background_button":32}],34:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var ClickToPausePlugin = function ClickToPausePlugin() {
$traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments);
};
var $ClickToPausePlugin = ClickToPausePlugin;
($traceurRuntime.createClass)(ClickToPausePlugin, {
get name() {
return 'click_to_pause';
},
bindEvents: function() {
this.listenTo(this.container, 'container:click', this.click);
this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate);
},
click: function() {
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
}
},
settingsUpdate: function() {
this.container.$el.removeClass('pointer-enabled');
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
this.container.$el.addClass('pointer-enabled');
}
}
}, {}, ContainerPlugin);
module.exports = ClickToPausePlugin;
},{"container_plugin":"container_plugin"}],35:[function(require,module,exports){
"use strict";
module.exports = require('./click_to_pause');
},{"./click_to_pause":34}],36:[function(require,module,exports){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var DVRControls = function DVRControls(core) {
$traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $DVRControls = DVRControls;
($traceurRuntime.createClass)(DVRControls, {
get template() {
return JST.dvr_controls;
},
get name() {
return 'dvr_controls';
},
get events() {
return {'click .live-button': 'click'};
},
get attributes() {
return {
'class': 'dvr-controls',
'data-dvr-controls': ''
};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl, 'mediacontrol:rendered', this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, 'container:dvr', this.dvrChanged);
},
dvrChanged: function(dvrEnabled) {
this.settingsUpdate();
this.core.mediaControl.$el.addClass('live');
if (dvrEnabled) {
this.core.mediaControl.$el.addClass('dvr');
this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide();
} else {
this.core.mediaControl.$el.removeClass('dvr');
}
},
click: function() {
if (!this.core.mediaControl.container.isPlaying()) {
this.core.mediaControl.container.play();
}
if (this.core.mediaControl.$el.hasClass('dvr')) {
this.core.mediaControl.container.setCurrentTime(-1);
}
},
settingsUpdate: function() {
var $__0 = this;
this.stopListening();
if (this.shouldRender()) {
this.render();
this.$el.click((function() {
return $__0.click();
}));
}
this.bindEvents();
},
shouldRender: function() {
var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls;
return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live';
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
if (this.shouldRender()) {
this.core.mediaControl.$el.addClass('live');
this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el);
if (this.$duration) {
this.$duration.remove();
}
this.$duration = $('<span data-duration></span>');
this.core.mediaControl.seekTime.$el.append(this.$duration);
}
return this;
}
}, {}, UICorePlugin);
module.exports = DVRControls;
},{"../../base/jst":9,"../../base/styler":10,"ui_core_plugin":"ui_core_plugin"}],37:[function(require,module,exports){
"use strict";
module.exports = require('./dvr_controls');
},{"./dvr_controls":36}],38:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var GoogleAnalytics = function GoogleAnalytics(options) {
$traceurRuntime.superCall(this, $GoogleAnalytics.prototype, "constructor", [options]);
if (options.gaAccount) {
this.embedScript();
this.account = options.gaAccount;
this.trackerName = options.gaTrackerName + "." || 'Clappr.';
this.currentHDState = undefined;
}
};
var $GoogleAnalytics = GoogleAnalytics;
($traceurRuntime.createClass)(GoogleAnalytics, {
get name() {
return 'google_analytics';
},
embedScript: function() {
var $__0 = this;
if (!window._gat) {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("async", "async");
script.setAttribute("src", "http://www.google-analytics.com/ga.js");
script.onload = (function() {
return $__0.addEventListeners();
});
document.body.appendChild(script);
} else {
this.addEventListeners();
}
},
addEventListeners: function() {
var $__0 = this;
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:pause', this.onPause);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:ended', this.onEnded);
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:error', this.onError);
this.listenTo(this.container, 'container:playbackstate', this.onPlaybackChanged);
this.listenTo(this.container, 'container:volume', (function(event) {
return $__0.onVolumeChanged(event);
}));
this.listenTo(this.container, 'container:seek', (function(event) {
return $__0.onSeek(event);
}));
this.listenTo(this.container, 'container:fullscreen', this.onFullscreen);
this.listenTo(this.container, 'container:highdefinitionupdate', this.onHD);
this.listenTo(this.container.playback, 'playback:dvr', this.onDVR);
_gaq.push([this.trackerName + '_setAccount', this.account]);
},
onPlay: function() {
this.push(["Video", "Play", this.container.playback.src]);
},
onStop: function() {
this.push(["Video", "Stop", this.container.playback.src]);
},
onEnded: function() {
this.push(["Video", "Ended", this.container.playback.src]);
},
onBuffering: function() {
this.push(["Video", "Buffering", this.container.playback.src]);
},
onBufferFull: function() {
this.push(["Video", "Bufferfull", this.container.playback.src]);
},
onError: function() {
this.push(["Video", "Error", this.container.playback.src]);
},
onHD: function() {
var status = this.container.isHighDefinitionInUse() ? "ON" : "OFF";
if (status !== this.currentHDState) {
this.currentHDState = status;
this.push(["Video", "HD - " + status, this.container.playback.src]);
}
},
onPlaybackChanged: function() {
var type = this.container.getPlaybackType();
if (type !== null) {
this.push(["Video", "Playback Type - " + type, this.container.playback.src]);
}
},
onDVR: function() {
var status = this.container.isHighDefinitionInUse();
this.push(["Interaction", "DVR - " + status, this.container.playback.src]);
},
onPause: function() {
this.push(["Video", "Pause", this.container.playback.src]);
},
onSeek: function() {
this.push(["Video", "Seek", this.container.playback.src]);
},
onVolumeChanged: function() {
this.push(["Interaction", "Volume", this.container.playback.src]);
},
onFullscreen: function() {
this.push(["Interaction", "Fullscreen", this.container.playback.src]);
},
push: function(array) {
var res = [this.trackerName + "_trackEvent"].concat(array);
_gaq.push(res);
}
}, {}, ContainerPlugin);
module.exports = GoogleAnalytics;
},{"container_plugin":"container_plugin"}],39:[function(require,module,exports){
"use strict";
module.exports = require('./google_analytics');
},{"./google_analytics":38}],40:[function(require,module,exports){
"use strict";
module.exports = require('./log');
},{"./log":41}],41:[function(require,module,exports){
"use strict";
var Mousetrap = require('mousetrap');
var _ = require('underscore');
var Log = function Log() {
var $__0 = this;
Mousetrap.bind(['ctrl+shift+d'], (function() {
return $__0.onOff();
}));
this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
};
($traceurRuntime.createClass)(Log, {
info: function(klass, message) {
this.log(klass, 'info', message);
},
warn: function(klass, message) {
this.log(klass, 'warn', message);
},
debug: function(klass, message) {
this.log(klass, 'debug', message);
},
onOff: function() {
window.DEBUG = !window.DEBUG;
if (window.DEBUG) {
console.log('log enabled');
} else {
console.log('log disabled');
}
},
log: function(klass, level, message) {
if (!window.DEBUG || _.contains(this.BLACKLIST, message))
return;
var color;
if (level === 'warn') {
color = '#FF8000';
} else if (level === 'info') {
color = '#006600';
} else if (level === 'error') {
color = '#FF0000';
}
console.log("%c [" + klass + "] [" + level + "] " + message, 'color: ' + color);
}
}, {});
Log.getInstance = function() {
if (this._instance === undefined) {
this._instance = new this();
}
return this._instance;
};
module.exports = Log;
},{"mousetrap":4,"underscore":6}],42:[function(require,module,exports){
"use strict";
module.exports = require('./poster');
},{"./poster":43}],43:[function(require,module,exports){
(function (process){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var $ = require('jquery');
var _ = require('underscore');
var PosterPlugin = function PosterPlugin(options) {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]);
this.options = options;
_.defaults(this.options, {disableControlsOnPoster: true});
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
this.render();
};
var $PosterPlugin = PosterPlugin;
($traceurRuntime.createClass)(PosterPlugin, {
get name() {
return 'poster';
},
get template() {
return JST.poster;
},
get attributes() {
return {
'class': 'player-poster',
'data-poster': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferfull);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:ended', this.onStop);
Mediator.on('player:resize', this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []);
Mediator.off('player:resize', this.updateSize, this);
},
onBuffering: function() {
this.hidePlayButton();
},
onBufferfull: function() {
this.$el.hide();
if (this.options.disableControlsOnPoster) {
this.container.enableMediaControl();
}
},
onStop: function() {
this.$el.show();
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
if (!this.options.hidePlayButton) {
this.showPlayButton();
}
},
hidePlayButton: function() {
this.$playButton.hide();
},
showPlayButton: function() {
this.$playButton.show();
this.updateSize();
},
clicked: function() {
this.container.play();
return false;
},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
if (this.$playWrapper.is(':visible')) {
this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)});
if (!this.options.hidePlayButton) {
this.$playButton.show();
}
} else {
this.$playButton.hide();
}
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playButton = this.$el.find('.poster-icon');
this.$playWrapper = this.$el.find('.play-wrapper');
if (this.options.poster !== undefined) {
var imgEl = $('<img data-poster class="poster-background"></img>');
imgEl.attr('src', this.options.poster);
this.$el.prepend(imgEl);
}
this.container.$el.append(this.el);
if (!!this.options.hidePlayButton) {
this.hidePlayButton();
}
process.nextTick((function() {
return $__0.updateSize();
}));
return this;
}
}, {}, UIContainerPlugin);
module.exports = PosterPlugin;
}).call(this,require('_process'))
},{"../../base/jst":9,"../../base/styler":10,"_process":2,"jquery":"jquery","mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":6}],44:[function(require,module,exports){
"use strict";
module.exports = require('./spinner_three_bounce');
},{"./spinner_three_bounce":45}],45:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {
$traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]);
this.template = JST.spinner_three_bounce;
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stop', this.onStop);
this.render();
};
var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;
($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {
get name() {
return 'spinner';
},
get attributes() {
return {
'data-spinner': '',
'class': 'spinner-three-bounce'
};
},
onBuffering: function() {
this.$el.show();
},
onBufferFull: function() {
this.$el.hide();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.html(this.template());
var style = Styler.getStyleFor('spinner_three_bounce');
this.container.$el.append(style);
this.container.$el.append(this.$el);
this.$el.hide();
return this;
}
}, {}, UIContainerPlugin);
module.exports = SpinnerThreeBouncePlugin;
},{"../../base/jst":9,"../../base/styler":10,"ui_container_plugin":"ui_container_plugin"}],46:[function(require,module,exports){
"use strict";
module.exports = require('./stats');
},{"./stats":47}],47:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var $ = require("jquery");
var StatsPlugin = function StatsPlugin(options) {
$traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]);
this.setInitialAttrs();
this.reportInterval = options.reportInterval || 5000;
this.state = "IDLE";
};
var $StatsPlugin = StatsPlugin;
($traceurRuntime.createClass)(StatsPlugin, {
get name() {
return 'stats';
},
bindEvents: function() {
this.listenTo(this.container.playback, 'playback:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:destroyed', this.onStop);
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stats:add', this.onStatsAdd);
this.listenTo(this.container, 'container:bitrate', this.onStatsAdd);
this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd);
},
setInitialAttrs: function() {
this.firstPlay = true;
this.startupTime = 0;
this.rebufferingTime = 0;
this.watchingTime = 0;
this.rebuffers = 0;
this.externalMetrics = {};
},
onPlay: function() {
this.state = "PLAYING";
this.watchingTimeInit = Date.now();
if (!this.intervalId) {
this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
}
},
onStop: function() {
clearInterval(this.intervalId);
this.intervalId = undefined;
this.state = "STOPPED";
},
onBuffering: function() {
if (this.firstPlay) {
this.startupTimeInit = Date.now();
} else {
this.rebufferingTimeInit = Date.now();
}
this.state = "BUFFERING";
this.rebuffers++;
},
onBufferFull: function() {
if (this.firstPlay && !!this.startupTimeInit) {
this.firstPlay = false;
this.startupTime = Date.now() - this.startupTimeInit;
this.watchingTimeInit = Date.now();
} else if (!!this.rebufferingTimeInit) {
this.rebufferingTime += this.getRebufferingTime();
}
this.rebufferingTimeInit = undefined;
this.state = "PLAYING";
},
getRebufferingTime: function() {
return Date.now() - this.rebufferingTimeInit;
},
getWatchingTime: function() {
var totalTime = (Date.now() - this.watchingTimeInit);
return totalTime - this.rebufferingTime;
},
isRebuffering: function() {
return !!this.rebufferingTimeInit;
},
onStatsAdd: function(metric) {
$.extend(this.externalMetrics, metric);
},
getStats: function() {
var metrics = {
startupTime: this.startupTime,
rebuffers: this.rebuffers,
rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,
watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()
};
$.extend(metrics, this.externalMetrics);
return metrics;
},
report: function() {
this.container.statsReport(this.getStats());
}
}, {}, ContainerPlugin);
module.exports = StatsPlugin;
},{"container_plugin":"container_plugin","jquery":"jquery"}],48:[function(require,module,exports){
"use strict";
module.exports = require('./watermark');
},{"./watermark":49}],49:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var WaterMarkPlugin = function WaterMarkPlugin(options) {
$traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.position = options.position || "bottom-right";
if (options.watermark) {
this.imageUrl = options.watermark;
this.render();
} else {
this.$el.remove();
}
};
var $WaterMarkPlugin = WaterMarkPlugin;
($traceurRuntime.createClass)(WaterMarkPlugin, {
get name() {
return 'watermark';
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
},
onPlay: function() {
if (!this.hidden)
this.$el.show();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
var templateOptions = {
position: this.position,
imageUrl: this.imageUrl
};
this.$el.html(this.template(templateOptions));
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIContainerPlugin);
module.exports = WaterMarkPlugin;
},{"../../base/jst":9,"../../base/styler":10,"ui_container_plugin":"ui_container_plugin"}],"base_object":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = require('./utils').extend;
var Events = require('./events');
var pluginOptions = ['container'];
var BaseObject = function BaseObject(options) {
this.uniqueId = _.uniqueId('o');
options || (options = {});
_.extend(this, _.pick(options, pluginOptions));
};
($traceurRuntime.createClass)(BaseObject, {}, {}, Events);
BaseObject.extend = extend;
module.exports = BaseObject;
},{"./events":8,"./utils":11,"underscore":6}],"browser":[function(require,module,exports){
"use strict";
var Browser = function Browser() {};
($traceurRuntime.createClass)(Browser, {}, {});
Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);
Browser.isChrome = !!(navigator.userAgent.match(/chrome/i));
Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i));
Browser.isLegacyIE = !!(window.ActiveXObject);
Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i));
Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));
Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));
module.exports = Browser;
},{}],"container_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var ContainerPlugin = function ContainerPlugin(options) {
$traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]);
this.bindEvents();
};
var $ContainerPlugin = ContainerPlugin;
($traceurRuntime.createClass)(ContainerPlugin, {
enable: function() {
this.bindEvents();
},
disable: function() {
this.stopListening();
},
bindEvents: function() {},
destroy: function() {
this.stopListening();
}
}, {}, BaseObject);
module.exports = ContainerPlugin;
},{"base_object":"base_object"}],"container":[function(require,module,exports){
"use strict";
module.exports = require('./container');
},{"./container":12}],"core_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CorePlugin = function CorePlugin(core) {
$traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]);
this.core = core;
};
var $CorePlugin = CorePlugin;
($traceurRuntime.createClass)(CorePlugin, {
getExternalInterface: function() {
return {};
},
destroy: function() {}
}, {}, BaseObject);
module.exports = CorePlugin;
},{"base_object":"base_object"}],"core":[function(require,module,exports){
"use strict";
module.exports = require('./core');
},{"./core":15}],"flash":[function(require,module,exports){
"use strict";
module.exports = require('./flash');
},{"./flash":26}],"hls":[function(require,module,exports){
"use strict";
module.exports = require('./hls');
},{"./hls":27}],"html5_audio":[function(require,module,exports){
"use strict";
module.exports = require('./html5_audio');
},{"./html5_audio":28}],"html5_video":[function(require,module,exports){
"use strict";
module.exports = require('./html5_video');
},{"./html5_video":29}],"jquery":[function(require,module,exports){
/*!
* jQuery JavaScript Library v2.1.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:11Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowclip^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// #11217 - WebKit loses check when the name is after the checked attribute
// Support: Windows Web Apps (WWA)
// `name` and `type` need .setAttribute for WWA
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
},{}],"media_control":[function(require,module,exports){
"use strict";
module.exports = require('./media_control');
},{"./media_control":22}],"mediator":[function(require,module,exports){
"use strict";
var Events = require('../base/events');
var events = new Events();
var Mediator = function Mediator() {};
($traceurRuntime.createClass)(Mediator, {}, {});
Mediator.on = function(name, callback, context) {
events.on(name, callback, context);
return;
};
Mediator.once = function(name, callback, context) {
events.once(name, callback, context);
return;
};
Mediator.off = function(name, callback, context) {
events.off(name, callback, context);
return;
};
Mediator.trigger = function(name, opts) {
events.trigger(name, opts);
return;
};
Mediator.stopListening = function(obj, name, callback) {
events.stopListening(obj, name, callback);
return;
};
module.exports = Mediator;
},{"../base/events":8}],"playback":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Playback = function Playback(options) {
$traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]);
this.settings = {};
};
var $Playback = Playback;
($traceurRuntime.createClass)(Playback, {
play: function() {},
pause: function() {},
stop: function() {},
seek: function(time) {},
getDuration: function() {
return 0;
},
isPlaying: function() {
return false;
},
getPlaybackType: function() {
return 'no_op';
},
isHighDefinitionInUse: function() {
return false;
},
volume: function(value) {},
destroy: function() {
this.$el.remove();
}
}, {}, UIObject);
Playback.canPlay = (function(source) {
return false;
});
module.exports = Playback;
},{"ui_object":"ui_object"}],"player_info":[function(require,module,exports){
"use strict";
var PlayerInfo = {
options: {},
playbackPlugins: [],
currentSize: {
width: 0,
height: 0
}
};
module.exports = PlayerInfo;
},{}],"ui_container_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UIContainerPlugin = function UIContainerPlugin(options) {
$traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]);
this.enabled = true;
this.bindEvents();
};
var $UIContainerPlugin = UIContainerPlugin;
($traceurRuntime.createClass)(UIContainerPlugin, {
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
bindEvents: function() {},
destroy: function() {
this.remove();
}
}, {}, UIObject);
module.exports = UIContainerPlugin;
},{"ui_object":"ui_object"}],"ui_core_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UICorePlugin = function UICorePlugin(core) {
$traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]);
this.core = core;
this.enabled = true;
this.bindEvents();
this.render();
};
var $UICorePlugin = UICorePlugin;
($traceurRuntime.createClass)(UICorePlugin, {
bindEvents: function() {},
getExternalInterface: function() {
return {};
},
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
destroy: function() {
this.remove();
},
render: function() {
this.$el.html(this.template());
this.$el.append(this.styler.getStyleFor(this.name));
this.core.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = UICorePlugin;
},{"ui_object":"ui_object"}],"ui_object":[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var extend = require('./utils').extend;
var BaseObject = require('base_object');
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var UIObject = function UIObject(options) {
$traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]);
this.cid = _.uniqueId('c');
this._ensureElement();
this.delegateEvents();
};
var $UIObject = UIObject;
($traceurRuntime.createClass)(UIObject, {
get tagName() {
return 'div';
},
$: function(selector) {
return this.$el.find(selector);
},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
setElement: function(element, delegate) {
if (this.$el)
this.undelegateEvents();
this.$el = element instanceof $ ? element : $(element);
this.el = this.$el[0];
if (delegate !== false)
this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events'))))
return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method))
method = this[events[key]];
if (!method)
continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id)
attrs.id = _.result(this, 'id');
if (this.className)
attrs['class'] = _.result(this, 'className');
var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
}, {}, BaseObject);
UIObject.extend = extend;
module.exports = UIObject;
},{"./utils":11,"base_object":"base_object","jquery":"jquery","underscore":6}]},{},[3,1]);
|
ajax/libs/react/0.12.0/react-with-addons.min.js | viskin/cdnjs | /**
* React (with addons) v0.12.0
*
* Copyright 2013-2014, 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.
*
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,function(e){var n=t[a][1][e];return o(n?n:e)},l,l.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t){"use strict";var n=e("./LinkedStateMixin"),r=e("./React"),o=e("./ReactComponentWithPureRenderMixin"),i=e("./ReactCSSTransitionGroup"),a=e("./ReactTransitionGroup"),s=e("./ReactUpdates"),u=e("./cx"),c=e("./cloneWithProps"),l=e("./update");r.addons={CSSTransitionGroup:i,LinkedStateMixin:n,PureRenderMixin:o,TransitionGroup:a,batchedUpdates:s.batchedUpdates,classSet:u,cloneWithProps:c,update:l},t.exports=r},{"./LinkedStateMixin":25,"./React":31,"./ReactCSSTransitionGroup":34,"./ReactComponentWithPureRenderMixin":39,"./ReactTransitionGroup":87,"./ReactUpdates":88,"./cloneWithProps":110,"./cx":115,"./update":154}],2:[function(e,t){"use strict";var n=e("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":122}],3:[function(e,t){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ExecutionEnvironment"),s=e("./SyntheticInputEvent"),u=e("./keyOf"),c=a.canUseDOM&&"TextEvent"in window&&!("documentMode"in document||n()),l=32,p=String.fromCharCode(l),d=o.topLevelTypes,f={beforeInput:{phasedRegistrationNames:{bubbled:u({onBeforeInput:null}),captured:u({onBeforeInputCapture:null})},dependencies:[d.topCompositionEnd,d.topKeyPress,d.topTextInput,d.topPaste]}},h=null,m=!1,v={eventTypes:f,extractEvents:function(e,t,n,o){var a;if(c)switch(e){case d.topKeyPress:var u=o.which;if(u!==l)return;m=!0,a=p;break;case d.topTextInput:if(a=o.data,a===p&&m)return;break;default:return}else{switch(e){case d.topPaste:h=null;break;case d.topKeyPress:o.which&&!r(o)&&(h=String.fromCharCode(o.which));break;case d.topCompositionEnd:h=o.data}if(null===h)return;a=h}if(a){var v=s.getPooled(f.beforeInput,n,o);return v.data=a,h=null,i.accumulateTwoPhaseDispatches(v),v}}};t.exports=v},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./SyntheticInputEvent":98,"./keyOf":144}],4:[function(e,t){var n=e("./invariant"),r={addClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.add(t):r.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return n(!/\s/.test(t)),t&&(e.classList?e.classList.remove(t):r.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?r.addClass:r.removeClass)(e,t)},hasClass:function(e,t){return n(!/\s/.test(t)),e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}};t.exports=r},{"./invariant":137}],5:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={columnCount:!0,fillOpacity:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};t.exports=a},{}],6:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./ExecutionEnvironment"),o=(e("./camelizeStyleName"),e("./dangerousStyleValue")),i=e("./hyphenateStyleName"),a=e("./memoizeStringOnly"),s=(e("./warning"),a(function(e){return i(e)})),u="cssFloat";r.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(u="styleFloat");var c={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=o(n,r)+";")}return t||null},setValueForStyles:function(e,t){var r=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=o(i,t[i]);if("float"===i&&(i=u),a)r[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var c in s)r[c]="";else r[i]=""}}}};t.exports=c},{"./CSSProperty":5,"./ExecutionEnvironment":23,"./camelizeStyleName":109,"./dangerousStyleValue":116,"./hyphenateStyleName":135,"./memoizeStringOnly":146,"./warning":155}],7:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),o=e("./Object.assign"),i=e("./invariant");o(n.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){i(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./invariant":137}],8:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=M.getPooled(P.change,w,e);E.accumulateTwoPhaseDispatches(t),R.batchedUpdates(o,t)}function o(e){g.enqueueEvents(e),g.processEventQueue()}function i(e,t){T=e,w=t,T.attachEvent("onchange",r)}function a(){T&&(T.detachEvent("onchange",r),T=null,w=null)}function s(e,t,n){return e===x.topChange?n:void 0}function u(e,t,n){e===x.topFocus?(a(),i(t,n)):e===x.topBlur&&a()}function c(e,t){T=e,w=t,_=e.value,S=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(T,"value",k),T.attachEvent("onpropertychange",p)}function l(){T&&(delete T.value,T.detachEvent("onpropertychange",p),T=null,w=null,_=null,S=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==_&&(_=t,r(e))}}function d(e,t,n){return e===x.topInput?n:void 0}function f(e,t,n){e===x.topFocus?(l(),c(t,n)):e===x.topBlur&&l()}function h(e){return e!==x.topSelectionChange&&e!==x.topKeyUp&&e!==x.topKeyDown||!T||T.value===_?void 0:(_=T.value,w)}function m(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function v(e,t,n){return e===x.topClick?n:void 0}var y=e("./EventConstants"),g=e("./EventPluginHub"),E=e("./EventPropagators"),C=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),b=e("./isEventSupported"),O=e("./isTextInputElement"),D=e("./keyOf"),x=y.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:D({onChange:null}),captured:D({onChangeCapture:null})},dependencies:[x.topBlur,x.topChange,x.topClick,x.topFocus,x.topInput,x.topKeyDown,x.topKeyUp,x.topSelectionChange]}},T=null,w=null,_=null,S=null,N=!1;C.canUseDOM&&(N=b("change")&&(!("documentMode"in document)||document.documentMode>8));var I=!1;C.canUseDOM&&(I=b("input")&&(!("documentMode"in document)||document.documentMode>9));var k={get:function(){return S.get.call(this)},set:function(e){_=""+e,S.set.call(this,e)}},A={eventTypes:P,extractEvents:function(e,t,r,o){var i,a;if(n(t)?N?i=s:a=u:O(t)?I?i=d:(i=h,a=f):m(t)&&(i=v),i){var c=i(e,t,r);if(c){var l=M.getPooled(P.change,c,o);return E.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,r)}};t.exports=A},{"./EventConstants":17,"./EventPluginHub":19,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactUpdates":88,"./SyntheticEvent":96,"./isEventSupported":138,"./isTextInputElement":140,"./keyOf":144}],9:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],10:[function(e,t){"use strict";function n(e){switch(e){case y.topCompositionStart:return E.compositionStart;case y.topCompositionEnd:return E.compositionEnd;case y.topCompositionUpdate:return E.compositionUpdate}}function r(e,t){return e===y.topKeyDown&&t.keyCode===h}function o(e,t){switch(e){case y.topKeyUp:return-1!==f.indexOf(t.keyCode);case y.topKeyDown:return t.keyCode!==h;case y.topKeyPress:case y.topMouseDown:case y.topBlur:return!0;default:return!1}}function i(e){this.root=e,this.startSelection=c.getSelection(e),this.startValue=this.getText()}var a=e("./EventConstants"),s=e("./EventPropagators"),u=e("./ExecutionEnvironment"),c=e("./ReactInputSelection"),l=e("./SyntheticCompositionEvent"),p=e("./getTextContentAccessor"),d=e("./keyOf"),f=[9,13,27,32],h=229,m=u.canUseDOM&&"CompositionEvent"in window,v=!m||"documentMode"in document&&document.documentMode>8&&document.documentMode<=11,y=a.topLevelTypes,g=null,E={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[y.topBlur,y.topCompositionEnd,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[y.topBlur,y.topCompositionStart,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[y.topBlur,y.topCompositionUpdate,y.topKeyDown,y.topKeyPress,y.topKeyUp,y.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var e=this.getText(),t=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return e.substr(t,e.length-n-t)};var C={eventTypes:E,extractEvents:function(e,t,a,u){var c,p;if(m?c=n(e):g?o(e,u)&&(c=E.compositionEnd):r(e,u)&&(c=E.compositionStart),v&&(g||c!==E.compositionStart?c===E.compositionEnd&&g&&(p=g.getData(),g=null):g=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=C},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactInputSelection":63,"./SyntheticCompositionEvent":94,"./getTextContentAccessor":132,"./keyOf":144}],11:[function(e,t){"use strict";function n(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r,o=e("./Danger"),i=e("./ReactMultiChildUpdateTypes"),a=e("./getTextContentAccessor"),s=e("./invariant"),u=a();r="textContent"===u?function(e,t){e.textContent=t}:function(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);if(t){var n=e.ownerDocument||document;e.appendChild(n.createTextNode(t))}};var c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:r,processUpdates:function(e,t){for(var a,u=null,c=null,l=0;a=e[l];l++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var p=a.fromIndex,d=a.parentNode.childNodes[p],f=a.parentID;s(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,c=c||[],c.push(d)}var h=o.dangerouslyRenderMarkup(t);if(c)for(var m=0;m<c.length;m++)c[m].parentNode.removeChild(c[m]);for(var v=0;a=e[v];v++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,h[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,u[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:r(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};t.exports=c},{"./Danger":14,"./ReactMultiChildUpdateTypes":70,"./getTextContentAccessor":132,"./invariant":137}],12:[function(e,t){"use strict";function n(e,t){return(e&t)===t}var r=e("./invariant"),o={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},i=e.DOMAttributeNames||{},s=e.DOMPropertyNames||{},u=e.DOMMutationMethods||{};e.isCustomAttribute&&a._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var c in t){r(!a.isStandardName.hasOwnProperty(c)),a.isStandardName[c]=!0;var l=c.toLowerCase();if(a.getPossibleStandardName[l]=c,i.hasOwnProperty(c)){var p=i[c];a.getPossibleStandardName[p]=c,a.getAttributeName[c]=p}else a.getAttributeName[c]=l;a.getPropertyName[c]=s.hasOwnProperty(c)?s[c]:c,a.getMutationMethod[c]=u.hasOwnProperty(c)?u[c]:null;var d=t[c];a.mustUseAttribute[c]=n(d,o.MUST_USE_ATTRIBUTE),a.mustUseProperty[c]=n(d,o.MUST_USE_PROPERTY),a.hasSideEffects[c]=n(d,o.HAS_SIDE_EFFECTS),a.hasBooleanValue[c]=n(d,o.HAS_BOOLEAN_VALUE),a.hasNumericValue[c]=n(d,o.HAS_NUMERIC_VALUE),a.hasPositiveNumericValue[c]=n(d,o.HAS_POSITIVE_NUMERIC_VALUE),a.hasOverloadedBooleanValue[c]=n(d,o.HAS_OVERLOADED_BOOLEAN_VALUE),r(!a.mustUseAttribute[c]||!a.mustUseProperty[c]),r(a.mustUseProperty[c]||!a.hasSideEffects[c]),r(!!a.hasBooleanValue[c]+!!a.hasNumericValue[c]+!!a.hasOverloadedBooleanValue[c]<=1)}}},i={},a={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<a._isCustomAttributeFunctions.length;t++){var n=a._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=i[e];return r||(i[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:o};t.exports=a},{"./invariant":137}],13:[function(e,t){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e("./DOMProperty"),o=e("./escapeTextForBrowser"),i=e("./memoizeStringOnly"),a=(e("./warning"),i(function(e){return o(e)+'="'})),s={createMarkupForID:function(e){return a(r.ID_ATTRIBUTE_NAME)+o(e)+'"'},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var i=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?o(i):a(i)+o(t)+'"'}return r.isCustomAttribute(e)?null==t?"":a(e)+o(t)+'"':null},setValueForProperty:function(e,t,o){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var i=r.getMutationMethod[t];if(i)i(e,o);else if(n(t,o))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+o);else{var a=r.getPropertyName[t];r.hasSideEffects[t]&&""+e[a]==""+o||(e[a]=o)}}else r.isCustomAttribute(t)&&(null==o?e.removeAttribute(t):e.setAttribute(t,""+o))},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var o=r.getPropertyName[t],i=r.getDefaultValueForProperty(e.nodeName,o);r.hasSideEffects[t]&&""+e[o]===i||(e[o]=i)}}else r.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=s},{"./DOMProperty":12,"./escapeTextForBrowser":120,"./memoizeStringOnly":146,"./warning":155}],14:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e("./ExecutionEnvironment"),o=e("./createNodesFromMarkup"),i=e("./emptyFunction"),a=e("./getMarkupWrap"),s=e("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(e){s(r.canUseDOM);for(var t,l={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",l[t]=l[t]||[],l[t][p]=e[p];var d=[],f=0;for(t in l)if(l.hasOwnProperty(t)){var h=l[t];for(var m in h)if(h.hasOwnProperty(m)){var v=h[m];h[m]=v.replace(u,"$1 "+c+'="'+m+'" ')}var y=o(h.join(""),i);for(p=0;p<y.length;++p){var g=y[p];g.hasAttribute&&g.hasAttribute(c)&&(m=+g.getAttribute(c),g.removeAttribute(c),s(!d.hasOwnProperty(m)),d[m]=g,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(r.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=o(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=l},{"./ExecutionEnvironment":23,"./createNodesFromMarkup":114,"./emptyFunction":118,"./getMarkupWrap":129,"./invariant":137}],15:[function(e,t){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":144}],16:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./SyntheticMouseEvent"),i=e("./ReactMount"),a=e("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var m=f?i.getID(f):"",v=h?i.getID(h):"",y=o.getPooled(c.mouseLeave,m,a);y.type="mouseleave",y.target=f,y.relatedTarget=h;var g=o.getPooled(c.mouseEnter,v,a);return g.type="mouseenter",g.target=h,g.relatedTarget=f,r.accumulateEnterLeaveDispatches(y,g,m,v),l[0]=y,l[1]=g,l}};t.exports=p},{"./EventConstants":17,"./EventPropagators":22,"./ReactMount":68,"./SyntheticMouseEvent":100,"./keyOf":144}],17:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),o=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{"./keyMirror":143}],18:[function(e,t){var n=e("./emptyFunction"),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):{remove:n}},registerDefault:function(){}};t.exports=r},{"./emptyFunction":118}],19:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),r=e("./EventPluginUtils"),o=e("./accumulateInto"),i=e("./forEachAccumulated"),a=e("./invariant"),s={},u=null,c=function(e){if(e){var t=r.executeDispatch,o=n.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),r.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},l=null,p={injection:{injectMount:r.injection.injectMount,injectInstanceHandle:function(e){l=e},getInstanceHandle:function(){return l},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){a(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,r,i){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(e,t,r,i);p&&(a=o(a,p))}}return a},enqueueEvents:function(e){e&&(u=o(u,e))},processEventQueue:function(){var e=u;u=null,i(e,c),a(!u)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=p},{"./EventPluginRegistry":20,"./EventPluginUtils":21,"./accumulateInto":106,"./forEachAccumulated":123,"./invariant":137}],20:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var c in o)i(r(o[c],t,c))}}}function r(e,t,n){i(!u.eventNameDispatchConfigs.hasOwnProperty(n)),u.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var a in r)if(r.hasOwnProperty(a)){var s=r[a];o(s,t,n)}return!0}return e.registrationName?(o(e.registrationName,t,n),!0):!1}function o(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s.hasOwnProperty(r)&&s[r]===o||(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=u.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=u},{"./invariant":137}],21:[function(e,t){"use strict";function n(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function r(e){return e===m.topMouseMove||e===m.topTouchMove}function o(e){return e===m.topMouseDown||e===m.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){e.currentTarget=h.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;f(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e("./EventConstants"),f=e("./invariant"),h={Mount:null,injectMount:function(e){h.Mount=e}},m=d.topLevelTypes,v={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:l,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=v},{"./EventConstants":17,"./invariant":137}],22:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return m(e,r)}function r(e,t,r){var o=t?h.bubbled:h.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=m(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,o)}function u(e,t,n,r){p.injection.getInstanceHandle().traverseEnterLeave(n,r,i,e,t)}function c(e){f(e,a)}var l=e("./EventConstants"),p=e("./EventPluginHub"),d=e("./accumulateInto"),f=e("./forEachAccumulated"),h=l.PropagationPhases,m=p.getListener,v={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=v},{"./EventConstants":17,"./EventPluginHub":19,"./accumulateInto":106,"./forEachAccumulated":123}],23:[function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],24:[function(e,t){"use strict";var n,r=e("./DOMProperty"),o=e("./ExecutionEnvironment"),i=r.injection.MUST_USE_ATTRIBUTE,a=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,c=r.injection.HAS_NUMERIC_VALUE,l=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(o.canUseDOM){var d=document.implementation;n=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var f={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:i,checked:a|s,classID:i,className:n?i:a,cols:i|l,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:a|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:p,draggable:null,encType:null,form:i,formNoValidate:s,frameBorder:i,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:i,loop:a|s,manifest:i,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,open:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:a|s,rel:null,required:s,role:i,rows:i|l,rowSpan:null,sandbox:null,scope:null,scrolling:null,seamless:i|s,selected:a|s,shape:null,size:i|l,sizes:i,span:l,spellCheck:null,src:null,srcDoc:a,srcSet:i,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:a|u,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|s,itemType:i,property:null},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=f},{"./DOMProperty":12,"./ExecutionEnvironment":23}],25:[function(e,t){"use strict";var n=e("./ReactLink"),r=e("./ReactStateSetters"),o={linkState:function(e){return new n(this.state[e],r.createStateKeySetter(this,e))}};t.exports=o},{"./ReactLink":66,"./ReactStateSetters":83}],26:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function o(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e("./ReactPropTypes"),u=e("./invariant"),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},l={Mixin:{propTypes:{value:function(e,t){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?void 0:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?void 0:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(o(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),i):e.props.checkedLink?(o(e),a):e.props.onChange}};t.exports=l},{"./ReactPropTypes":77,"./invariant":137}],27:[function(e,t){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),o=e("./accumulateInto"),i=e("./forEachAccumulated"),a=e("./invariant"),s={trapBubbledEvent:function(e,t){a(this.isMounted());var n=r.trapBubbledEvent(e,t,this.getDOMNode());this._localEventListeners=o(this._localEventListeners,n)},componentWillUnmount:function(){this._localEventListeners&&i(this._localEventListeners,n)}};t.exports=s},{"./ReactBrowserEventEmitter":33,"./accumulateInto":106,"./forEachAccumulated":123,"./invariant":137}],28:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{"./EventConstants":17,"./emptyFunction":118}],29:[function(e,t){function n(e){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var t=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(t[a]=i[a])}}return t}t.exports=n},{}],30:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},o=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},a=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,c=r,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:r,twoArgumentPooler:o,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{"./invariant":137}],31:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./EventPluginUtils"),o=e("./ReactChildren"),i=e("./ReactComponent"),a=e("./ReactCompositeComponent"),s=e("./ReactContext"),u=e("./ReactCurrentOwner"),c=e("./ReactElement"),l=(e("./ReactElementValidator"),e("./ReactDOM")),p=e("./ReactDOMComponent"),d=e("./ReactDefaultInjection"),f=e("./ReactInstanceHandles"),h=e("./ReactLegacyElement"),m=e("./ReactMount"),v=e("./ReactMultiChild"),y=e("./ReactPerf"),g=e("./ReactPropTypes"),E=e("./ReactServerRendering"),C=e("./ReactTextComponent"),R=e("./Object.assign"),M=e("./deprecated"),b=e("./onlyChild");
d.inject();var O=c.createElement,D=c.createFactory;O=h.wrapCreateElement(O),D=h.wrapCreateFactory(D);var x=y.measure("React","render",m.render),P={Children:{map:o.map,forEach:o.forEach,count:o.count,only:b},DOM:l,PropTypes:g,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createElement:O,createFactory:D,constructAndRenderComponent:m.constructAndRenderComponent,constructAndRenderComponentByID:m.constructAndRenderComponentByID,render:x,renderToString:E.renderToString,renderToStaticMarkup:E.renderToStaticMarkup,unmountComponentAtNode:m.unmountComponentAtNode,isValidClass:h.isValidClass,isValidElement:c.isValidElement,withContext:s.withContext,__spread:R,renderComponent:M("React","renderComponent","render",this,x),renderComponentToString:M("React","renderComponentToString","renderToString",this,E.renderToString),renderComponentToStaticMarkup:M("React","renderComponentToStaticMarkup","renderToStaticMarkup",this,E.renderToStaticMarkup),isValidComponent:M("React","isValidComponent","isValidElement",this,c.isValidElement)};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({Component:i,CurrentOwner:u,DOMComponent:p,DOMPropertyOperations:n,InstanceHandles:f,Mount:m,MultiChild:v,TextComponent:C});P.version="0.12.0",t.exports=P},{"./DOMPropertyOperations":13,"./EventPluginUtils":21,"./Object.assign":29,"./ReactChildren":36,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactDOM":43,"./ReactDOMComponent":45,"./ReactDefaultInjection":55,"./ReactElement":56,"./ReactElementValidator":57,"./ReactInstanceHandles":64,"./ReactLegacyElement":65,"./ReactMount":68,"./ReactMultiChild":69,"./ReactPerf":73,"./ReactPropTypes":77,"./ReactServerRendering":81,"./ReactTextComponent":84,"./deprecated":117,"./onlyChild":148}],32:[function(e,t){"use strict";var n=e("./ReactEmptyComponent"),r=e("./ReactMount"),o=e("./invariant"),i={getDOMNode:function(){return o(this.isMounted()),n.isNullComponentID(this._rootNodeID)?null:r.getNode(this._rootNodeID)}};t.exports=i},{"./ReactEmptyComponent":58,"./ReactMount":68,"./invariant":137}],33:[function(e,t){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=d++,l[e[h]]={}),l[e[h]]}var r=e("./EventConstants"),o=e("./EventPluginHub"),i=e("./EventPluginRegistry"),a=e("./ReactEventEmitterMixin"),s=e("./ViewportMetrics"),u=e("./Object.assign"),c=e("./isEventSupported"),l={},p=!1,d=0,f={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),m=u({},a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!m.ReactEventListener||!m.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],u=r.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];a.hasOwnProperty(d)&&a[d]||(d===u.topWheel?c("wheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",o):c("mousewheel")?m.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",o):m.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",o):d===u.topScroll?c("scroll",!0)?m.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",o):m.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",m.ReactEventListener.WINDOW_HANDLE):d===u.topFocus||d===u.topBlur?(c("focus",!0)?(m.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",o),m.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",o)):c("focusin")&&(m.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",o),m.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",o)),a[u.topBlur]=!0,a[u.topFocus]=!0):f.hasOwnProperty(d)&&m.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),p=!0}},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:o.putListener,getListener:o.getListener,deleteListener:o.deleteListener,deleteAllListeners:o.deleteAllListeners});t.exports=m},{"./EventConstants":17,"./EventPluginHub":19,"./EventPluginRegistry":20,"./Object.assign":29,"./ReactEventEmitterMixin":60,"./ViewportMetrics":105,"./isEventSupported":138}],34:[function(e,t){"use strict";var n=e("./React"),r=e("./Object.assign"),o=n.createFactory(e("./ReactTransitionGroup")),i=n.createFactory(e("./ReactCSSTransitionGroupChild")),a=n.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:n.PropTypes.string.isRequired,transitionEnter:n.PropTypes.bool,transitionLeave:n.PropTypes.bool},getDefaultProps:function(){return{transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return i({name:this.props.transitionName,enter:this.props.transitionEnter,leave:this.props.transitionLeave},e)},render:function(){return o(r({},this.props,{childFactory:this._wrapChild}))}});t.exports=a},{"./Object.assign":29,"./React":31,"./ReactCSSTransitionGroupChild":35,"./ReactTransitionGroup":87}],35:[function(e,t){"use strict";var n=e("./React"),r=e("./CSSCore"),o=e("./ReactTransitionEvents"),i=e("./onlyChild"),a=17,s=n.createClass({displayName:"ReactCSSTransitionGroupChild",transition:function(e,t){var n=this.getDOMNode(),i=this.props.name+"-"+e,a=i+"-active",s=function(e){e&&e.target!==n||(r.removeClass(n,i),r.removeClass(n,a),o.removeEndEventListener(n,s),t&&t())};o.addEndEventListener(n,s),r.addClass(n,i),this.queueClass(a)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,a))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(r.addClass.bind(r,this.getDOMNode())),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillEnter:function(e){this.props.enter?this.transition("enter",e):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e):e()},render:function(){return i(this.props.children)}});t.exports=s},{"./CSSCore":4,"./React":31,"./ReactTransitionEvents":86,"./onlyChild":148}],36:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function o(e,t,o){if(null==e)return e;var i=n.getPooled(t,o);p(e,r,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function s(e,t,n){if(null==e)return e;var r={},o=i.getPooled(r,t,n);return p(e,a,o),i.release(o),r}function u(){return null}function c(e){return p(e,u,null)}var l=e("./PooledClass"),p=e("./traverseAllChildren"),d=(e("./warning"),l.twoArgumentPooler),f=l.threeArgumentPooler;l.addPoolingTo(n,d),l.addPoolingTo(i,f);var h={forEach:o,map:s,count:c};t.exports=h},{"./PooledClass":30,"./traverseAllChildren":153,"./warning":155}],37:[function(e,t){"use strict";var n=e("./ReactElement"),r=e("./ReactOwner"),o=e("./ReactUpdates"),i=e("./Object.assign"),a=e("./invariant"),s=e("./keyMirror"),u=s({MOUNTED:null,UNMOUNTED:null}),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){a(!c),p=e.mountImageIntoNode,l=e.unmountIDFromEnvironment,d.BackendIDOperations=e.BackendIDOperations,c=!0}},LifeCycle:u,BackendIDOperations:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(e,t){var n=this._pendingElement||this._currentElement;this.replaceProps(i({},n.props,e),t)},replaceProps:function(e,t){a(this.isMounted()),a(0===this._mountDepth),this._pendingElement=n.cloneAndReplaceProps(this._pendingElement||this._currentElement,e),o.enqueueUpdate(this,t)},_setPropsInternal:function(e,t){var r=this._pendingElement||this._currentElement;this._pendingElement=n.cloneAndReplaceProps(r,i({},r.props,e)),o.enqueueUpdate(this,t)},construct:function(e){this.props=e.props,this._owner=e._owner,this._lifeCycleState=u.UNMOUNTED,this._pendingCallbacks=null,this._currentElement=e,this._pendingElement=null},mountComponent:function(e,t,n){a(!this.isMounted());var o=this._currentElement.ref;if(null!=o){var i=this._currentElement._owner;r.addComponentAsRefTo(this,o,i)}this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){a(this.isMounted());var e=this._currentElement.ref;null!=e&&r.removeComponentAsRefFrom(this,e,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){a(this.isMounted()),this._pendingElement=e,this.performUpdateIfNecessary(t)},performUpdateIfNecessary:function(e){if(null!=this._pendingElement){var t=this._currentElement,n=this._pendingElement;this._currentElement=n,this.props=n.props,this._owner=n._owner,this._pendingElement=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this._currentElement;(n._owner!==t._owner||n.ref!==t.ref)&&(null!=t.ref&&r.removeComponentAsRefFrom(this,t.ref,t._owner),null!=n.ref&&r.addComponentAsRefTo(this,n.ref,n._owner))},mountComponentIntoNode:function(e,t,n){var r=o.ReactReconcileTransaction.getPooled();r.perform(this._mountComponentIntoNode,this,e,t,r,n),o.ReactReconcileTransaction.release(r)},_mountComponentIntoNode:function(e,t,n,r){var o=this.mountComponent(e,n,0);p(o,t,r)},isOwnedBy:function(e){return this._owner===e},getSiblingByRef:function(e){var t=this._owner;return t&&t.refs?t.refs[e]:null}}};t.exports=d},{"./Object.assign":29,"./ReactElement":56,"./ReactOwner":72,"./ReactUpdates":88,"./invariant":137,"./keyMirror":143}],38:[function(e,t){"use strict";var n=e("./ReactDOMIDOperations"),r=e("./ReactMarkupChecksum"),o=e("./ReactMount"),i=e("./ReactPerf"),a=e("./ReactReconcileTransaction"),s=e("./getReactRootElementInContainer"),u=e("./invariant"),c=e("./setInnerHTML"),l=1,p=9,d={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(e){o.purgeID(e)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(e,t,n){if(u(t&&(t.nodeType===l||t.nodeType===p)),n){if(r.canReuseMarkup(e,s(t)))return;u(t.nodeType!==p)}u(t.nodeType!==p),c(t,e)})};t.exports=d},{"./ReactDOMIDOperations":47,"./ReactMarkupChecksum":67,"./ReactMount":68,"./ReactPerf":73,"./ReactReconcileTransaction":79,"./getReactRootElementInContainer":131,"./invariant":137,"./setInnerHTML":149}],39:[function(e,t){"use strict";var n=e("./shallowEqual"),r={shouldComponentUpdate:function(e,t){return!n(this.props,e)||!n(this.state,t)}};t.exports=r},{"./shallowEqual":150}],40:[function(e,t){"use strict";function n(e){var t=e._owner||null;return t&&t.constructor&&t.constructor.displayName?" Check the render method of `"+t.constructor.displayName+"`.":""}function r(e,t){for(var n in t)t.hasOwnProperty(n)&&D("function"==typeof t[n])}function o(e,t){var n=I.hasOwnProperty(t)?I[t]:null;L.hasOwnProperty(t)&&D(n===S.OVERRIDE_BASE),e.hasOwnProperty(t)&&D(n===S.DEFINE_MANY||n===S.DEFINE_MANY_MERGED)}function i(e){var t=e._compositeLifeCycleState;D(e.isMounted()||t===A.MOUNTING),D(null==f.current),D(t!==A.UNMOUNTING)}function a(e,t){if(t){D(!y.isValidFactory(t)),D(!h.isValidElement(t));var n=e.prototype;t.hasOwnProperty(_)&&k.mixins(e,t.mixins);for(var r in t)if(t.hasOwnProperty(r)&&r!==_){var i=t[r];if(o(n,r),k.hasOwnProperty(r))k[r](e,i);else{var a=I.hasOwnProperty(r),s=n.hasOwnProperty(r),u=i&&i.__reactDontBind,p="function"==typeof i,d=p&&!a&&!s&&!u;if(d)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[r]=i,n[r]=i;else if(s){var f=I[r];D(a&&(f===S.DEFINE_MANY_MERGED||f===S.DEFINE_MANY)),f===S.DEFINE_MANY_MERGED?n[r]=c(n[r],i):f===S.DEFINE_MANY&&(n[r]=l(n[r],i))}else n[r]=i}}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in k;D(!o);var i=n in e;D(!i),e[n]=r}}}function u(e,t){return D(e&&t&&"object"==typeof e&&"object"==typeof t),T(t,function(t,n){D(void 0===e[n]),e[n]=t}),e}function c(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);return null==n?r:null==r?n:u(n,r)}}function l(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}var p=e("./ReactComponent"),d=e("./ReactContext"),f=e("./ReactCurrentOwner"),h=e("./ReactElement"),m=(e("./ReactElementValidator"),e("./ReactEmptyComponent")),v=e("./ReactErrorUtils"),y=e("./ReactLegacyElement"),g=e("./ReactOwner"),E=e("./ReactPerf"),C=e("./ReactPropTransferer"),R=e("./ReactPropTypeLocations"),M=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),b=e("./Object.assign"),O=e("./instantiateReactComponent"),D=e("./invariant"),x=e("./keyMirror"),P=e("./keyOf"),T=(e("./monitorCodeUse"),e("./mapObject")),w=e("./shouldUpdateReactComponent"),_=(e("./warning"),P({mixins:null})),S=x({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),N=[],I={mixins:S.DEFINE_MANY,statics:S.DEFINE_MANY,propTypes:S.DEFINE_MANY,contextTypes:S.DEFINE_MANY,childContextTypes:S.DEFINE_MANY,getDefaultProps:S.DEFINE_MANY_MERGED,getInitialState:S.DEFINE_MANY_MERGED,getChildContext:S.DEFINE_MANY_MERGED,render:S.DEFINE_ONCE,componentWillMount:S.DEFINE_MANY,componentDidMount:S.DEFINE_MANY,componentWillReceiveProps:S.DEFINE_MANY,shouldComponentUpdate:S.DEFINE_ONCE,componentWillUpdate:S.DEFINE_MANY,componentDidUpdate:S.DEFINE_MANY,componentWillUnmount:S.DEFINE_MANY,updateComponent:S.OVERRIDE_BASE},k={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)a(e,t[n])},childContextTypes:function(e,t){r(e,t,R.childContext),e.childContextTypes=b({},e.childContextTypes,t)},contextTypes:function(e,t){r(e,t,R.context),e.contextTypes=b({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?c(e.getDefaultProps,t):t},propTypes:function(e,t){r(e,t,R.prop),e.propTypes=b({},e.propTypes,t)},statics:function(e,t){s(e,t)}},A=x({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null}),L={construct:function(){p.Mixin.construct.apply(this,arguments),g.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._compositeLifeCycleState=null},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==A.MOUNTING},mountComponent:E.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=A.MOUNTING,this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.context=this._processContext(this._currentElement._context),this.props=this._processProps(this.props),this.state=this.getInitialState?this.getInitialState():null,D("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=O(this._renderValidatedComponent(),this._currentElement.type),this._compositeLifeCycleState=null;var r=this._renderedComponent.mountComponent(e,t,n+1);return this.componentDidMount&&t.getReactMountReady().enqueue(this.componentDidMount,this),r}),unmountComponent:function(){this._compositeLifeCycleState=A.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(e,t){D("object"==typeof e||null==e),this.replaceState(b({},this._pendingState||this.state,e),t)},replaceState:function(e,t){i(this),this._pendingState=e,this._compositeLifeCycleState!==A.MOUNTING&&M.enqueueUpdate(this,t)},_processContext:function(e){var t=null,n=this.constructor.contextTypes;if(n){t={};for(var r in n)t[r]=e[r]}return t},_processChildContext:function(e){var t=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",t){D("object"==typeof this.constructor.childContextTypes);for(var n in t)D(n in this.constructor.childContextTypes);return b({},e,t)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,r){var o=this.constructor.displayName;for(var i in e)if(e.hasOwnProperty(i)){var a=e[i](t,i,o,r);a instanceof Error&&n(this)}},performUpdateIfNecessary:function(e){var t=this._compositeLifeCycleState;if(t!==A.MOUNTING&&t!==A.RECEIVING_PROPS&&(null!=this._pendingElement||null!=this._pendingState||this._pendingForceUpdate)){var n=this.context,r=this.props,o=this._currentElement;null!=this._pendingElement&&(o=this._pendingElement,n=this._processContext(o._context),r=this._processProps(o.props),this._pendingElement=null,this._compositeLifeCycleState=A.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(r,n)),this._compositeLifeCycleState=null;var i=this._pendingState||this.state;this._pendingState=null;var a=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(r,i,n);a?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,n,e)):(this._currentElement=o,this.props=r,this.state=i,this.context=n,this._owner=o._owner)}},_performComponentUpdate:function(e,t,n,r,o){var i=this._currentElement,a=this.props,s=this.state,u=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this._currentElement=e,this.props=t,this.state=n,this.context=r,this._owner=e._owner,this.updateComponent(o,i),this.componentDidUpdate&&o.getReactMountReady().enqueue(this.componentDidUpdate.bind(this,a,s,u),this)},receiveComponent:function(e,t){(e!==this._currentElement||null==e._owner)&&p.Mixin.receiveComponent.call(this,e,t)},updateComponent:E.measure("ReactCompositeComponent","updateComponent",function(e,t){p.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(w(r,o))n.receiveComponent(o,e);else{var i=this._rootNodeID,a=n._rootNodeID;n.unmountComponent(),this._renderedComponent=O(o,this._currentElement.type);var s=this._renderedComponent.mountComponent(i,e,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(e){var t=this._compositeLifeCycleState;D(this.isMounted()||t===A.MOUNTING),D(t!==A.UNMOUNTING&&null==f.current),this._pendingForceUpdate=!0,M.enqueueUpdate(this,e)},_renderValidatedComponent:E.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._currentElement._context),f.current=this;try{e=this.render(),null===e||e===!1?(e=m.getEmptyComponent(),m.registerNullComponentID(this._rootNodeID)):m.deregisterNullComponentID(this._rootNodeID)}finally{d.current=t,f.current=null}return D(h.isValidElement(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(v.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=e.bind(t);return n}},U=function(){};b(U.prototype,p.Mixin,g.Mixin,C.Mixin,L);var F={LifeCycle:A,Base:U,createClass:function(e){var t=function(){};t.prototype=new U,t.prototype.constructor=t,N.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),D(t.prototype.render);for(var n in I)t.prototype[n]||(t.prototype[n]=null);return y.wrapFactory(h.createFactory(t))},injection:{injectMixin:function(e){N.push(e)}}};t.exports=F},{"./Object.assign":29,"./ReactComponent":37,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactElementValidator":57,"./ReactEmptyComponent":58,"./ReactErrorUtils":59,"./ReactLegacyElement":65,"./ReactOwner":72,"./ReactPerf":73,"./ReactPropTransferer":74,"./ReactPropTypeLocationNames":75,"./ReactPropTypeLocations":76,"./ReactUpdates":88,"./instantiateReactComponent":136,"./invariant":137,"./keyMirror":143,"./keyOf":144,"./mapObject":145,"./monitorCodeUse":147,"./shouldUpdateReactComponent":151,"./warning":155}],41:[function(e,t){"use strict";var n=e("./Object.assign"),r={current:{},withContext:function(e,t){var o,i=r.current;r.current=n({},i,e);try{o=t()}finally{r.current=i}return o}};t.exports=r},{"./Object.assign":29}],42:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],43:[function(e,t){"use strict";function n(e){return o.markNonLegacyFactory(r.createFactory(e))}var r=e("./ReactElement"),o=(e("./ReactElementValidator"),e("./ReactLegacyElement")),i=e("./mapObject"),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},n);t.exports=a},{"./ReactElement":56,"./ReactElementValidator":57,"./ReactLegacyElement":65,"./mapObject":145}],44:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),i=e("./ReactElement"),a=e("./ReactDOM"),s=e("./keyMirror"),u=i.createFactory(a.button.type),c=s({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),l=o.createClass({displayName:"ReactDOMButton",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&c[t]||(e[t]=this.props[t]);return u(e,this.props.children)}});t.exports=l},{"./AutoFocusMixin":2,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./keyMirror":143}],45:[function(e,t){"use strict";function n(e){e&&(y(null==e.children||null==e.dangerouslySetInnerHTML),y(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=d.findReactContainerForID(e);if(o){var i=o.nodeType===O?o.ownerDocument:o;C(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e){T.call(P,e)||(y(x.test(e)),P[e]=!0)}function i(e){o(e),this._tag=e,this.tagName=e.toUpperCase()}var a=e("./CSSPropertyOperations"),s=e("./DOMProperty"),u=e("./DOMPropertyOperations"),c=e("./ReactBrowserComponentMixin"),l=e("./ReactComponent"),p=e("./ReactBrowserEventEmitter"),d=e("./ReactMount"),f=e("./ReactMultiChild"),h=e("./ReactPerf"),m=e("./Object.assign"),v=e("./escapeTextForBrowser"),y=e("./invariant"),g=(e("./isEventSupported"),e("./keyOf")),E=(e("./monitorCodeUse"),p.deleteListener),C=p.listenTo,R=p.registrationNameModules,M={string:!0,number:!0},b=g({style:null}),O=1,D={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},x=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,P={},T={}.hasOwnProperty;i.displayName="ReactDOMComponent",i.Mixin={mountComponent:h.measure("ReactDOMComponent","mountComponent",function(e,t,r){l.Mixin.mountComponent.call(this,e,t,r),n(this.props);var o=D[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+o}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n="<"+this._tag;for(var o in t)if(t.hasOwnProperty(o)){var i=t[o];if(null!=i)if(R.hasOwnProperty(o))r(this._rootNodeID,o,i,e);else{o===b&&(i&&(i=t.style=m({},t.style)),i=a.createMarkupForStyles(i));var s=u.createMarkupForProperty(o,i);s&&(n+=" "+s)}}if(e.renderToStaticMarkup)return n+">";var c=u.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=M[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return v(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._currentElement||null==e._owner)&&l.Mixin.receiveComponent.call(this,e,t)},updateComponent:h.measure("ReactDOMComponent","updateComponent",function(e,t){n(this._currentElement.props),l.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,o,i,a=this.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===b){var u=e[n];for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else R.hasOwnProperty(n)?E(this._rootNodeID,n):(s.isStandardName[n]||s.isCustomAttribute(n))&&l.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in a){var c=a[n],p=e[n];if(a.hasOwnProperty(n)&&c!==p)if(n===b)if(c&&(c=a.style=m({},c)),p){for(o in p)!p.hasOwnProperty(o)||c&&c.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in c)c.hasOwnProperty(o)&&p[o]!==c[o]&&(i=i||{},i[o]=c[o])}else i=c;else R.hasOwnProperty(n)?r(this._rootNodeID,n,c,t):(s.isStandardName[n]||s.isCustomAttribute(n))&&l.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,c)}i&&l.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t){var n=this.props,r=M[typeof e.children]?e.children:null,o=M[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,u=null!=o?null:n.children,c=null!=r||null!=i,p=null!=o||null!=a;null!=s&&null==u?this.updateChildren(null,t):c&&!p&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&l.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),p.deleteAllListeners(this._rootNodeID),l.Mixin.unmountComponent.call(this)}},m(i.prototype,l.Mixin,i.Mixin,f.Mixin,c),t.exports=i},{"./CSSPropertyOperations":6,"./DOMProperty":12,"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactMount":68,"./ReactMultiChild":69,"./ReactPerf":73,"./escapeTextForBrowser":120,"./invariant":137,"./isEventSupported":138,"./keyOf":144,"./monitorCodeUse":147}],46:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactElement"),s=e("./ReactDOM"),u=a.createFactory(s.form.type),c=i.createClass({displayName:"ReactDOMForm",mixins:[o,r],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=c},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56}],47:[function(e,t){"use strict";var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),o=e("./DOMPropertyOperations"),i=e("./ReactMount"),a=e("./ReactPerf"),s=e("./invariant"),u=e("./setInnerHTML"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:a.measure("ReactDOMIDOperations","updatePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)}),deletePropertyByID:a.measure("ReactDOMIDOperations","deletePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)}),updateStylesByID:a.measure("ReactDOMIDOperations","updateStylesByID",function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)}),updateInnerHTMLByID:a.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(e,t){var n=i.getNode(e);u(n,t)}),updateTextContentByID:a.measure("ReactDOMIDOperations","updateTextContentByID",function(e,t){var n=i.getNode(e);r.updateTextContent(n,t)}),dangerouslyReplaceNodeWithMarkupByID:a.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)}),dangerouslyProcessChildrenUpdates:a.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)})};t.exports=l},{"./CSSPropertyOperations":6,"./DOMChildrenOperations":11,"./DOMPropertyOperations":13,"./ReactMount":68,"./ReactPerf":73,"./invariant":137,"./setInnerHTML":149}],48:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactElement"),s=e("./ReactDOM"),u=a.createFactory(s.img.type),c=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return u(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=c},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56}],49:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactElement"),c=e("./ReactDOM"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=e("./invariant"),h=u.createFactory(c.input.type),m={},v=s.createClass({displayName:"ReactDOMInput",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue;
return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=i.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=i.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,h(e,this.props.children)},componentDidMount:function(){var e=l.getID(this.getDOMNode());m[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=l.getID(e);delete m[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&o.setValueForProperty(e,"checked",this.props.checked||!1);var t=i.getValue(this);null!=t&&o.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,r=i.getOnChange(this);r&&(t=r.call(this,e)),p.asap(n,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var a=this.getDOMNode(),s=a;s.parentNode;)s=s.parentNode;for(var u=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),c=0,d=u.length;d>c;c++){var h=u[c];if(h!==a&&h.form===a.form){var v=l.getID(h);f(v);var y=m[v];f(y),p.asap(n,y)}}}return t}});t.exports=v},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactMount":68,"./ReactUpdates":88,"./invariant":137}],50:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),o=e("./ReactElement"),i=e("./ReactDOM"),a=(e("./warning"),o.createFactory(i.option.type)),s=r.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return a(this.props,this.props.children)}});t.exports=s},{"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./warning":155}],51:[function(e,t){"use strict";function n(){this.isMounted()&&(this.setState({value:this._pendingValue}),this._pendingValue=0)}function r(e,t){if(null!=e[t])if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function o(e,t){var n,r,o,i=e.props.multiple,a=null!=t?t:e.state.value,s=e.getDOMNode().options;if(i)for(n={},r=0,o=a.length;o>r;++r)n[""+a[r]]=!0;else n=""+a;for(r=0,o=s.length;o>r;r++){var u=i?n.hasOwnProperty(s[r].value):s[r].value===n;u!==s[r].selected&&(s[r].selected=u)}}var i=e("./AutoFocusMixin"),a=e("./LinkedValueUtils"),s=e("./ReactBrowserComponentMixin"),u=e("./ReactCompositeComponent"),c=e("./ReactElement"),l=e("./ReactDOM"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=c.createFactory(l.select.type),h=u.createClass({displayName:"ReactDOMSelect",mixins:[i,a.Mixin,s],propTypes:{defaultValue:r,value:r},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillMount:function(){this._pendingValue=null},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,f(e,this.props.children)},componentDidMount:function(){o(this,a.getValue(this))},componentDidUpdate:function(e){var t=a.getValue(this),n=!!e.multiple,r=!!this.props.multiple;(null!=t||n!==r)&&o(this,t)},_handleChange:function(e){var t,r=a.getOnChange(this);r&&(t=r.call(this,e));var o;if(this.props.multiple){o=[];for(var i=e.target.options,s=0,u=i.length;u>s;s++)i[s].selected&&o.push(i[s].value)}else o=e.target.value;return this._pendingValue=o,p.asap(n,this),t}});t.exports=h},{"./AutoFocusMixin":2,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactUpdates":88}],52:[function(e,t){"use strict";function n(e,t,n,r){return e===n&&t===r}function r(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function o(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var r=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,l=s.cloneRange();l.selectNodeContents(e),l.setEnd(s.startContainer,s.startOffset);var p=n(l.startContainer,l.startOffset,l.endContainer,l.endOffset),d=p?0:l.toString().length,f=d+c,h=document.createRange();h.setStart(r,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function a(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=u(e,o),l=u(e,i);if(s&&l){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p))}}}var s=e("./ExecutionEnvironment"),u=e("./getNodeForCharacterOffset"),c=e("./getTextContentAccessor"),l=s.canUseDOM&&document.selection,p={getOffsets:l?r:o,setOffsets:l?i:a};t.exports=p},{"./ExecutionEnvironment":23,"./getNodeForCharacterOffset":130,"./getTextContentAccessor":132}],53:[function(e,t){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),o=e("./DOMPropertyOperations"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactElement"),c=e("./ReactDOM"),l=e("./ReactUpdates"),p=e("./Object.assign"),d=e("./invariant"),f=(e("./warning"),u.createFactory(c.textarea.type)),h=s.createClass({displayName:"ReactDOMTextarea",mixins:[r,i.Mixin,a],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(d(null==e),Array.isArray(t)&&(d(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=i.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,f(e,this.state.initialValue)},componentDidUpdate:function(){var e=i.getValue(this);if(null!=e){var t=this.getDOMNode();o.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,r=i.getOnChange(this);return r&&(t=r.call(this,e)),l.asap(n,this),t}});t.exports=h},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":56,"./ReactUpdates":88,"./invariant":137,"./warning":155}],54:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),o=e("./Transaction"),i=e("./Object.assign"),a=e("./emptyFunction"),s={initialize:a,close:function(){p.isBatchingUpdates=!1}},u={initialize:a,close:r.flushBatchedUpdates.bind(r)},c=[u,s];i(n.prototype,o.Mixin,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n){var r=p.isBatchingUpdates;p.isBatchingUpdates=!0,r?e(t,n):l.perform(e,null,t,n)}};t.exports=p},{"./Object.assign":29,"./ReactUpdates":88,"./Transaction":104,"./emptyFunction":118}],55:[function(e,t){"use strict";function n(){O.EventEmitter.injectReactEventListener(b),O.EventPluginHub.injectEventPluginOrder(s),O.EventPluginHub.injectInstanceHandle(D),O.EventPluginHub.injectMount(x),O.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:w,EnterLeaveEventPlugin:u,ChangeEventPlugin:o,CompositionEventPlugin:a,MobileSafariClickEventPlugin:p,SelectEventPlugin:P,BeforeInputEventPlugin:r}),O.NativeComponent.injectGenericComponentClass(m),O.NativeComponent.injectComponentClasses({button:v,form:y,img:g,input:E,option:C,select:R,textarea:M,html:S("html"),head:S("head"),body:S("body")}),O.CompositeComponent.injectMixin(d),O.DOMProperty.injectDOMPropertyConfig(l),O.DOMProperty.injectDOMPropertyConfig(_),O.EmptyComponent.injectEmptyComponent("noscript"),O.Updates.injectReconcileTransaction(f.ReactReconcileTransaction),O.Updates.injectBatchingStrategy(h),O.RootIndex.injectCreateReactRootIndex(c.canUseDOM?i.createReactRootIndex:T.createReactRootIndex),O.Component.injectEnvironment(f)}var r=e("./BeforeInputEventPlugin"),o=e("./ChangeEventPlugin"),i=e("./ClientReactRootIndex"),a=e("./CompositionEventPlugin"),s=e("./DefaultEventPluginOrder"),u=e("./EnterLeaveEventPlugin"),c=e("./ExecutionEnvironment"),l=e("./HTMLDOMPropertyConfig"),p=e("./MobileSafariClickEventPlugin"),d=e("./ReactBrowserComponentMixin"),f=e("./ReactComponentBrowserEnvironment"),h=e("./ReactDefaultBatchingStrategy"),m=e("./ReactDOMComponent"),v=e("./ReactDOMButton"),y=e("./ReactDOMForm"),g=e("./ReactDOMImg"),E=e("./ReactDOMInput"),C=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),b=e("./ReactEventListener"),O=e("./ReactInjection"),D=e("./ReactInstanceHandles"),x=e("./ReactMount"),P=e("./SelectEventPlugin"),T=e("./ServerReactRootIndex"),w=e("./SimpleEventPlugin"),_=e("./SVGDOMPropertyConfig"),S=e("./createFullPageComponent");t.exports={inject:n}},{"./BeforeInputEventPlugin":3,"./ChangeEventPlugin":8,"./ClientReactRootIndex":9,"./CompositionEventPlugin":10,"./DefaultEventPluginOrder":15,"./EnterLeaveEventPlugin":16,"./ExecutionEnvironment":23,"./HTMLDOMPropertyConfig":24,"./MobileSafariClickEventPlugin":28,"./ReactBrowserComponentMixin":32,"./ReactComponentBrowserEnvironment":38,"./ReactDOMButton":44,"./ReactDOMComponent":45,"./ReactDOMForm":46,"./ReactDOMImg":48,"./ReactDOMInput":49,"./ReactDOMOption":50,"./ReactDOMSelect":51,"./ReactDOMTextarea":53,"./ReactDefaultBatchingStrategy":54,"./ReactEventListener":61,"./ReactInjection":62,"./ReactInstanceHandles":64,"./ReactMount":68,"./SVGDOMPropertyConfig":89,"./SelectEventPlugin":90,"./ServerReactRootIndex":91,"./SimpleEventPlugin":92,"./createFullPageComponent":113}],56:[function(e,t){"use strict";var n=e("./ReactContext"),r=e("./ReactCurrentOwner"),o=(e("./warning"),{key:!0,ref:!0}),i=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=o,this.props=i};i.prototype={_isReactElement:!0},i.createElement=function(e,t,a){var s,u={},c=null,l=null;if(null!=t){l=void 0===t.ref?null:t.ref,c=null==t.key?null:""+t.key;for(s in t)t.hasOwnProperty(s)&&!o.hasOwnProperty(s)&&(u[s]=t[s])}var p=arguments.length-2;if(1===p)u.children=a;else if(p>1){for(var d=Array(p),f=0;p>f;f++)d[f]=arguments[f+2];u.children=d}if(e.defaultProps){var h=e.defaultProps;for(s in h)"undefined"==typeof u[s]&&(u[s]=h[s])}return new i(e,c,l,r.current,n.current,u)},i.createFactory=function(e){var t=i.createElement.bind(null,e);return t.type=e,t},i.cloneAndReplaceProps=function(e,t){var n=new i(e.type,e.key,e.ref,e._owner,e._context,t);return n},i.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=i},{"./ReactContext":41,"./ReactCurrentOwner":42,"./warning":155}],57:[function(e,t){"use strict";function n(){var e=p.current;return e&&e.constructor.displayName||void 0}function r(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,i("react_key_warning",'Each child in an array should have a unique "key" prop.',e,t))}function o(e,t,n){v.test(e)&&i("react_numeric_key_warning","Child objects should have non-numeric keys so ordering is preserved.",t,n)}function i(e,t,r,o){var i=n(),a=o.displayName,s=i||a,u=f[e];if(!u.hasOwnProperty(s)){u[s]=!0,t+=i?" Check the render method of "+i+".":" Check the renderComponent call using <"+a+">.";var c=null;r._owner&&r._owner!==p.current&&(c=r._owner.constructor.displayName,t+=" It was passed a child from "+c+"."),t+=" See http://fb.me/react-warning-keys for more information.",d(e,{component:s,componentOwner:c}),console.warn(t)}}function a(){var e=n()||"";h.hasOwnProperty(e)||(h[e]=!0,d("react_object_map_children"))}function s(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var i=e[n];c.isValidElement(i)&&r(i,t)}else if(c.isValidElement(e))e._store.validated=!0;else if(e&&"object"==typeof e){a();for(var s in e)o(s,e[s],t)}}function u(e,t,n,r){for(var o in t)if(t.hasOwnProperty(o)){var i;try{i=t[o](n,o,e,r)}catch(a){i=a}i instanceof Error&&!(i.message in m)&&(m[i.message]=!0,d("react_failed_descriptor_type_check",{message:i.message}))}}var c=e("./ReactElement"),l=e("./ReactPropTypeLocations"),p=e("./ReactCurrentOwner"),d=e("./monitorCodeUse"),f={react_key_warning:{},react_numeric_key_warning:{}},h={},m={},v=/^\d+$/,y={createElement:function(e){var t=c.createElement.apply(this,arguments);if(null==t)return t;for(var n=2;n<arguments.length;n++)s(arguments[n],e);var r=e.displayName;return e.propTypes&&u(r,e.propTypes,t.props,l.prop),e.contextTypes&&u(r,e.contextTypes,t._context,l.context),t},createFactory:function(e){var t=y.createElement.bind(null,e);return t.type=e,t}};t.exports=y},{"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactPropTypeLocations":76,"./monitorCodeUse":147}],58:[function(e,t){"use strict";function n(){return u(a),a()}function r(e){c[e]=!0}function o(e){delete c[e]}function i(e){return c[e]}var a,s=e("./ReactElement"),u=e("./invariant"),c={},l={injectEmptyComponent:function(e){a=s.createFactory(e)}},p={deregisterNullComponentID:o,getEmptyComponent:n,injection:l,isNullComponentID:i,registerNullComponentID:r};t.exports=p},{"./ReactElement":56,"./invariant":137}],59:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],60:[function(e,t){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e("./EventPluginHub"),o={handleTopLevel:function(e,t,o,i){var a=r.extractEvents(e,t,o,i);n(a)}};t.exports=o},{"./EventPluginHub":19}],61:[function(e,t){"use strict";function n(e){var t=l.getID(e),n=c.getReactRootIDFromNodeID(t),r=l.findReactContainerForID(n),o=l.getFirstReactDOM(r);return o}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){for(var t=l.getFirstReactDOM(f(e.nativeEvent))||window,r=t;r;)e.ancestors.push(r),r=n(r);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=l.getID(t)||"";m._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=h(window);e(t)}var a=e("./EventListener"),s=e("./ExecutionEnvironment"),u=e("./PooledClass"),c=e("./ReactInstanceHandles"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./Object.assign"),f=e("./getEventTarget"),h=e("./getUnboundedScrollPosition");d(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var m={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){m._handleTopLevel=e},setEnabled:function(e){m._enabled=!!e},isEnabled:function(){return m._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,m.dispatchEvent.bind(null,e)):void 0},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,m.dispatchEvent.bind(null,e)):void 0},monitorScrollValue:function(e){var t=i.bind(null,e);a.listen(window,"scroll",t),a.listen(window,"resize",t)},dispatchEvent:function(e,t){if(m._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=m},{"./EventListener":18,"./ExecutionEnvironment":23,"./Object.assign":29,"./PooledClass":30,"./ReactInstanceHandles":64,"./ReactMount":68,"./ReactUpdates":88,"./getEventTarget":128,"./getUnboundedScrollPosition":133}],62:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),o=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactEmptyComponent"),s=e("./ReactBrowserEventEmitter"),u=e("./ReactNativeComponent"),c=e("./ReactPerf"),l=e("./ReactRootIndex"),p=e("./ReactUpdates"),d={Component:o.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EmptyComponent:a.injection,EventPluginHub:r.injection,EventEmitter:s.injection,NativeComponent:u.injection,Perf:c.injection,RootIndex:l.injection,Updates:p.injection};t.exports=d},{"./DOMProperty":12,"./EventPluginHub":19,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactEmptyComponent":58,"./ReactNativeComponent":71,"./ReactPerf":73,"./ReactRootIndex":80,"./ReactUpdates":88}],63:[function(e,t){"use strict";function n(e){return o(document.documentElement,e)}var r=e("./ReactDOMSelection"),o=e("./containsNode"),i=e("./focusNode"),a=e("./getActiveElement"),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),r=e.focusedElem,o=e.selectionRange;t!==r&&n(r)&&(s.hasSelectionCapabilities(r)&&s.setSelection(r,o),i(r))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};t.exports=s},{"./ReactDOMSelection":52,"./containsNode":111,"./focusNode":122,"./getActiveElement":124}],64:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function r(e,t){return e.charAt(t)===d||t===e.length}function o(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(o(e)&&o(t)),p(i(e,t)),e===t)return e;for(var n=e.length+f,a=n;a<t.length&&!r(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(o(s)),s}function c(e,t,n,r,o,u){e=e||"",t=t||"",p(e!==t);var c=i(t,e);p(c||i(e,t));for(var l=0,d=c?a:s,f=e;;f=d(f,t)){var m;if(o&&f===e||u&&f===t||(m=n(f,c,r)),m===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,m={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=m},{"./ReactRootIndex":80,"./invariant":137}],65:[function(e,t){"use strict";function n(e,t){if("function"==typeof t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];if("function"==typeof r){var o=r.bind(t);for(var i in r)r.hasOwnProperty(i)&&(o[i]=r[i]);e[n]=o}else e[n]=r}}var r=(e("./ReactCurrentOwner"),e("./invariant")),o=(e("./monitorCodeUse"),e("./warning"),{}),i={},a={};a.wrapCreateFactory=function(e){var t=function(t){return"function"!=typeof t?e(t):t.isReactNonLegacyFactory?e(t.type):t.isReactLegacyFactory?e(t.type):t};return t},a.wrapCreateElement=function(e){var t=function(t){if("function"!=typeof t)return e.apply(this,arguments);var n;return t.isReactNonLegacyFactory?(n=Array.prototype.slice.call(arguments,0),n[0]=t.type,e.apply(this,n)):t.isReactLegacyFactory?(t._isMockFunction&&(t.type._mockedReactClassConstructor=t),n=Array.prototype.slice.call(arguments,0),n[0]=t.type,e.apply(this,n)):t.apply(null,Array.prototype.slice.call(arguments,1))};return t},a.wrapFactory=function(e){r("function"==typeof e);var t=function(){return e.apply(this,arguments)};return n(t,e.type),t.isReactLegacyFactory=o,t.type=e.type,t},a.markNonLegacyFactory=function(e){return e.isReactNonLegacyFactory=i,e},a.isValidFactory=function(e){return"function"==typeof e&&e.isReactLegacyFactory===o},a.isValidClass=function(e){return a.isValidFactory(e)},a._isLegacyCallWarningEnabled=!0,t.exports=a},{"./ReactCurrentOwner":42,"./invariant":137,"./monitorCodeUse":147,"./warning":155}],66:[function(e,t){"use strict";function n(e,t){this.value=e,this.requestChange=t}function r(e){var t={value:"undefined"==typeof e?o.PropTypes.any.isRequired:e.isRequired,requestChange:o.PropTypes.func.isRequired};return o.PropTypes.shape(t)}var o=e("./React");n.PropTypes={link:r},t.exports=n},{"./React":31}],67:[function(e,t){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{"./adler32":107}],68:[function(e,t){"use strict";function n(e){var t=E(e);return t&&I.getID(t)}function r(e){var t=o(e);if(t)if(x.hasOwnProperty(t)){var n=x[t];n!==e&&(R(!s(n,t)),x[t]=e)}else x[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(D)||""}function i(e,t){var n=o(e);n!==t&&delete x[n],e.setAttribute(D,t),x[t]=e}function a(e){return x.hasOwnProperty(e)&&s(x[e],e)||(x[e]=I.findReactNodeByID(e)),x[e]}function s(e,t){if(e){R(o(e)===t);var n=I.findReactContainerForID(t);if(n&&y(n,e))return!0}return!1}function u(e){delete x[e]}function c(e){var t=x[e];return t&&s(t,e)?void(N=t):!1}function l(e){N=null,m.traverseAncestors(e,c);var t=N;return N=null,t}var p=e("./DOMProperty"),d=e("./ReactBrowserEventEmitter"),f=(e("./ReactCurrentOwner"),e("./ReactElement")),h=e("./ReactLegacyElement"),m=e("./ReactInstanceHandles"),v=e("./ReactPerf"),y=e("./containsNode"),g=e("./deprecated"),E=e("./getReactRootElementInContainer"),C=e("./instantiateReactComponent"),R=e("./invariant"),M=e("./shouldUpdateReactComponent"),b=(e("./warning"),h.wrapCreateElement(f.createElement)),O=m.SEPARATOR,D=p.ID_ATTRIBUTE_NAME,x={},P=1,T=9,w={},_={},S=[],N=null,I={_instancesByReactRootID:w,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){var o=t.props;return I.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){R(t&&(t.nodeType===P||t.nodeType===T)),d.ensureScrollValueMonitoring();var n=I.registerContainer(t);return w[n]=e,n},_renderNewRootComponent:v.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var r=C(e,null),o=I._registerComponent(r,t);return r.mountComponentIntoNode(o,t,n),r}),render:function(e,t,r){R(f.isValidElement(e));var o=w[n(t)];if(o){var i=o._currentElement;if(M(i,e))return I._updateRootComponent(o,e,t,r);I.unmountComponentAtNode(t)}var a=E(t),s=a&&I.isRenderedByReact(a),u=s&&!o,c=I._renderNewRootComponent(e,t,u);return r&&r.call(c),c},constructAndRenderComponent:function(e,t,n){var r=b(e,t);return I.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return R(r),I.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=n(e);return t&&(t=m.getReactRootIDFromNodeID(t)),t||(t=m.createReactRootID()),_[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),r=w[t];return r?(I.unmountComponentFromNode(r,e),delete w[t],delete _[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===T&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=m.getReactRootIDFromNodeID(e),n=_[t];return n},findReactNodeByID:function(e){var t=I.findReactContainerForID(e);return I.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=I.getID(e);return t?t.charAt(0)===O:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(I.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=S,r=0,o=l(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=I.getID(a);s?t===s?i=a:m.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,R(!1)},getReactRootID:n,getID:r,setID:i,getNode:a,purgeID:u};I.renderComponent=g("ReactMount","renderComponent","render",this,I.render),t.exports=I},{"./DOMProperty":12,"./ReactBrowserEventEmitter":33,"./ReactCurrentOwner":42,"./ReactElement":56,"./ReactInstanceHandles":64,"./ReactLegacyElement":65,"./ReactPerf":73,"./containsNode":111,"./deprecated":117,"./getReactRootElementInContainer":131,"./instantiateReactComponent":136,"./invariant":137,"./shouldUpdateReactComponent":151,"./warning":155}],69:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function o(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){h.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(h,m),s())}function s(){h.length=0,m.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t){var n=l(e),r=[],o=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a,null);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,t,this._mountDepth+1);s._mountIndex=o,r.push(c),o++}}return r},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():a())}},updateChildren:function(e,t){f++;var n=!0;try{this._updateChildren(e,t),n=!1}finally{f--,f||(n?s():a())}},_updateChildren:function(e,t){var n=l(e),r=this._renderedChildren;if(n||r){var o,i=0,a=0;for(o in n)if(n.hasOwnProperty(o)){var s=r&&r[o],u=s&&s._currentElement,c=n[o];if(d(u,c))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(c,t),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,o));var f=p(c,null);this._mountChildByNameAtIndex(f,o,a,t)}a++}for(o in r)!r.hasOwnProperty(o)||n&&n[o]||this._unmountChildByName(r[o],o)}},unmountChildren:function(){var e=this._renderedChildren;for(var t in e){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){o(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r){var o=this._rootNodeID+t,i=e.mountComponent(o,r,this._mountDepth+1);e._mountIndex=n,this.createChild(e,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[t]=e},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null,e.unmountComponent(),delete this._renderedChildren[t]}}};t.exports=v},{"./ReactComponent":37,"./ReactMultiChildUpdateTypes":70,"./flattenChildren":121,"./instantiateReactComponent":136,"./shouldUpdateReactComponent":151}],70:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{"./keyMirror":143}],71:[function(e,t){"use strict";function n(e,t,n){var r=a[e];return null==r?(o(i),new i(e,t)):n===e?(o(i),new i(e,t)):new r.type(t)}var r=e("./Object.assign"),o=e("./invariant"),i=null,a={},s={injectGenericComponentClass:function(e){i=e},injectComponentClasses:function(e){r(a,e)}},u={createInstanceForTag:n,injection:s};t.exports=u},{"./Object.assign":29,"./invariant":137}],72:[function(e,t){"use strict";var n=e("./emptyObject"),r=e("./invariant"),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.refs[t]===e&&n.detachRef(t)},Mixin:{construct:function(){this.refs=n},attachRef:function(e,t){r(t.isOwnedBy(this));var o=this.refs===n?this.refs={}:this.refs;o[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=o},{"./emptyObject":119,"./invariant":137}],73:[function(e,t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measure:function(e,t,n){return n},injection:{injectMeasure:function(e){r.storedMeasure=e}}};t.exports=r},{}],74:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}function r(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=c[n];r&&c.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var o=e("./Object.assign"),i=e("./emptyFunction"),a=e("./invariant"),s=e("./joinClasses"),u=(e("./warning"),n(function(e,t){return o({},t,e)})),c={children:i,className:n(s),style:u},l={TransferStrategies:c,mergeProps:function(e,t){return r(o({},e),t)},Mixin:{transferPropsTo:function(e){return a(e._owner===this),r(e.props,this.props),e}}};t.exports=l},{"./Object.assign":29,"./emptyFunction":118,"./invariant":137,"./joinClasses":142,"./warning":155}],75:[function(e,t){"use strict";var n={};t.exports=n},{}],76:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":143}],77:[function(e,t){"use strict";function n(e){function t(t,n,r,o,i){if(o=o||C,null!=n[r])return e(n,r,o,i);var a=y[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):void 0}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,r,o){var i=t[n],a=h(i);if(a!==e){var s=y[o],u=m(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}}return n(t)}function o(){return n(E.thatReturns())}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=y[o],s=h(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function a(){function e(e,t,n,r){if(!v.isValidElement(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=y[o],a=e.name||C;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}}return n(t)}function u(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return;var s=y[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return n(t)}function c(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))
}for(var u in i)if(i.hasOwnProperty(u)){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function l(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return}var s=y[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return n(t)}function p(){function e(e,t,n,r){if(!f(e[t])){var o=y[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=y[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var l=c(i,u,r,o);if(l)return l}}}return n(t,"expected `object`")}function f(e){switch(typeof e){case"number":case"string":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(f);if(v.isValidElement(e))return!0;for(var t in e)if(!f(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var v=e("./ReactElement"),y=e("./ReactPropTypeLocationNames"),g=e("./deprecated"),E=e("./emptyFunction"),C="<<anonymous>>",R=a(),M=p(),b={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,element:R,instanceOf:s,node:M,objectOf:c,oneOf:u,oneOfType:l,shape:d,component:g("React.PropTypes","component","element",this,R),renderable:g("React.PropTypes","renderable","node",this,M)};t.exports=b},{"./ReactElement":56,"./ReactPropTypeLocationNames":75,"./deprecated":117,"./emptyFunction":118}],78:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),o=e("./ReactBrowserEventEmitter"),i=e("./Object.assign");i(n.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];o.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33}],79:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e("./CallbackQueue"),o=e("./PooledClass"),i=e("./ReactBrowserEventEmitter"),a=e("./ReactInputSelection"),s=e("./ReactPutListenerQueue"),u=e("./Transaction"),c=e("./Object.assign"),l={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,l,p,d],m={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n.prototype,u.Mixin,m),o.addPoolingTo(n),t.exports=n},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33,"./ReactInputSelection":63,"./ReactPutListenerQueue":78,"./Transaction":104}],80:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],81:[function(e,t){"use strict";function n(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=u(e,null),o=r.mountComponent(n,t,0);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidElement(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=u(e,null);return r.mountComponent(n,t,0)},null)}finally{s.release(t)}}var o=e("./ReactElement"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderToString:n,renderToStaticMarkup:r}},{"./ReactElement":56,"./ReactInstanceHandles":64,"./ReactMarkupChecksum":67,"./ReactServerRenderingTransaction":82,"./instantiateReactComponent":136,"./invariant":137}],82:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=o.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e("./PooledClass"),o=e("./CallbackQueue"),i=e("./ReactPutListenerQueue"),a=e("./Transaction"),s=e("./Object.assign"),u=e("./emptyFunction"),c={initialize:function(){this.reactMountReady.reset()},close:u},l={initialize:function(){this.putListenerQueue.reset()},close:u},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};s(n.prototype,a.Mixin,d),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactPutListenerQueue":78,"./Transaction":104,"./emptyFunction":118}],83:[function(e,t){"use strict";function n(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var r={createStateSetter:function(e,t){return function(n,r,o,i,a,s){var u=t.call(e,n,r,o,i,a,s);u&&e.setState(u)}},createStateKeySetter:function(e,t){var r=e.__keySetters||(e.__keySetters={});return r[t]||(r[t]=n(e,t))}};r.Mixin={createStateSetter:function(e){return r.createStateSetter(this,e)},createStateKeySetter:function(e){return r.createStateKeySetter(this,e)}},t.exports=r},{}],84:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactComponent"),o=e("./ReactElement"),i=e("./Object.assign"),a=e("./escapeTextForBrowser"),s=function(){};i(s.prototype,r.Mixin,{mountComponent:function(e,t,o){r.Mixin.mountComponent.call(this,e,t,o);var i=a(this.props);return t.renderToStaticMarkup?i:"<span "+n.createMarkupForID(e)+">"+i+"</span>"},receiveComponent:function(e){var t=e.props;t!==this.props&&(this.props=t,r.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}});var u=function(e){return new o(s,null,null,null,null,e)};u.type=s,t.exports=u},{"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactComponent":37,"./ReactElement":56,"./escapeTextForBrowser":120}],85:[function(e,t){"use strict";var n=e("./ReactChildren"),r={getChildMapping:function(e){return n.map(e,function(e){return e})},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var i in e)t.hasOwnProperty(i)?o.length&&(r[i]=o,o=[]):o.push(i);var a,s={};for(var u in t){if(r.hasOwnProperty(u))for(a=0;a<r[u].length;a++){var c=r[u][a];s[r[u][a]]=n(c)}s[u]=n(u)}for(a=0;a<o.length;a++)s[o[a]]=n(o[a]);return s}};t.exports=r},{"./ReactChildren":36}],86:[function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a){var r=a[n];for(var o in r)if(o in t){s.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}var i=e("./ExecutionEnvironment"),a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[];i.canUseDOM&&n();var u={addEndEventListener:function(e,t){return 0===s.length?void window.setTimeout(t,0):void s.forEach(function(n){r(e,n,t)})},removeEndEventListener:function(e,t){0!==s.length&&s.forEach(function(n){o(e,n,t)})}};t.exports=u},{"./ExecutionEnvironment":23}],87:[function(e,t){"use strict";var n=e("./React"),r=e("./ReactTransitionChildMapping"),o=e("./Object.assign"),i=e("./cloneWithProps"),a=e("./emptyFunction"),s=n.createClass({displayName:"ReactTransitionGroup",propTypes:{component:n.PropTypes.any,childFactory:n.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:a.thatReturnsArgument}},getInitialState:function(){return{children:r.getChildMapping(this.props.children)}},componentWillReceiveProps:function(e){var t=r.getChildMapping(e.children),n=this.state.children;this.setState({children:r.mergeChildMappings(n,t)});var o;for(o in t){var i=n&&n.hasOwnProperty(o);!t[o]||i||this.currentlyTransitioningKeys[o]||this.keysToEnter.push(o)}for(o in n){var a=t&&t.hasOwnProperty(o);!n[o]||a||this.currentlyTransitioningKeys[o]||this.keysToLeave.push(o)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=r.getChildMapping(this.props.children);if(n&&n.hasOwnProperty(e))this.performEnter(e);else{var i=o({},this.state.children);delete i[e],this.setState({children:i})}},render:function(){var e={};for(var t in this.state.children){var r=this.state.children[t];r&&(e[t]=i(this.props.childFactory(r),{ref:t}))}return n.createElement(this.props.component,this.props,e)}});t.exports=s},{"./Object.assign":29,"./React":31,"./ReactTransitionChildMapping":85,"./cloneWithProps":110,"./emptyFunction":118}],88:[function(e,t){"use strict";function n(){h(O.ReactReconcileTransaction&&g)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=O.ReactReconcileTransaction.getPooled()}function o(e,t,r){n(),g.batchedUpdates(e,t,r)}function i(e,t){return e._mountDepth-t._mountDepth}function a(e){var t=e.dirtyComponentsLength;h(t===m.length),m.sort(i);for(var n=0;t>n;n++){var r=m[n];if(r.isMounted()){var o=r._pendingCallbacks;if(r._pendingCallbacks=null,r.performUpdateIfNecessary(e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r)}}}function s(e,t){return h(!t||"function"==typeof t),n(),g.isBatchingUpdates?(m.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):void g.batchedUpdates(s,e,t)}function u(e,t){h(g.isBatchingUpdates),v.enqueue(e,t),y=!0}var c=e("./CallbackQueue"),l=e("./PooledClass"),p=(e("./ReactCurrentOwner"),e("./ReactPerf")),d=e("./Transaction"),f=e("./Object.assign"),h=e("./invariant"),m=(e("./warning"),[]),v=c.getPooled(),y=!1,g=null,E={initialize:function(){this.dirtyComponentsLength=m.length},close:function(){this.dirtyComponentsLength!==m.length?(m.splice(0,this.dirtyComponentsLength),M()):m.length=0}},C={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},R=[E,C];f(r.prototype,d.Mixin,{getTransactionWrappers:function(){return R},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,O.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return d.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),l.addPoolingTo(r);var M=p.measure("ReactUpdates","flushBatchedUpdates",function(){for(;m.length||y;){if(m.length){var e=r.getPooled();e.perform(a,null,e),r.release(e)}if(y){y=!1;var t=v;v=c.getPooled(),t.notifyAll(),c.release(t)}}}),b={injectReconcileTransaction:function(e){h(e),O.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){h(e),h("function"==typeof e.batchedUpdates),h("boolean"==typeof e.isBatchingUpdates),g=e}},O={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:M,injection:b,asap:u};t.exports=O},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactCurrentOwner":42,"./ReactPerf":73,"./Transaction":104,"./invariant":137,"./warning":155}],89:[function(e,t){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,o={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},DOMAttributeNames:{fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=o},{"./DOMProperty":12}],90:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function r(e){if(!y&&null!=h&&h==u()){var t=n(h);if(!v||!p(v,t)){v=t;var r=s.getPooled(f.select,m,e);return r.type="select",r.target=h,i.accumulateTwoPhaseDispatches(r),r}}}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ReactInputSelection"),s=e("./SyntheticEvent"),u=e("./getActiveElement"),c=e("./isTextInputElement"),l=e("./keyOf"),p=e("./shallowEqual"),d=o.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,m=null,v=null,y=!1,g={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,m=n,v=null);break;case d.topBlur:h=null,m=null,v=null;break;case d.topMouseDown:y=!0;break;case d.topContextMenu:case d.topMouseUp:return y=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=g},{"./EventConstants":17,"./EventPropagators":22,"./ReactInputSelection":63,"./SyntheticEvent":96,"./getActiveElement":124,"./isTextInputElement":140,"./keyOf":144,"./shallowEqual":150}],91:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],92:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPluginUtils"),o=e("./EventPropagators"),i=e("./SyntheticClipboardEvent"),a=e("./SyntheticEvent"),s=e("./SyntheticFocusEvent"),u=e("./SyntheticKeyboardEvent"),c=e("./SyntheticMouseEvent"),l=e("./SyntheticDragEvent"),p=e("./SyntheticTouchEvent"),d=e("./SyntheticUIEvent"),f=e("./SyntheticWheelEvent"),h=e("./getEventCharCode"),m=e("./invariant"),v=e("./keyOf"),y=(e("./warning"),n.topLevelTypes),g={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},E={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel};for(var C in E)E[C].dependencies=[C];var R={eventTypes:g,executeDispatch:function(e,t,n){var o=r.executeDispatch(e,t,n);o===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=E[e];if(!v)return null;var g;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:g=a;break;case y.topKeyPress:if(0===h(r))return null;case y.topKeyDown:case y.topKeyUp:g=u;break;case y.topBlur:case y.topFocus:g=s;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:g=c;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:g=l;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:g=p;break;case y.topScroll:g=d;break;case y.topWheel:g=f;break;case y.topCopy:case y.topCut:case y.topPaste:g=i}m(g);var C=g.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(C),C}};t.exports=R},{"./EventConstants":17,"./EventPluginUtils":21,"./EventPropagators":22,"./SyntheticClipboardEvent":93,"./SyntheticDragEvent":95,"./SyntheticEvent":96,"./SyntheticFocusEvent":97,"./SyntheticKeyboardEvent":99,"./SyntheticMouseEvent":100,"./SyntheticTouchEvent":101,"./SyntheticUIEvent":102,"./SyntheticWheelEvent":103,"./getEventCharCode":125,"./invariant":137,"./keyOf":144,"./warning":155}],93:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],94:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],95:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={dataTransfer:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":100}],96:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var a=r[o];this[o]=a?a(n):n[o]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?i.thatReturnsTrue:i.thatReturnsFalse,this.isPropagationStopped=i.thatReturnsFalse}var r=e("./PooledClass"),o=e("./Object.assign"),i=e("./emptyFunction"),a=e("./getEventTarget"),s={type:null,target:a,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=i.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=i.thatReturnsTrue},persist:function(){this.isPersistent=i.thatReturnsTrue},isPersistent:i.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=s,n.augmentClass=function(e,t){var n=this,i=Object.create(n.prototype);o(i,e.prototype),e.prototype=i,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./Object.assign":29,"./PooledClass":30,"./emptyFunction":118,"./getEventTarget":128}],97:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":102}],98:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":96}],99:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventCharCode"),i=e("./getEventKey"),a=e("./getEventModifierState"),s={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:a,charCode:function(e){return"keypress"===e.type?o(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?o(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(n,s),t.exports=n},{"./SyntheticUIEvent":102,"./getEventCharCode":125,"./getEventKey":126,"./getEventModifierState":127}],100:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),i=e("./getEventModifierState"),a={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":102,"./ViewportMetrics":105,"./getEventModifierState":127}],101:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventModifierState"),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":102,"./getEventModifierState":127}],102:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o=e("./getEventTarget"),i={view:function(e){if(e.view)return e.view;var t=o(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,i),t.exports=n},{"./SyntheticEvent":96,"./getEventTarget":128}],103:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":100}],104:[function(e,t){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,r,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var i,a=t[r],s=this.wrapperInitData[r];try{i=!0,s!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o},{"./invariant":137}],105:[function(e,t){"use strict";var n=e("./getUnboundedScrollPosition"),r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var e=n(window);r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{"./getUnboundedScrollPosition":133}],106:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n&&o?(e.push.apply(e,t),e):n?(e.push(t),e):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":137}],107:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],108:[function(e,t){function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;t.exports=n},{}],109:[function(e,t){"use strict";function n(e){return r(e.replace(o,"ms-"))}var r=e("./camelize"),o=/^-ms-/;t.exports=n},{"./camelize":108}],110:[function(e,t){"use strict";function n(e,t){var n=o.mergeProps(t,e.props);return!n.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(n.children=e.props.children),r.createElement(e.type,n)}var r=e("./ReactElement"),o=e("./ReactPropTransferer"),i=e("./keyOf"),a=(e("./warning"),i({children:null}));t.exports=n},{"./ReactElement":56,"./ReactPropTransferer":74,"./keyOf":144,"./warning":155}],111:[function(e,t){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e("./isTextNode");t.exports=n},{"./isTextNode":141}],112:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():o(e):[e]}var o=e("./toArray");t.exports=r},{"./toArray":152}],113:[function(e,t){"use strict";function n(e){var t=o.createFactory(e),n=r.createClass({displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){i(!1)},render:function(){return t(this.props)}});return n}var r=e("./ReactCompositeComponent"),o=e("./ReactElement"),i=e("./invariant");t.exports=n},{"./ReactCompositeComponent":40,"./ReactElement":56,"./invariant":137}],114:[function(e,t){function n(e){var t=e.match(c);return t&&t[1].toLowerCase()}function r(e,t){var r=u;s(!!u);var o=n(e),c=o&&a(o);if(c){r.innerHTML=c[1]+e+c[2];for(var l=c[0];l--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return d}var o=e("./ExecutionEnvironment"),i=e("./createArrayFrom"),a=e("./getMarkupWrap"),s=e("./invariant"),u=o.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=r},{"./ExecutionEnvironment":23,"./createArrayFrom":112,"./getMarkupWrap":129,"./invariant":137}],115:[function(e,t){function n(e){return"object"==typeof e?Object.keys(e).filter(function(t){return e[t]}).join(" "):Array.prototype.join.call(arguments," ")}t.exports=n},{}],116:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.hasOwnProperty(e)&&o[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=e("./CSSProperty"),o=r.isUnitlessNumber;t.exports=n},{"./CSSProperty":5}],117:[function(e,t){function n(e,t,n,r,o){return o
}e("./Object.assign"),e("./warning");t.exports=n},{"./Object.assign":29,"./warning":155}],118:[function(e,t){function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},t.exports=r},{}],119:[function(e,t){"use strict";var n={};t.exports=n},{}],120:[function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;t.exports=r},{}],121:[function(e,t){"use strict";function n(e,t,n){var r=e,i=!r.hasOwnProperty(n);if(i&&null!=t){var a,s=typeof t;a="string"===s?o(t):"number"===s?o(""+t):t,r[n]=a}}function r(e){if(null==e)return e;var t={};return i(e,n,t),t}{var o=e("./ReactTextComponent"),i=e("./traverseAllChildren");e("./warning")}t.exports=r},{"./ReactTextComponent":84,"./traverseAllChildren":153,"./warning":155}],122:[function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}t.exports=n},{}],123:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],124:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],125:[function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=n},{}],126:[function(e,t){"use strict";function n(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=r(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":""}var r=e("./getEventCharCode"),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=n},{"./getEventCharCode":125}],127:[function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=r},{}],128:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],129:[function(e,t){function n(e){return o(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var r=e("./ExecutionEnvironment"),o=e("./invariant"),i=r.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,ellipse:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};t.exports=n},{"./ExecutionEnvironment":23,"./invariant":137}],130:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3==o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}t.exports=o},{}],131:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],132:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var r=e("./ExecutionEnvironment"),o=null;t.exports=n},{"./ExecutionEnvironment":23}],133:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],134:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],135:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e("./hyphenate"),o=/^ms-/;t.exports=n},{"./hyphenate":134}],136:[function(e,t){"use strict";function n(e,t){var n;return n="string"==typeof e.type?r.createInstanceForTag(e.type,e.props,t):new e.type(e.props),n.construct(e),n}{var r=(e("./warning"),e("./ReactElement"),e("./ReactLegacyElement"),e("./ReactNativeComponent"));e("./ReactEmptyComponent")}t.exports=n},{"./ReactElement":56,"./ReactEmptyComponent":58,"./ReactLegacyElement":65,"./ReactNativeComponent":71,"./warning":155}],137:[function(e,t){"use strict";var n=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};t.exports=n},{}],138:[function(e,t){"use strict";function n(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var r,o=e("./ExecutionEnvironment");o.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":23}],139:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],140:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],141:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":139}],142:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e=(e?e+" ":"")+t);return e}t.exports=n},{}],143:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{"./invariant":137}],144:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],145:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o={};for(var i in e)r.call(e,i)&&(o[i]=t.call(n,e[i],i,e));return o}var r=Object.prototype.hasOwnProperty;t.exports=n},{}],146:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],147:[function(e,t){"use strict";function n(e){r(e&&!/[^a-z0-9_]/.test(e))}var r=e("./invariant");t.exports=n},{"./invariant":137}],148:[function(e,t){"use strict";function n(e){return o(r.isValidElement(e)),e}var r=e("./ReactElement"),o=e("./invariant");t.exports=n},{"./ReactElement":56,"./invariant":137}],149:[function(e,t){"use strict";var n=e("./ExecutionEnvironment"),r=/^[ \r\n\t\f]/,o=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,i=function(e,t){e.innerHTML=t};if(n.canUseDOM){var a=document.createElement("div");a.innerHTML=" ",""===a.innerHTML&&(i=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&o.test(t)){e.innerHTML=""+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=i},{"./ExecutionEnvironment":23}],150:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],151:[function(e,t){"use strict";function n(e,t){return e&&t&&e.type===t.type&&e.key===t.key&&e._owner===t._owner?!0:!1}t.exports=n},{}],152:[function(e,t){function n(e){var t=e.length;if(r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),r("number"==typeof t),r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var o=Array(t),i=0;t>i;i++)o[i]=e[i];return o}var r=e("./invariant");t.exports=n},{"./invariant":137}],153:[function(e,t){"use strict";function n(e){return d[e]}function r(e,t){return e&&null!=e.key?i(e.key):t.toString(36)}function o(e){return(""+e).replace(f,n)}function i(e){return"$"+o(e)}function a(e,t,n){return null==e?0:h(e,"",0,t,n)}var s=e("./ReactElement"),u=e("./ReactInstanceHandles"),c=e("./invariant"),l=u.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,o,a){var u,d,f=0;if(Array.isArray(e))for(var m=0;m<e.length;m++){var v=e[m];u=t+(t?p:l)+r(v,m),d=n+f,f+=h(v,u,d,o,a)}else{var y=typeof e,g=""===t,E=g?l+r(e,0):t;if(null==e||"boolean"===y)o(a,null,E,n),f=1;else if("string"===y||"number"===y||s.isValidElement(e))o(a,e,E,n),f=1;else if("object"===y){c(!e||1!==e.nodeType);for(var C in e)e.hasOwnProperty(C)&&(u=t+(t?p:l)+i(C)+p+r(e[C],0),d=n+f,f+=h(e[C],u,d,o,a))}}return f};t.exports=a},{"./ReactElement":56,"./ReactInstanceHandles":64,"./invariant":137}],154:[function(e,t){"use strict";function n(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?i(new e.constructor,e):e}function r(e,t,n){s(Array.isArray(e));var r=t[n];s(Array.isArray(r))}function o(e,t){if(s("object"==typeof t),t.hasOwnProperty(p))return s(1===Object.keys(t).length),t[p];var a=n(e);if(t.hasOwnProperty(d)){var h=t[d];s(h&&"object"==typeof h),s(a&&"object"==typeof a),i(a,t[d])}t.hasOwnProperty(u)&&(r(e,t,u),t[u].forEach(function(e){a.push(e)})),t.hasOwnProperty(c)&&(r(e,t,c),t[c].forEach(function(e){a.unshift(e)})),t.hasOwnProperty(l)&&(s(Array.isArray(e)),s(Array.isArray(t[l])),t[l].forEach(function(e){s(Array.isArray(e)),a.splice.apply(a,e)})),t.hasOwnProperty(f)&&(s("function"==typeof t[f]),a=t[f](a));for(var v in t)m.hasOwnProperty(v)&&m[v]||(a[v]=o(e[v],t[v]));return a}var i=e("./Object.assign"),a=e("./keyOf"),s=e("./invariant"),u=a({$push:null}),c=a({$unshift:null}),l=a({$splice:null}),p=a({$set:null}),d=a({$merge:null}),f=a({$apply:null}),h=[u,c,l,p,d,f],m={};h.forEach(function(e){m[e]=!0}),t.exports=o},{"./Object.assign":29,"./invariant":137,"./keyOf":144}],155:[function(e,t){"use strict";var n=e("./emptyFunction"),r=n;t.exports=r},{"./emptyFunction":118}]},{},[1])(1)}); |
app/assets/javascripts/actions/eventsActions.js | loggingroads/onboarding | import React from 'react';
export const SET_EVENTS_LIST = 'SET_EVENTS_LIST';
export const SET_EVENT_DETAIL = 'SET_EVENT_DETAIL';
export function setEventsList() {
const url = '/api/v1/events';
return function(dispatch) {
$.get(url).then(function(eventsList){
dispatch({
type: SET_EVENTS_LIST,
eventsList
});
});
};
}
export function setEventDetail(id) {
const url = `/api/v1/events/${id}`;
return function(dispatch) {
$.get(url).then(function(eventDetail){
dispatch({
type: SET_EVENT_DETAIL,
eventDetail
});
});
};
}
|
src/components/AboutPage.spec.js | daitobedai/NoCode | import React from 'react';
import {shallow} from 'enzyme';
import {expect} from 'chai';
import AboutPage from './AboutPage';
describe('<AboutPage />', () => {
it('should have a header called \'About\'', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.find('h2').text();
const expected = 'About';
expect(actual).to.equal(expected);
});
it('should have a header with \'alt-header\' class', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.find('h2').prop('className');
const expected = 'alt-header';
expect(actual).to.equal(expected);
});
it('should link to an unknown route path', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.findWhere(n => n.prop('to') === '/badlink').length;
const expected = 1;
expect(actual).to.be.equal(expected);
});
});
|
app/components/Menu/OptionsMenu.js | ivtpz/brancher | import React from 'react';
import { Link } from 'react-router';
import * as styles from './Menu.scss';
export default ({ links }) => {
return (
<div className={styles.pageContainer}>
<div className={styles.menuContainer}>
<div className={styles.optionsCircle}>
{links.map(link => (
<Link to={link.path}><div className={styles.menuLink}>{link.text}</div></Link>
))}
<Link to='/'><div className={styles.menuLink}>Main Menu</div></Link>
</div>
</div>
</div>
);
};
|
ajax/libs/core-js/0.9.14/library.js | brix/cdnjs | /**
* core-js 0.9.14
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2015 Denis Pushkarev
*/
!function(undefined){
'use strict';
var __e = null, __g = null;
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
__webpack_require__(17);
__webpack_require__(22);
__webpack_require__(24);
__webpack_require__(26);
__webpack_require__(28);
__webpack_require__(29);
__webpack_require__(30);
__webpack_require__(31);
__webpack_require__(32);
__webpack_require__(33);
__webpack_require__(34);
__webpack_require__(38);
__webpack_require__(39);
__webpack_require__(40);
__webpack_require__(41);
__webpack_require__(43);
__webpack_require__(44);
__webpack_require__(47);
__webpack_require__(48);
__webpack_require__(50);
__webpack_require__(52);
__webpack_require__(53);
__webpack_require__(54);
__webpack_require__(55);
__webpack_require__(56);
__webpack_require__(60);
__webpack_require__(63);
__webpack_require__(64);
__webpack_require__(66);
__webpack_require__(67);
__webpack_require__(69);
__webpack_require__(70);
__webpack_require__(71);
__webpack_require__(73);
__webpack_require__(74);
__webpack_require__(75);
__webpack_require__(76);
__webpack_require__(77);
__webpack_require__(79);
__webpack_require__(80);
__webpack_require__(81);
__webpack_require__(82);
__webpack_require__(84);
__webpack_require__(85);
__webpack_require__(86);
__webpack_require__(87);
__webpack_require__(88);
__webpack_require__(89);
__webpack_require__(90);
__webpack_require__(91);
__webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
__webpack_require__(96);
__webpack_require__(97);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, cel = __webpack_require__(4)
, cof = __webpack_require__(5)
, $def = __webpack_require__(9)
, invoke = __webpack_require__(10)
, arrayMethod = __webpack_require__(11)
, IE_PROTO = __webpack_require__(8).safe('__proto__')
, assert = __webpack_require__(13)
, assertObject = assert.obj
, ObjectProto = Object.prototype
, html = $.html
, A = []
, _slice = A.slice
, _join = A.join
, classof = cof.classof
, has = $.has
, defineProperty = $.setDesc
, getOwnDescriptor = $.getDesc
, defineProperties = $.setDescs
, isFunction = $.isFunction
, isObject = $.isObject
, toObject = $.toObject
, toLength = $.toLength
, toIndex = $.toIndex
, IE8_DOM_DEFINE = false
, $indexOf = __webpack_require__(14)(false)
, $forEach = arrayMethod(0)
, $map = arrayMethod(1)
, $filter = arrayMethod(2)
, $some = arrayMethod(3)
, $every = arrayMethod(4);
if(!$.DESC){
try {
IE8_DOM_DEFINE = defineProperty(cel('div'), 'x',
{get: function(){ return 8; }}
).x == 8;
} catch(e){ /* empty */ }
$.setDesc = function(O, P, Attributes){
if(IE8_DOM_DEFINE)try {
return defineProperty(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)assertObject(O)[P] = Attributes.value;
return O;
};
$.getDesc = function(O, P){
if(IE8_DOM_DEFINE)try {
return getOwnDescriptor(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]);
};
$.setDescs = defineProperties = function(O, Properties){
assertObject(O);
var keys = $.getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)$.setDesc(O, P = keys[i++], Properties[P]);
return O;
};
}
$def($def.S + $def.F * !$.DESC, 'Object', {
// 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $.getDesc,
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
defineProperty: $.setDesc,
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
defineProperties: defineProperties
});
// IE 8- don't enum bug keys
var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' +
'toLocaleString,toString,valueOf').split(',')
// Additional keys for getOwnPropertyNames
, keys2 = keys1.concat('length', 'prototype')
, keysLen1 = keys1.length;
// Create object with `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = cel('iframe')
, i = keysLen1
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict.prototype[keys1[i]];
return createDict();
};
function createGetKeys(names, length){
return function(object){
var O = toObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(length > i)if(has(O, key = names[i++])){
~$indexOf(result, key) || result.push(key);
}
return result;
};
}
function Empty(){}
$def($def.S, 'Object', {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
getPrototypeOf: $.getProto = $.getProto || function(O){
O = Object(assert.def(O));
if(has(O, IE_PROTO))return O[IE_PROTO];
if(isFunction(O.constructor) && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
},
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true),
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
create: $.create = $.create || function(O, /*?*/Properties){
var result;
if(O !== null){
Empty.prototype = assertObject(O);
result = new Empty();
Empty.prototype = null;
// add "__proto__" for Object.getPrototypeOf shim
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : defineProperties(result, Properties);
},
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false),
// 19.1.2.17 / 15.2.3.8 Object.seal(O)
seal: function seal(it){
return it; // <- cap
},
// 19.1.2.5 / 15.2.3.9 Object.freeze(O)
freeze: function freeze(it){
return it; // <- cap
},
// 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O)
preventExtensions: function preventExtensions(it){
return it; // <- cap
},
// 19.1.2.13 / 15.2.3.11 Object.isSealed(O)
isSealed: function isSealed(it){
return !isObject(it); // <- cap
},
// 19.1.2.12 / 15.2.3.12 Object.isFrozen(O)
isFrozen: function isFrozen(it){
return !isObject(it); // <- cap
},
// 19.1.2.11 / 15.2.3.13 Object.isExtensible(O)
isExtensible: function isExtensible(it){
return isObject(it); // <- cap
}
});
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
$def($def.P, 'Function', {
bind: function(that /*, args... */){
var fn = assert.fn(this)
, partArgs = _slice.call(arguments, 1);
function bound(/* args... */){
var args = partArgs.concat(_slice.call(arguments))
, constr = this instanceof bound
, ctx = constr ? $.create(fn.prototype) : that
, result = invoke(fn, args, ctx);
return constr ? ctx : result;
}
if(fn.prototype)bound.prototype = fn.prototype;
return bound;
}
});
// Fix for not array-like ES3 string and DOM objects
if(!(0 in Object('z') && 'z'[0] == 'z')){
$.ES5Object = function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
}
var buggySlice = true;
try {
if(html)_slice.call(html);
buggySlice = false;
} catch(e){ /* empty */ }
$def($def.P + $def.F * buggySlice, 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return _slice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
$def($def.P + $def.F * ($.ES5Object != Object), 'Array', {
join: function join(){
return _join.apply($.ES5Object(this), arguments);
}
});
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
$def($def.S, 'Array', {
isArray: function(arg){
return cof(arg) == 'Array';
}
});
function createArrayReduce(isRight){
return function(callbackfn, memo){
assert.fn(callbackfn);
var O = toObject(this)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(arguments.length < 2)for(;;){
if(index in O){
memo = O[index];
index += i;
break;
}
index += i;
assert(isRight ? index >= 0 : length > index, 'Reduce of empty array with no initial value');
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in O){
memo = callbackfn(memo, O[index], index, this);
}
return memo;
};
}
$def($def.P, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: $.each = $.each || function forEach(callbackfn/*, that = undefined */){
return $forEach(this, callbackfn, arguments[1]);
},
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn/*, that = undefined */){
return $map(this, callbackfn, arguments[1]);
},
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn/*, that = undefined */){
return $filter(this, callbackfn, arguments[1]);
},
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn/*, that = undefined */){
return $some(this, callbackfn, arguments[1]);
},
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn/*, that = undefined */){
return $every(this, callbackfn, arguments[1]);
},
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: createArrayReduce(false),
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: createArrayReduce(true),
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(el /*, fromIndex = 0 */){
return $indexOf(this, el, arguments[1]);
},
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function(el, fromIndex /* = @[*-1] */){
var O = toObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, $.toInteger(fromIndex));
if(index < 0)index = toLength(length + index);
for(;index >= 0; index--)if(index in O)if(O[index] === el)return index;
return -1;
}
});
// 21.1.3.25 / 15.5.4.20 String.prototype.trim()
$def($def.P, 'String', {trim: __webpack_require__(15)(/^\s*([\s\S]*\S)?\s*$/, '$1')});
// 20.3.3.1 / 15.9.4.4 Date.now()
$def($def.S, 'Date', {now: function(){
return +new Date;
}});
function lz(num){
return num > 9 ? num : '0' + num;
}
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
// PhantomJS and old webkit had a broken Date implementation.
var date = new Date(-5e13 - 1)
, brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z'
&& __webpack_require__(16)(function(){ new Date(NaN).toISOString(); }));
$def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){
if(!isFinite(this))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}});
if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){
var tag = classof(it);
return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag;
};
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = typeof self != 'undefined' ? self : Function('return this')()
, core = {}
, defineProperty = Object.defineProperty
, hasOwnProperty = {}.hasOwnProperty
, ceil = Math.ceil
, floor = Math.floor
, max = Math.max
, min = Math.min;
// The engine works fine with descriptors? Thank's IE8 for his funny defineProperty.
var DESC = !!function(){
try {
return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2;
} catch(e){ /* empty */ }
}();
var hide = createDefiner(1);
// 7.1.4 ToInteger
function toInteger(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
}
function desc(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
}
function simpleSet(object, key, value){
object[key] = value;
return object;
}
function createDefiner(bitmap){
return DESC ? function(object, key, value){
return $.setDesc(object, key, desc(bitmap, value));
} : simpleSet;
}
function isObject(it){
return it !== null && (typeof it == 'object' || typeof it == 'function');
}
function isFunction(it){
return typeof it == 'function';
}
function assertDefined(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
}
var $ = module.exports = __webpack_require__(3)({
g: global,
core: core,
html: global.document && document.documentElement,
// http://jsperf.com/core-js-isobject
isObject: isObject,
isFunction: isFunction,
that: function(){
return this;
},
// 7.1.4 ToInteger
toInteger: toInteger,
// 7.1.15 ToLength
toLength: function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
},
toIndex: function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
},
has: function(it, key){
return hasOwnProperty.call(it, key);
},
create: Object.create,
getProto: Object.getPrototypeOf,
DESC: DESC,
desc: desc,
getDesc: Object.getOwnPropertyDescriptor,
setDesc: defineProperty,
setDescs: Object.defineProperties,
getKeys: Object.keys,
getNames: Object.getOwnPropertyNames,
getSymbols: Object.getOwnPropertySymbols,
assertDefined: assertDefined,
// Dummy, fix for not array-like ES3 string in es5 module
ES5Object: Object,
toObject: function(it){
return $.ES5Object(assertDefined(it));
},
hide: hide,
def: createDefiner(0),
set: global.Symbol ? simpleSet : hide,
each: [].forEach
});
/* eslint-disable no-undef */
if(typeof __e != 'undefined')__e = core;
if(typeof __g != 'undefined')__g = global;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function($){
$.FW = false;
$.path = $.core;
return $;
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, document = $.g.document
, isObject = $.isObject
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, TAG = __webpack_require__(6)('toStringTag')
, toString = {}.toString;
function cof(it){
return toString.call(it).slice(8, -1);
}
cof.classof = function(it){
var O, T;
return it == undefined ? it === undefined ? 'Undefined' : 'Null'
: typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O);
};
cof.set = function(it, tag, stat){
if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag);
};
module.exports = cof;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2).g
, store = __webpack_require__(7)('wks');
module.exports = function(name){
return store[name] || (store[name] =
global.Symbol && global.Symbol[name] || __webpack_require__(8).safe('Symbol.' + name));
};
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, SHARED = '__core-js_shared__'
, store = $.g[SHARED] || $.hide($.g, SHARED, {})[SHARED];
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var sid = 0;
function uid(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++sid + Math.random()).toString(36));
}
uid.safe = __webpack_require__(2).g.Symbol || uid;
module.exports = uid;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, global = $.g
, core = $.core
, isFunction = $.isFunction;
function ctx(fn, that){
return function(){
return fn.apply(that, arguments);
};
}
// type bitmap
$def.F = 1; // forced
$def.G = 2; // global
$def.S = 4; // static
$def.P = 8; // proto
$def.B = 16; // bind
$def.W = 32; // wrap
function $def(type, name, source){
var key, own, out, exp
, isGlobal = type & $def.G
, isProto = type & $def.P
, target = isGlobal ? global : type & $def.S
? global[name] : (global[name] || {}).prototype
, exports = isGlobal ? core : core[name] || (core[name] = {});
if(isGlobal)source = name;
for(key in source){
// contains in native
own = !(type & $def.F) && target && key in target;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
if(isGlobal && !isFunction(target[key]))exp = source[key];
// bind timers to global for call from export context
else if(type & $def.B && own)exp = ctx(out, global);
// wrap global constructors for prevent change them in library
else if(type & $def.W && target[key] == out)!function(C){
exp = function(param){
return this instanceof C ? new C(param) : C(param);
};
exp.prototype = C.prototype;
}(out);
else exp = isProto && isFunction(out) ? ctx(Function.call, out) : out;
// export
exports[key] = exp;
if(isProto)(exports.prototype || (exports.prototype = {}))[key] = out;
}
}
module.exports = $def;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
// Fast apply
// http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4])
: fn.call(that, args[0], args[1], args[2], args[3], args[4]);
} return fn.apply(that, args);
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12);
module.exports = function(TYPE){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function($this, callbackfn, that){
var O = Object($.assertDefined($this))
, self = $.ES5Object(O)
, f = ctx(callbackfn, that, 3)
, length = $.toLength(self.length)
, index = 0
, result = IS_MAP ? Array(length) : IS_FILTER ? [] : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
// Optional / simple context binding
var assertFunction = __webpack_require__(13).fn;
module.exports = function(fn, that, length){
assertFunction(fn);
if(~length && that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
} return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2);
function assert(condition, msg1, msg2){
if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1);
}
assert.def = $.assertDefined;
assert.fn = function(it){
if(!$.isFunction(it))throw TypeError(it + ' is not a function!');
return it;
};
assert.obj = function(it){
if(!$.isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
assert.inst = function(it, Constructor, name){
if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!");
return it;
};
module.exports = assert;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var $ = __webpack_require__(2);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = $.toObject($this)
, length = $.toLength(O.length)
, index = $.toIndex(fromIndex, length)
, value;
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = function(regExp, replace, isStatic){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(isStatic ? it : this).replace(regExp, replacer);
};
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function(exec){
try {
exec();
return false;
} catch(e){
return true;
}
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var $ = __webpack_require__(2)
, setTag = __webpack_require__(5).set
, uid = __webpack_require__(8)
, shared = __webpack_require__(7)
, $def = __webpack_require__(9)
, $redef = __webpack_require__(18)
, keyOf = __webpack_require__(19)
, enumKeys = __webpack_require__(20)
, assertObject = __webpack_require__(13).obj
, ObjectProto = Object.prototype
, DESC = $.DESC
, has = $.has
, $create = $.create
, getDesc = $.getDesc
, setDesc = $.setDesc
, desc = $.desc
, $names = __webpack_require__(21)
, getNames = $names.get
, toObject = $.toObject
, $Symbol = $.g.Symbol
, setter = false
, TAG = uid('tag')
, HIDDEN = uid('hidden')
, _propertyIsEnumerable = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, useNative = $.isFunction($Symbol);
var setSymbolDesc = DESC ? function(){ // fallback for old Android
try {
return $create(setDesc({}, HIDDEN, {
get: function(){
return setDesc(this, HIDDEN, {value: false})[HIDDEN];
}
}))[HIDDEN] || setDesc;
} catch(e){
return function(it, key, D){
var protoDesc = getDesc(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
setDesc(it, key, D);
if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc);
};
}
}() : setDesc;
function wrap(tag){
var sym = AllSymbols[tag] = $.set($create($Symbol.prototype), TAG, tag);
DESC && setter && setSymbolDesc(ObjectProto, tag, {
configurable: true,
set: function(value){
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, desc(1, value));
}
});
return sym;
}
function defineProperty(it, key, D){
if(D && has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = $create(D, {enumerable: desc(0, false)});
} return setSymbolDesc(it, key, D);
} return setDesc(it, key, D);
}
function defineProperties(it, P){
assertObject(it);
var keys = enumKeys(P = toObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)defineProperty(it, key = keys[i++], P[key]);
return it;
}
function create(it, P){
return P === undefined ? $create(it) : defineProperties($create(it), P);
}
function propertyIsEnumerable(key){
var E = _propertyIsEnumerable.call(this, key);
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key]
? E : true;
}
function getOwnPropertyDescriptor(it, key){
var D = getDesc(it = toObject(it), key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
}
function getOwnPropertyNames(it){
var names = getNames(toObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key);
return result;
}
function getOwnPropertySymbols(it){
var names = getNames(toObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]);
return result;
}
// 19.4.1.1 Symbol([description])
if(!useNative){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor');
return wrap(uid(arguments[0]));
};
$redef($Symbol.prototype, 'toString', function(){
return this[TAG];
});
$.create = create;
$.setDesc = defineProperty;
$.getDesc = getOwnPropertyDescriptor;
$.setDescs = defineProperties;
$.getNames = $names.get = getOwnPropertyNames;
$.getSymbols = getOwnPropertySymbols;
if($.DESC && $.FW)$redef(ObjectProto, 'propertyIsEnumerable', propertyIsEnumerable, true);
}
var symbolStatics = {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
return keyOf(SymbolRegistry, key);
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
};
// 19.4.2.2 Symbol.hasInstance
// 19.4.2.3 Symbol.isConcatSpreadable
// 19.4.2.4 Symbol.iterator
// 19.4.2.6 Symbol.match
// 19.4.2.8 Symbol.replace
// 19.4.2.9 Symbol.search
// 19.4.2.10 Symbol.species
// 19.4.2.11 Symbol.split
// 19.4.2.12 Symbol.toPrimitive
// 19.4.2.13 Symbol.toStringTag
// 19.4.2.14 Symbol.unscopables
$.each.call((
'hasInstance,isConcatSpreadable,iterator,match,replace,search,' +
'species,split,toPrimitive,toStringTag,unscopables'
).split(','), function(it){
var sym = __webpack_require__(6)(it);
symbolStatics[it] = useNative ? sym : wrap(sym);
}
);
setter = true;
$def($def.G + $def.W, {Symbol: $Symbol});
$def($def.S, 'Symbol', symbolStatics);
$def($def.S + $def.F * !useNative, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: getOwnPropertySymbols
});
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setTag($.g.JSON, 'JSON', true);
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2).hide;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2);
module.exports = function(object, el){
var O = $.toObject(object)
, keys = $.getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2);
module.exports = function(it){
var keys = $.getKeys(it)
, getDesc = $.getDesc
, getSymbols = $.getSymbols;
if(getSymbols)$.each.call(getSymbols(it), function(key){
if(getDesc(it, key).enumerable)keys.push(key);
});
return keys;
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var $ = __webpack_require__(2)
, toString = {}.toString
, getNames = $.getNames;
var windowNames = typeof window == 'object' && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
function getWindowNames(it){
try {
return getNames(it);
} catch(e){
return windowNames.slice();
}
}
module.exports.get = function getOwnPropertyNames(it){
if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it);
return getNames($.toObject(it));
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $def = __webpack_require__(9);
$def($def.S, 'Object', {assign: __webpack_require__(23)});
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, enumKeys = __webpack_require__(20);
// 19.1.2.1 Object.assign(target, source, ...)
/* eslint-disable no-unused-vars */
module.exports = Object.assign || function assign(target, source){
/* eslint-enable no-unused-vars */
var T = Object($.assertDefined(target))
, l = arguments.length
, i = 1;
while(l > i){
var S = $.ES5Object(arguments[i++])
, keys = enumKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)T[key = keys[j++]] = S[key];
}
return T;
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $def = __webpack_require__(9);
$def($def.S, 'Object', {
is: __webpack_require__(25)
});
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $def = __webpack_require__(9);
$def($def.S, 'Object', {setPrototypeOf: __webpack_require__(27).set});
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var $ = __webpack_require__(2)
, assert = __webpack_require__(13);
function check(O, proto){
assert.obj(O);
assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!");
}
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line
? function(buggy, set){
try {
set = __webpack_require__(12)(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2);
set({}, []);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}()
: undefined),
check: check
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, isObject = $.isObject
, toObject = $.toObject;
$.each.call(('freeze,seal,preventExtensions,isFrozen,isSealed,isExtensible,' +
'getOwnPropertyDescriptor,getPrototypeOf,keys,getOwnPropertyNames').split(',')
, function(KEY, ID){
var fn = ($.core.Object || {})[KEY] || Object[KEY]
, forced = 0
, method = {};
method[KEY] = ID == 0 ? function freeze(it){
return isObject(it) ? fn(it) : it;
} : ID == 1 ? function seal(it){
return isObject(it) ? fn(it) : it;
} : ID == 2 ? function preventExtensions(it){
return isObject(it) ? fn(it) : it;
} : ID == 3 ? function isFrozen(it){
return isObject(it) ? fn(it) : true;
} : ID == 4 ? function isSealed(it){
return isObject(it) ? fn(it) : true;
} : ID == 5 ? function isExtensible(it){
return isObject(it) ? fn(it) : false;
} : ID == 6 ? function getOwnPropertyDescriptor(it, key){
return fn(toObject(it), key);
} : ID == 7 ? function getPrototypeOf(it){
return fn(Object($.assertDefined(it)));
} : ID == 8 ? function keys(it){
return fn(toObject(it));
} : __webpack_require__(21).get;
try {
fn('z');
} catch(e){
forced = 1;
}
$def($def.S + $def.F * forced, 'Object', method);
});
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, HAS_INSTANCE = __webpack_require__(6)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){
if(!$.isFunction(this) || !$.isObject(O))return false;
if(!$.isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = $.getProto(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, abs = Math.abs
, floor = Math.floor
, _isFinite = $.g.isFinite
, MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991;
function isInteger(it){
return !$.isObject(it) && _isFinite(it) && floor(it) === it;
}
$def($def.S, 'Number', {
// 20.1.2.1 Number.EPSILON
EPSILON: Math.pow(2, -52),
// 20.1.2.2 Number.isFinite(number)
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
},
// 20.1.2.3 Number.isInteger(number)
isInteger: isInteger,
// 20.1.2.4 Number.isNaN(number)
isNaN: function isNaN(number){
return number != number;
},
// 20.1.2.5 Number.isSafeInteger(number)
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER;
},
// 20.1.2.6 Number.MAX_SAFE_INTEGER
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
// 20.1.2.10 Number.MIN_SAFE_INTEGER
MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER,
// 20.1.2.12 Number.parseFloat(string)
parseFloat: parseFloat,
// 20.1.2.13 Number.parseInt(string, radix)
parseInt: parseInt
});
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
var Infinity = 1 / 0
, $def = __webpack_require__(9)
, E = Math.E
, pow = Math.pow
, abs = Math.abs
, exp = Math.exp
, log = Math.log
, sqrt = Math.sqrt
, ceil = Math.ceil
, floor = Math.floor
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
function roundTiesToEven(n){
return n + 1 / EPSILON - 1 / EPSILON;
}
// 20.2.2.28 Math.sign(x)
function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
}
// 20.2.2.5 Math.asinh(x)
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1));
}
// 20.2.2.14 Math.expm1(x)
function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1;
}
$def($def.S, 'Math', {
// 20.2.2.3 Math.acosh(x)
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x;
},
// 20.2.2.5 Math.asinh(x)
asinh: asinh,
// 20.2.2.7 Math.atanh(x)
atanh: function atanh(x){
return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2;
},
// 20.2.2.9 Math.cbrt(x)
cbrt: function cbrt(x){
return sign(x = +x) * pow(abs(x), 1 / 3);
},
// 20.2.2.11 Math.clz32(x)
clz32: function clz32(x){
return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32;
},
// 20.2.2.12 Math.cosh(x)
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
},
// 20.2.2.14 Math.expm1(x)
expm1: expm1,
// 20.2.2.16 Math.fround(x)
fround: function fround(x){
var $abs = abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
},
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, len = arguments.length
, args = Array(len)
, larg = 0
, arg;
while(i < len){
arg = args[i] = abs(arguments[i++]);
if(arg == Infinity)return Infinity;
if(arg > larg)larg = arg;
}
larg = larg || 1;
while(len--)sum += pow(args[len] / larg, 2);
return larg * sqrt(sum);
},
// 20.2.2.18 Math.imul(x, y)
imul: function imul(x, y){
var UInt16 = 0xffff
, xn = +x
, yn = +y
, xl = UInt16 & xn
, yl = UInt16 & yn;
return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0);
},
// 20.2.2.20 Math.log1p(x)
log1p: function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x);
},
// 20.2.2.21 Math.log10(x)
log10: function log10(x){
return log(x) / Math.LN10;
},
// 20.2.2.22 Math.log2(x)
log2: function log2(x){
return log(x) / Math.LN2;
},
// 20.2.2.28 Math.sign(x)
sign: sign,
// 20.2.2.30 Math.sinh(x)
sinh: function sinh(x){
return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2);
},
// 20.2.2.33 Math.tanh(x)
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
},
// 20.2.2.34 Math.trunc(x)
trunc: function trunc(it){
return (it > 0 ? floor : ceil)(it);
}
});
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9)
, toIndex = __webpack_require__(2).toIndex
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$def($def.S + $def.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, len = arguments.length
, i = 0
, code;
while(len > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9);
$def($def.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = $.toObject(callSite.raw)
, len = $.toLength(tpl.length)
, sln = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < sln)res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
var set = __webpack_require__(2).set
, $at = __webpack_require__(35)(true)
, ITER = __webpack_require__(8).safe('iter')
, $iter = __webpack_require__(36)
, step = $iter.step;
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(37)(String, 'String', function(iterated){
set(this, ITER, {o: String(iterated), i: 0});
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var iter = this[ITER]
, O = iter.o
, index = iter.i
, point;
if(index >= O.length)return step(1);
point = $at(O, index);
iter.i += point.length;
return step(0, point);
});
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// true -> String#at
// false -> String#codePointAt
var $ = __webpack_require__(2);
module.exports = function(TO_STRING){
return function(that, pos){
var s = String($.assertDefined(that))
, i = $.toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l
|| (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, cof = __webpack_require__(5)
, classof = cof.classof
, assert = __webpack_require__(13)
, assertObject = assert.obj
, SYMBOL_ITERATOR = __webpack_require__(6)('iterator')
, FF_ITERATOR = '@@iterator'
, Iterators = __webpack_require__(7)('iterators')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
setIterator(IteratorPrototype, $.that);
function setIterator(O, value){
$.hide(O, SYMBOL_ITERATOR, value);
// Add iterator for FF iterator protocol
if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value);
}
module.exports = {
// Safari has buggy iterators w/o `next`
BUGGY: 'keys' in [] && !('next' in [].keys()),
Iterators: Iterators,
step: function(done, value){
return {value: value, done: !!done};
},
is: function(it){
var O = Object(it)
, Symbol = $.g.Symbol;
return (Symbol && Symbol.iterator || FF_ITERATOR) in O
|| SYMBOL_ITERATOR in O
|| $.has(Iterators, classof(O));
},
get: function(it){
var Symbol = $.g.Symbol
, getIter;
if(it != undefined){
getIter = it[Symbol && Symbol.iterator || FF_ITERATOR]
|| it[SYMBOL_ITERATOR]
|| Iterators[classof(it)];
}
assert($.isFunction(getIter), it, ' is not iterable!');
return assertObject(getIter.call(it));
},
set: setIterator,
create: function(Constructor, NAME, next, proto){
Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)});
cof.set(Constructor, NAME + ' Iterator');
}
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9)
, $redef = __webpack_require__(18)
, $ = __webpack_require__(2)
, cof = __webpack_require__(5)
, $iter = __webpack_require__(36)
, SYMBOL_ITERATOR = __webpack_require__(6)('iterator')
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values'
, Iterators = $iter.Iterators;
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){
$iter.create(Constructor, NAME, next);
function createMethod(kind){
function $$(that){
return new Constructor(that, kind);
}
switch(kind){
case KEYS: return function keys(){ return $$(this); };
case VALUES: return function values(){ return $$(this); };
} return function entries(){ return $$(this); };
}
var TAG = NAME + ' Iterator'
, proto = Base.prototype
, _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, _default = _native || createMethod(DEFAULT)
, methods, key;
// Fix native
if(_native){
var IteratorPrototype = $.getProto(_default.call(new Base));
// Set @@toStringTag to native iterators
cof.set(IteratorPrototype, TAG, true);
// FF fix
if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that);
}
// Define iterator
if($.FW)$iter.set(proto, _default);
// Plug for library
Iterators[NAME] = _default;
Iterators[TAG] = $.that;
if(DEFAULT){
methods = {
keys: IS_SET ? _default : createMethod(KEYS),
values: DEFAULT == VALUES ? _default : createMethod(VALUES),
entries: DEFAULT != VALUES ? _default : createMethod('entries')
};
if(FORCE)for(key in methods){
if(!(key in proto))$redef(proto, key, methods[key]);
} else $def($def.P + $def.F * $iter.BUGGY, NAME, methods);
}
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $def = __webpack_require__(9)
, $at = __webpack_require__(35)(false);
$def($def.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, cof = __webpack_require__(5)
, $def = __webpack_require__(9)
, toLength = $.toLength;
// should throw error on regex
$def($def.P + $def.F * !__webpack_require__(16)(function(){ 'q'.endsWith(/./); }), 'String', {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
endsWith: function endsWith(searchString /*, endPosition = @length */){
if(cof(searchString) == 'RegExp')throw TypeError();
var that = String($.assertDefined(this))
, endPosition = arguments[1]
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
searchString += '';
return that.slice(end - searchString.length, end) === searchString;
}
});
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, cof = __webpack_require__(5)
, $def = __webpack_require__(9);
$def($def.P, 'String', {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
includes: function includes(searchString /*, position = 0 */){
if(cof(searchString) == 'RegExp')throw TypeError();
return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]);
}
});
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9);
$def($def.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(42)
});
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2);
module.exports = function repeat(count){
var str = String($.assertDefined(this))
, res = ''
, n = $.toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, cof = __webpack_require__(5)
, $def = __webpack_require__(9);
// should throw error on regex
$def($def.P + $def.F * !__webpack_require__(16)(function(){ 'q'.startsWith(/./); }), 'String', {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
startsWith: function startsWith(searchString /*, position = 0 */){
if(cof(searchString) == 'RegExp')throw TypeError();
var that = String($.assertDefined(this))
, index = $.toLength(Math.min(arguments[1], that.length));
searchString += '';
return that.slice(index, index + searchString.length) === searchString;
}
});
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, $def = __webpack_require__(9)
, $iter = __webpack_require__(36)
, call = __webpack_require__(45);
$def($def.S + $def.F * !__webpack_require__(46)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = Object($.assertDefined(arrayLike))
, mapfn = arguments[1]
, mapping = mapfn !== undefined
, f = mapping ? ctx(mapfn, arguments[2], 2) : undefined
, index = 0
, length, result, step, iterator;
if($iter.is(O)){
iterator = $iter.get(O);
// strange IE quirks mode bug -> use typeof instead of isFunction
result = new (typeof this == 'function' ? this : Array);
for(; !(step = iterator.next()).done; index++){
result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value;
}
} else {
// strange IE quirks mode bug -> use typeof instead of isFunction
result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length));
for(; length > index; index++){
result[index] = mapping ? f(O[index], index) : O[index];
}
}
result.length = index;
return result;
}
});
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var assertObject = __webpack_require__(13).obj;
function close(iterator){
var ret = iterator['return'];
if(ret !== undefined)assertObject(ret.call(iterator));
}
function call(iterator, fn, value, entries){
try {
return entries ? fn(assertObject(value)[0], value[1]) : fn(value);
} catch(e){
close(iterator);
throw e;
}
}
call.close = close;
module.exports = call;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
var SYMBOL_ITERATOR = __webpack_require__(6)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][SYMBOL_ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec){
if(!SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[SYMBOL_ITERATOR]();
iter.next = function(){ safe = true; };
arr[SYMBOL_ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9);
$def($def.S, 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, length = arguments.length
// strange IE quirks mode bug -> use typeof instead of isFunction
, result = new (typeof this == 'function' ? this : Array)(length);
while(length > index)result[index] = arguments[index++];
result.length = length;
return result;
}
});
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, setUnscope = __webpack_require__(49)
, ITER = __webpack_require__(8).safe('iter')
, $iter = __webpack_require__(36)
, step = $iter.step
, Iterators = $iter.Iterators;
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
__webpack_require__(37)(Array, 'Array', function(iterated, kind){
$.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind});
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var iter = this[ITER]
, O = iter.o
, kind = iter.k
, index = iter.i++;
if(!O || index >= O.length){
iter.o = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
setUnscope('keys');
setUnscope('values');
setUnscope('entries');
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var $ = __webpack_require__(2)
, UNSCOPABLES = __webpack_require__(6)('unscopables');
if($.FW && !(UNSCOPABLES in []))$.hide(Array.prototype, UNSCOPABLES, {});
module.exports = function(key){
if($.FW)[][UNSCOPABLES][key] = true;
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(51)(Array);
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, SPECIES = __webpack_require__(6)('species');
module.exports = function(C){
if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, {
configurable: true,
get: $.that
});
};
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, toIndex = $.toIndex;
$def($def.P, 'Array', {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){
var O = Object($.assertDefined(this))
, len = $.toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments[2]
, fin = end === undefined ? len : toIndex(end, len)
, count = Math.min(fin - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from = from + count - 1;
to = to + count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
}
});
__webpack_require__(49)('copyWithin');
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, toIndex = $.toIndex;
$def($def.P, 'Array', {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
fill: function fill(value /*, start = 0, end = @length */){
var O = Object($.assertDefined(this))
, length = $.toLength(O.length)
, index = toIndex(arguments[1], length)
, end = arguments[2]
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
}
});
__webpack_require__(49)('fill');
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var KEY = 'find'
, $def = __webpack_require__(9)
, forced = true
, $find = __webpack_require__(11)(5);
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$def($def.P + $def.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments[1]);
}
});
__webpack_require__(49)(KEY);
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var KEY = 'findIndex'
, $def = __webpack_require__(9)
, forced = true
, $find = __webpack_require__(11)(6);
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$def($def.P + $def.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments[1]);
}
});
__webpack_require__(49)(KEY);
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, cof = __webpack_require__(5)
, $def = __webpack_require__(9)
, assert = __webpack_require__(13)
, forOf = __webpack_require__(57)
, setProto = __webpack_require__(27).set
, same = __webpack_require__(25)
, species = __webpack_require__(51)
, SPECIES = __webpack_require__(6)('species')
, RECORD = __webpack_require__(8).safe('record')
, PROMISE = 'Promise'
, global = $.g
, process = global.process
, asap = process && process.nextTick || __webpack_require__(58).set
, P = global[PROMISE]
, isFunction = $.isFunction
, isObject = $.isObject
, assertFunction = assert.fn
, assertObject = assert.obj
, Wrapper;
function testResolve(sub){
var test = new P(function(){});
if(sub)test.constructor = Object;
return P.resolve(test) === test;
}
var useNative = function(){
var works = false;
function P2(x){
var self = new P(x);
setProto(self, P2.prototype);
return self;
}
try {
works = isFunction(P) && isFunction(P.resolve) && testResolve();
setProto(P2, P);
P2.prototype = $.create(P.prototype, {constructor: {value: P2}});
// actual Firefox has broken subclass support, test that
if(!(P2.resolve(5).then(function(){}) instanceof P2)){
works = false;
}
} catch(e){ works = false; }
return works;
}();
// helpers
function isPromise(it){
return isObject(it) && (useNative ? cof.classof(it) == 'Promise' : RECORD in it);
}
function sameConstructor(a, b){
// library wrapper special case
if(!$.FW && a === P && b === Wrapper)return true;
return same(a, b);
}
function getConstructor(C){
var S = assertObject(C)[SPECIES];
return S != undefined ? S : C;
}
function isThenable(it){
var then;
if(isObject(it))then = it.then;
return isFunction(then) ? then : false;
}
function notify(record){
var chain = record.c;
if(chain.length)asap(function(){
var value = record.v
, ok = record.s == 1
, i = 0;
function run(react){
var cb = ok ? react.ok : react.fail
, ret, then;
try {
if(cb){
if(!ok)record.h = true;
ret = cb === true ? value : cb(value);
if(ret === react.P){
react.rej(TypeError('Promise-chain cycle'));
} else if(then = isThenable(ret)){
then.call(ret, react.res, react.rej);
} else react.res(ret);
} else react.rej(value);
} catch(err){
react.rej(err);
}
}
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
chain.length = 0;
});
}
function isUnhandled(promise){
var record = promise[RECORD]
, chain = record.a || record.c
, i = 0
, react;
if(record.h)return false;
while(chain.length > i){
react = chain[i++];
if(react.fail || !isUnhandled(react.P))return false;
} return true;
}
function $reject(value){
var record = this
, promise;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
record.v = value;
record.s = 2;
record.a = record.c.slice();
setTimeout(function(){
asap(function(){
if(isUnhandled(promise = record.p)){
if(cof(process) == 'process'){
process.emit('unhandledRejection', value, promise);
} else if(global.console && isFunction(console.error)){
console.error('Unhandled promise rejection', value);
}
}
record.a = undefined;
});
}, 1);
notify(record);
}
function $resolve(value){
var record = this
, then, wrapper;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
try {
if(then = isThenable(value)){
wrapper = {r: record, d: false}; // wrap
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} else {
record.v = value;
record.s = 1;
notify(record);
}
} catch(err){
$reject.call(wrapper || {r: record, d: false}, err); // wrap
}
}
// constructor polyfill
if(!useNative){
// 25.4.3.1 Promise(executor)
P = function Promise(executor){
assertFunction(executor);
var record = {
p: assert.inst(this, P, PROMISE), // <- promise
c: [], // <- awaiting reactions
a: undefined, // <- checked in isUnhandled reactions
s: 0, // <- state
d: false, // <- done
v: undefined, // <- value
h: false // <- handled rejection
};
$.hide(this, RECORD, record);
try {
executor(ctx($resolve, record, 1), ctx($reject, record, 1));
} catch(err){
$reject.call(record, err);
}
};
__webpack_require__(59)(P.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var S = assertObject(assertObject(this).constructor)[SPECIES];
var react = {
ok: isFunction(onFulfilled) ? onFulfilled : true,
fail: isFunction(onRejected) ? onRejected : false
};
var promise = react.P = new (S != undefined ? S : P)(function(res, rej){
react.res = assertFunction(res);
react.rej = assertFunction(rej);
});
var record = this[RECORD];
record.c.push(react);
if(record.a)record.a.push(react);
if(record.s)notify(record);
return promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
}
// export
$def($def.G + $def.W + $def.F * !useNative, {Promise: P});
cof.set(P, PROMISE);
species(P);
species(Wrapper = $.core[PROMISE]);
// statics
$def($def.S + $def.F * !useNative, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
return new (getConstructor(this))(function(res, rej){ rej(r); });
}
});
$def($def.S + $def.F * (!useNative || testResolve(true)), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
return isPromise(x) && sameConstructor(x.constructor, this)
? x : new this(function(res){ res(x); });
}
});
$def($def.S + $def.F * !(useNative && __webpack_require__(46)(function(iter){
P.all(iter)['catch'](function(){});
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = getConstructor(this)
, values = [];
return new C(function(res, rej){
forOf(iterable, false, values.push, values);
var remaining = values.length
, results = Array(remaining);
if(remaining)$.each.call(values, function(promise, index){
C.resolve(promise).then(function(value){
results[index] = value;
--remaining || res(results);
}, rej);
});
else res(results);
});
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = getConstructor(this);
return new C(function(res, rej){
forOf(iterable, false, function(promise){
C.resolve(promise).then(res, rej);
});
});
}
});
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(12)
, get = __webpack_require__(36).get
, call = __webpack_require__(45);
module.exports = function(iterable, entries, fn, that){
var iterator = get(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, step;
while(!(step = iterator.next()).done){
if(call(iterator, f, step.value, entries) === false){
return call.close(iterator);
}
}
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, cof = __webpack_require__(5)
, invoke = __webpack_require__(10)
, cel = __webpack_require__(4)
, global = $.g
, isFunction = $.isFunction
, html = $.html
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, postMessage = global.postMessage
, addEventListener = global.addEventListener
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
function run(){
var id = +this;
if($.has(queue, id)){
var fn = queue[id];
delete queue[id];
fn();
}
}
function listner(event){
run.call(event.data);
}
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!isFunction(setTask) || !isFunction(clearTask)){
setTask = function(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(isFunction(fn) ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function(id){
delete queue[id];
};
// Node.js 0.8-
if(cof(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Modern browsers, skip implementation for WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is object
} else if(addEventListener && isFunction(postMessage) && !global.importScripts){
defer = function(id){
postMessage(id, '*');
};
addEventListener('message', listner, false);
// WebWorkers
} else if(isFunction(MessageChannel)){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listner;
defer = ctx(port.postMessage, port, 1);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
var $redef = __webpack_require__(18);
module.exports = function(target, src){
for(var key in src)$redef(target, key, src[key]);
return target;
};
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(61);
// 23.1 Map Objects
__webpack_require__(62)('Map', function(get){
return function Map(){ return get(this, arguments[0]); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, safe = __webpack_require__(8).safe
, assert = __webpack_require__(13)
, forOf = __webpack_require__(57)
, step = __webpack_require__(36).step
, $has = $.has
, set = $.set
, isObject = $.isObject
, hide = $.hide
, isExtensible = Object.isExtensible || isObject
, ID = safe('id')
, O1 = safe('O1')
, LAST = safe('last')
, FIRST = safe('first')
, ITER = safe('iter')
, SIZE = $.DESC ? safe('size') : 'size'
, id = 0;
function fastKey(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!$has(it, ID)){
// can't set id to frozen object
if(!isExtensible(it))return 'F';
// not necessary to add id
if(!create)return 'E';
// add missing object id
hide(it, ID, ++id);
// return object id with prefix
} return 'O' + it[ID];
}
function getEntry(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that[O1][index];
// frozen object case
for(entry = that[FIRST]; entry; entry = entry.n){
if(entry.k == key)return entry;
}
}
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
assert.inst(that, C, NAME);
set(that, O1, $.create(null));
set(that, SIZE, 0);
set(that, LAST, undefined);
set(that, FIRST, undefined);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
__webpack_require__(59)(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that[FIRST] = that[LAST] = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that[O1][entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that[FIRST] == entry)that[FIRST] = next;
if(that[LAST] == entry)that[LAST] = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments[1], 3)
, entry;
while(entry = entry ? entry.n : this[FIRST]){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if($.DESC)$.setDesc(C.prototype, 'size', {
get: function(){
return assert.def(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that[LAST] = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that[LAST], // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that[FIRST])that[FIRST] = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that[O1][index] = entry;
} return that;
},
getEntry: getEntry,
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
setIter: function(C, NAME, IS_MAP){
__webpack_require__(37)(C, NAME, function(iterated, kind){
set(this, ITER, {o: iterated, k: kind});
}, function(){
var iter = this[ITER]
, kind = iter.k
, entry = iter.l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){
// or finish the iteration
iter.o = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
}
};
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, BUGGY = __webpack_require__(36).BUGGY
, forOf = __webpack_require__(57)
, species = __webpack_require__(51)
, assertInstance = __webpack_require__(13).inst;
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = $.g[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
function fixMethod(KEY){
if($.FW){
var fn = proto[KEY];
__webpack_require__(18)(proto, KEY,
KEY == 'delete' ? function(a){ return fn.call(this, a === 0 ? 0 : a); }
: KEY == 'has' ? function has(a){ return fn.call(this, a === 0 ? 0 : a); }
: KEY == 'get' ? function get(a){ return fn.call(this, a === 0 ? 0 : a); }
: KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
}
}
if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
__webpack_require__(59)(C.prototype, methods);
C.prototype.constructor = C;
} else {
var inst = new C
, chain = inst[ADDER](IS_WEAK ? {} : -0, 1)
, buggyZero;
// wrap for init collections from iterable
if(!__webpack_require__(46)(function(iter){ new C(iter); })){ // eslint-disable-line no-new
C = wrapper(function(target, iterable){
assertInstance(target, C, NAME);
var that = new Base;
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
if($.FW)proto.constructor = C;
}
IS_WEAK || inst.forEach(function(val, key){
buggyZero = 1 / key === -Infinity;
});
// fix converting -0 key to +0
if(buggyZero){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
// + fix .add & .set for chaining
if(buggyZero || chain !== inst)fixMethod(ADDER);
}
__webpack_require__(5).set(C, NAME);
O[NAME] = C;
$def($def.G + $def.W + $def.F * (C != Base), O);
species(C);
species($.core[NAME]); // for wrapper
if(!IS_WEAK)common.setIter(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(61);
// 23.2 Set Objects
__webpack_require__(62)('Set', function(get){
return function Set(){ return get(this, arguments[0]); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, weak = __webpack_require__(65)
, leakStore = weak.leakStore
, ID = weak.ID
, WEAK = weak.WEAK
, has = $.has
, isObject = $.isObject
, isExtensible = Object.isExtensible || isObject
, tmp = {};
// 23.3 WeakMap Objects
var $WeakMap = __webpack_require__(62)('WeakMap', function(get){
return function WeakMap(){ return get(this, arguments[0]); };
}, {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
if(!isExtensible(key))return leakStore(this).get(key);
if(has(key, WEAK))return key[WEAK][this[ID]];
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
}, weak, true, true);
// IE11 WeakMap frozen keys fix
if($.FW && new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
$.each.call(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
__webpack_require__(18)(proto, key, function(a, b){
// store frozen objects on leaky map
if(isObject(a) && !isExtensible(a)){
var result = leakStore(this)[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, safe = __webpack_require__(8).safe
, assert = __webpack_require__(13)
, forOf = __webpack_require__(57)
, $has = $.has
, isObject = $.isObject
, hide = $.hide
, isExtensible = Object.isExtensible || isObject
, id = 0
, ID = safe('id')
, WEAK = safe('weak')
, LEAK = safe('leak')
, method = __webpack_require__(11)
, find = method(5)
, findIndex = method(6);
function findFrozen(store, key){
return find(store.array, function(it){
return it[0] === key;
});
}
// fallback for frozen keys
function leakStore(that){
return that[LEAK] || hide(that, LEAK, {
array: [],
get: function(key){
var entry = findFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findFrozen(this, key);
},
set: function(key, value){
var entry = findFrozen(this, key);
if(entry)entry[1] = value;
else this.array.push([key, value]);
},
'delete': function(key){
var index = findIndex(this.array, function(it){
return it[0] === key;
});
if(~index)this.array.splice(index, 1);
return !!~index;
}
})[LEAK];
}
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
$.set(assert.inst(that, C, NAME), ID, id++);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
__webpack_require__(59)(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
if(!isExtensible(key))return leakStore(this)['delete'](key);
return $has(key, WEAK) && $has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
if(!isExtensible(key))return leakStore(this).has(key);
return $has(key, WEAK) && $has(key[WEAK], this[ID]);
}
});
return C;
},
def: function(that, key, value){
if(!isExtensible(assert.obj(key))){
leakStore(that).set(key, value);
} else {
$has(key, WEAK) || hide(key, WEAK, {});
key[WEAK][that[ID]] = value;
} return that;
},
leakStore: leakStore,
WEAK: WEAK,
ID: ID
};
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(65);
// 23.4 WeakSet Objects
__webpack_require__(62)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments[0]); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, setProto = __webpack_require__(27)
, $iter = __webpack_require__(36)
, ITERATOR = __webpack_require__(6)('iterator')
, ITER = __webpack_require__(8).safe('iter')
, step = $iter.step
, assert = __webpack_require__(13)
, isObject = $.isObject
, getProto = $.getProto
, $Reflect = $.g.Reflect
, _apply = Function.apply
, assertObject = assert.obj
, _isExtensible = Object.isExtensible || isObject
, _preventExtensions = Object.preventExtensions
// IE TP has broken Reflect.enumerate
, buggyEnumerate = !($Reflect && $Reflect.enumerate && ITERATOR in $Reflect.enumerate({}));
function Enumerate(iterated){
$.set(this, ITER, {o: iterated, k: undefined, i: 0});
}
$iter.create(Enumerate, 'Object', function(){
var iter = this[ITER]
, keys = iter.k
, key;
if(keys == undefined){
iter.k = keys = [];
for(key in iter.o)keys.push(key);
}
do {
if(iter.i >= keys.length)return step(1);
} while(!((key = keys[iter.i++]) in iter.o));
return step(0, key);
});
var reflect = {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(target, thisArgument, argumentsList);
},
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
construct: function construct(target, argumentsList /*, newTarget*/){
var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype
, instance = $.create(isObject(proto) ? proto : Object.prototype)
, result = _apply.call(target, instance, argumentsList);
return isObject(result) ? result : instance;
},
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
defineProperty: function defineProperty(target, propertyKey, attributes){
assertObject(target);
try {
$.setDesc(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
},
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
deleteProperty: function deleteProperty(target, propertyKey){
var desc = $.getDesc(assertObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
},
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
get: function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc = $.getDesc(assertObject(target), propertyKey), proto;
if(desc)return $.has(desc, 'value')
? desc.value
: desc.get === undefined
? undefined
: desc.get.call(receiver);
return isObject(proto = getProto(target))
? get(proto, propertyKey, receiver)
: undefined;
},
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return $.getDesc(assertObject(target), propertyKey);
},
// 26.1.8 Reflect.getPrototypeOf(target)
getPrototypeOf: function getPrototypeOf(target){
return getProto(assertObject(target));
},
// 26.1.9 Reflect.has(target, propertyKey)
has: function has(target, propertyKey){
return propertyKey in target;
},
// 26.1.10 Reflect.isExtensible(target)
isExtensible: function isExtensible(target){
return _isExtensible(assertObject(target));
},
// 26.1.11 Reflect.ownKeys(target)
ownKeys: __webpack_require__(68),
// 26.1.12 Reflect.preventExtensions(target)
preventExtensions: function preventExtensions(target){
assertObject(target);
try {
if(_preventExtensions)_preventExtensions(target);
return true;
} catch(e){
return false;
}
},
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
set: function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = $.getDesc(assertObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getProto(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = $.desc(0);
}
if($.has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = $.getDesc(receiver, propertyKey) || $.desc(0);
existingDescriptor.value = V;
$.setDesc(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
};
// 26.1.14 Reflect.setPrototypeOf(target, proto)
if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
};
$def($def.G, {Reflect: {}});
$def($def.S + $def.F * buggyEnumerate, 'Reflect', {
// 26.1.5 Reflect.enumerate(target)
enumerate: function enumerate(target){
return new Enumerate(assertObject(target));
}
});
$def($def.S, 'Reflect', reflect);
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, assertObject = __webpack_require__(13).obj;
module.exports = function ownKeys(it){
assertObject(it);
var keys = $.getNames(it)
, getSymbols = $.getSymbols;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $def = __webpack_require__(9)
, $includes = __webpack_require__(14)(true);
$def($def.P, 'Array', {
// https://github.com/domenic/Array.prototype.includes
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments[1]);
}
});
__webpack_require__(49)('includes');
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/mathiasbynens/String.prototype.at
'use strict';
var $def = __webpack_require__(9)
, $at = __webpack_require__(35)(true);
$def($def.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $def = __webpack_require__(9)
, $pad = __webpack_require__(72);
$def($def.P, 'String', {
lpad: function lpad(n){
return $pad(this, n, arguments[1], true);
}
});
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
// http://wiki.ecmascript.org/doku.php?id=strawman:string_padding
var $ = __webpack_require__(2)
, repeat = __webpack_require__(42);
module.exports = function(that, minLength, fillChar, left){
// 1. Let O be CheckObjectCoercible(this value).
// 2. Let S be ToString(O).
var S = String($.assertDefined(that));
// 4. If intMinLength is undefined, return S.
if(minLength === undefined)return S;
// 4. Let intMinLength be ToInteger(minLength).
var intMinLength = $.toInteger(minLength);
// 5. Let fillLen be the number of characters in S minus intMinLength.
var fillLen = intMinLength - S.length;
// 6. If fillLen < 0, then throw a RangeError exception.
// 7. If fillLen is +∞, then throw a RangeError exception.
if(fillLen < 0 || fillLen === Infinity){
throw new RangeError('Cannot satisfy string length ' + minLength + ' for string: ' + S);
}
// 8. Let sFillStr be the string represented by fillStr.
// 9. If sFillStr is undefined, let sFillStr be a space character.
var sFillStr = fillChar === undefined ? ' ' : String(fillChar);
// 10. Let sFillVal be a String made of sFillStr, repeated until fillLen is met.
var sFillVal = repeat.call(sFillStr, Math.ceil(fillLen / sFillStr.length));
// truncate if we overflowed
if(sFillVal.length > fillLen)sFillVal = left
? sFillVal.slice(sFillVal.length - fillLen)
: sFillVal.slice(0, fillLen);
// 11. Return a string made from sFillVal, followed by S.
// 11. Return a String made from S, followed by sFillVal.
return left ? sFillVal.concat(S) : S.concat(sFillVal);
};
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $def = __webpack_require__(9)
, $pad = __webpack_require__(72);
$def($def.P, 'String', {
rpad: function rpad(n){
return $pad(this, n, arguments[1], false);
}
});
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/kangax/9698100
var $def = __webpack_require__(9);
$def($def.S, 'RegExp', {
escape: __webpack_require__(15)(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true)
});
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/WebReflection/9353781
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, ownKeys = __webpack_require__(68);
$def($def.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = $.toObject(object)
, result = {};
$.each.call(ownKeys(O), function(key){
$.setDesc(result, key, $.desc(0, $.getDesc(O, key)));
});
return result;
}
});
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
// http://goo.gl/XkBrjD
var $ = __webpack_require__(2)
, $def = __webpack_require__(9);
function createObjectToArray(isEntries){
return function(object){
var O = $.toObject(object)
, keys = $.getKeys(O)
, length = keys.length
, i = 0
, result = Array(length)
, key;
if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]];
else while(length > i)result[i] = O[keys[i++]];
return result;
};
}
$def($def.S, 'Object', {
values: createObjectToArray(false),
entries: createObjectToArray(true)
});
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
__webpack_require__(78)('Map');
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $def = __webpack_require__(9)
, forOf = __webpack_require__(57);
module.exports = function(NAME){
$def($def.P, NAME, {
toJSON: function toJSON(){
var arr = [];
forOf(this, false, arr.push, arr);
return arr;
}
});
};
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
__webpack_require__(78)('Set');
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9)
, $task = __webpack_require__(58);
$def($def.G + $def.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(48);
var $ = __webpack_require__(2)
, Iterators = __webpack_require__(36).Iterators
, ITERATOR = __webpack_require__(6)('iterator')
, ArrayValues = Iterators.Array
, NL = $.g.NodeList
, HTC = $.g.HTMLCollection
, NLProto = NL && NL.prototype
, HTCProto = HTC && HTC.prototype;
if($.FW){
if(NL && !(ITERATOR in NLProto))$.hide(NLProto, ITERATOR, ArrayValues);
if(HTC && !(ITERATOR in HTCProto))$.hide(HTCProto, ITERATOR, ArrayValues);
}
Iterators.NodeList = Iterators.HTMLCollection = ArrayValues;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, invoke = __webpack_require__(10)
, partial = __webpack_require__(83)
, navigator = $.g.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
function wrap(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
$.isFunction(fn) ? fn : Function(fn)
), time);
} : set;
}
$def($def.G + $def.B + $def.F * MSIE, {
setTimeout: wrap($.g.setTimeout),
setInterval: wrap($.g.setInterval)
});
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, invoke = __webpack_require__(10)
, assertFunction = __webpack_require__(13).fn;
module.exports = function(/* ...pargs */){
var fn = assertFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = $.path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, _length = arguments.length
, j = 0, k = 0, args;
if(!holder && !_length)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(_length > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, $def = __webpack_require__(9)
, assign = __webpack_require__(23)
, keyOf = __webpack_require__(19)
, ITER = __webpack_require__(8).safe('iter')
, assert = __webpack_require__(13)
, $iter = __webpack_require__(36)
, forOf = __webpack_require__(57)
, step = $iter.step
, getKeys = $.getKeys
, toObject = $.toObject
, has = $.has;
function Dict(iterable){
var dict = $.create(null);
if(iterable != undefined){
if($iter.is(iterable)){
forOf(iterable, true, function(key, value){
dict[key] = value;
});
} else assign(dict, iterable);
}
return dict;
}
Dict.prototype = null;
function DictIterator(iterated, kind){
$.set(this, ITER, {o: toObject(iterated), a: getKeys(iterated), i: 0, k: kind});
}
$iter.create(DictIterator, 'Dict', function(){
var iter = this[ITER]
, O = iter.o
, keys = iter.a
, kind = iter.k
, key;
do {
if(iter.i >= keys.length){
iter.o = undefined;
return step(1);
}
} while(!has(O, key = keys[iter.i++]));
if(kind == 'keys' )return step(0, key);
if(kind == 'values')return step(0, O[key]);
return step(0, [key, O[key]]);
});
function createDictIter(kind){
return function(it){
return new DictIterator(it, kind);
};
}
function generic(A, B){
// strange IE quirks mode bug -> use typeof instead of isFunction
return typeof A == 'function' ? A : B;
}
// 0 -> Dict.forEach
// 1 -> Dict.map
// 2 -> Dict.filter
// 3 -> Dict.some
// 4 -> Dict.every
// 5 -> Dict.find
// 6 -> Dict.findKey
// 7 -> Dict.mapPairs
function createDictMethod(TYPE){
var IS_MAP = TYPE == 1
, IS_EVERY = TYPE == 4;
return function(object, callbackfn, that /* = undefined */){
var f = ctx(callbackfn, that, 3)
, O = toObject(object)
, result = IS_MAP || TYPE == 7 || TYPE == 2 ? new (generic(this, Dict)) : undefined
, key, val, res;
for(key in O)if(has(O, key)){
val = O[key];
res = f(val, key, object);
if(TYPE){
if(IS_MAP)result[key] = res; // map
else if(res)switch(TYPE){
case 2: result[key] = val; break; // filter
case 3: return true; // some
case 5: return val; // find
case 6: return key; // findKey
case 7: result[res[0]] = res[1]; // mapPairs
} else if(IS_EVERY)return false; // every
}
}
return TYPE == 3 || IS_EVERY ? IS_EVERY : result;
};
}
// true -> Dict.turn
// false -> Dict.reduce
function createDictReduce(IS_TURN){
return function(object, mapfn, init){
assert.fn(mapfn);
var O = toObject(object)
, keys = getKeys(O)
, length = keys.length
, i = 0
, memo, key, result;
if(IS_TURN){
memo = init == undefined ? new (generic(this, Dict)) : Object(init);
} else if(arguments.length < 3){
assert(length, 'Reduce of empty object with no initial value');
memo = O[keys[i++]];
} else memo = Object(init);
while(length > i)if(has(O, key = keys[i++])){
result = mapfn(memo, O[key], key, object);
if(IS_TURN){
if(result === false)break;
} else memo = result;
}
return memo;
};
}
var findKey = createDictMethod(6);
$def($def.G + $def.F, {Dict: Dict});
$def($def.S, 'Dict', {
keys: createDictIter('keys'),
values: createDictIter('values'),
entries: createDictIter('entries'),
forEach: createDictMethod(0),
map: createDictMethod(1),
filter: createDictMethod(2),
some: createDictMethod(3),
every: createDictMethod(4),
find: createDictMethod(5),
findKey: findKey,
mapPairs: createDictMethod(7),
reduce: createDictReduce(false),
turn: createDictReduce(true),
keyOf: keyOf,
includes: function(object, el){
return (el == el ? keyOf(object, el) : findKey(object, function(it){
return it != it;
})) !== undefined;
},
// Has / get / set own property
has: has,
get: function(object, key){
if(has(object, key))return object[key];
},
set: $.def,
isDict: function(it){
return $.isObject(it) && $.getProto(it) === Dict.prototype;
}
});
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var core = __webpack_require__(2).core
, $iter = __webpack_require__(36);
core.isIterable = $iter.is;
core.getIterator = $iter.get;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ctx = __webpack_require__(12)
, safe = __webpack_require__(8).safe
, $def = __webpack_require__(9)
, $iter = __webpack_require__(36)
, forOf = __webpack_require__(57)
, ENTRIES = safe('entries')
, FN = safe('fn')
, ITER = safe('iter')
, call = __webpack_require__(45)
, getIterator = $iter.get
, setIterator = $iter.set
, createIterator = $iter.create;
function $for(iterable, entries){
if(!(this instanceof $for))return new $for(iterable, entries);
this[ITER] = getIterator(iterable);
this[ENTRIES] = !!entries;
}
createIterator($for, 'Wrapper', function(){
return this[ITER].next();
});
var $forProto = $for.prototype;
setIterator($forProto, function(){
return this[ITER]; // unwrap
});
function createChainIterator(next){
function Iterator(iter, fn, that){
this[ITER] = getIterator(iter);
this[ENTRIES] = iter[ENTRIES];
this[FN] = ctx(fn, that, iter[ENTRIES] ? 2 : 1);
}
createIterator(Iterator, 'Chain', next, $forProto);
setIterator(Iterator.prototype, $.that); // override $forProto iterator
return Iterator;
}
var MapIter = createChainIterator(function(){
var step = this[ITER].next();
return step.done
? step
: $iter.step(0, call(this[ITER], this[FN], step.value, this[ENTRIES]));
});
var FilterIter = createChainIterator(function(){
for(;;){
var step = this[ITER].next();
if(step.done || call(this[ITER], this[FN], step.value, this[ENTRIES]))return step;
}
});
__webpack_require__(59)($forProto, {
of: function(fn, that){
forOf(this, this[ENTRIES], fn, that);
},
array: function(fn, that){
var result = [];
forOf(fn != undefined ? this.map(fn, that) : this, false, result.push, result);
return result;
},
filter: function(fn, that){
return new FilterIter(this, fn, that);
},
map: function(fn, that){
return new MapIter(this, fn, that);
}
});
$for.isIterable = $iter.is;
$for.getIterator = getIterator;
$def($def.G + $def.F, {$for: $for});
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, partial = __webpack_require__(83);
// https://esdiscuss.org/topic/promise-returning-delay-function
$def($def.G + $def.F, {
delay: function(time){
return new ($.core.Promise || $.g.Promise)(function(resolve){
setTimeout(partial.call(resolve, true), time);
});
}
});
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9);
// Placeholder
$.core._ = $.path._ = $.path._ || {};
$def($def.P + $def.F, 'Function', {
part: __webpack_require__(83)
});
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, ownKeys = __webpack_require__(68);
function define(target, mixin){
var keys = ownKeys($.toObject(mixin))
, length = keys.length
, i = 0, key;
while(length > i)$.setDesc(target, key = keys[i++], $.getDesc(mixin, key));
return target;
}
$def($def.S + $def.F, 'Object', {
isObject: $.isObject,
classof: __webpack_require__(5).classof,
define: define,
make: function(proto, mixin){
return define($.create(proto), mixin);
}
});
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, assertFunction = __webpack_require__(13).fn;
$def($def.P + $def.F, 'Array', {
turn: function(fn, target /* = [] */){
assertFunction(fn);
var memo = target == undefined ? [] : Object(target)
, O = $.ES5Object(this)
, length = $.toLength(O.length)
, index = 0;
while(length > index)if(fn(memo, O[index], index++, this) === false)break;
return memo;
}
});
__webpack_require__(49)('turn');
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ITER = __webpack_require__(8).safe('iter');
__webpack_require__(37)(Number, 'Number', function(iterated){
$.set(this, ITER, {l: $.toLength(iterated), i: 0});
}, function(){
var iter = this[ITER]
, i = iter.i++
, done = i >= iter.l;
return {done: done, value: done ? undefined : i};
});
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, invoke = __webpack_require__(10)
, methods = {};
methods.random = function(lim /* = 0 */){
var a = +this
, b = lim == undefined ? 0 : +lim
, m = Math.min(a, b);
return Math.random() * (Math.max(a, b) - m) + m;
};
if($.FW)$.each.call((
// ES3:
'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' +
// ES6:
'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc'
).split(','), function(key){
var fn = Math[key];
if(fn)methods[key] = function(/* ...args */){
// ie9- dont support strict mode & convert `this` to object -> convert it to number
var args = [+this]
, i = 0;
while(arguments.length > i)args.push(arguments[i++]);
return invoke(fn, args);
};
}
);
$def($def.P + $def.F, 'Number', methods);
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9)
, replacer = __webpack_require__(15);
var escapeHTMLDict = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}, unescapeHTMLDict = {}, key;
for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key;
$def($def.P + $def.F, 'String', {
escapeHTML: replacer(/[&<>"']/g, escapeHTMLDict),
unescapeHTML: replacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict)
});
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, core = $.core
, formatRegExp = /\b\w\w?\b/g
, flexioRegExp = /:(.*)\|(.*)$/
, locales = {}
, current = 'en'
, SECONDS = 'Seconds'
, MINUTES = 'Minutes'
, HOURS = 'Hours'
, DATE = 'Date'
, MONTH = 'Month'
, YEAR = 'FullYear';
function lz(num){
return num > 9 ? num : '0' + num;
}
function createFormat(prefix){
return function(template, locale /* = current */){
var that = this
, dict = locales[$.has(locales, locale) ? locale : current];
function get(unit){
return that[prefix + unit]();
}
return String(template).replace(formatRegExp, function(part){
switch(part){
case 's' : return get(SECONDS); // Seconds : 0-59
case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59
case 'm' : return get(MINUTES); // Minutes : 0-59
case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59
case 'h' : return get(HOURS); // Hours : 0-23
case 'hh' : return lz(get(HOURS)); // Hours : 00-23
case 'D' : return get(DATE); // Date : 1-31
case 'DD' : return lz(get(DATE)); // Date : 01-31
case 'W' : return dict[0][get('Day')]; // Day : Понедельник
case 'N' : return get(MONTH) + 1; // Month : 1-12
case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12
case 'M' : return dict[2][get(MONTH)]; // Month : Январь
case 'MM' : return dict[1][get(MONTH)]; // Month : Января
case 'Y' : return get(YEAR); // Year : 2014
case 'YY' : return lz(get(YEAR) % 100); // Year : 14
} return part;
});
};
}
function addLocale(lang, locale){
function split(index){
var result = [];
$.each.call(locale.months.split(','), function(it){
result.push(it.replace(flexioRegExp, '$' + index));
});
return result;
}
locales[lang] = [locale.weekdays.split(','), split(1), split(2)];
return core;
}
$def($def.P + $def.F, DATE, {
format: createFormat('get'),
formatUTC: createFormat('getUTC')
});
addLocale(current, {
weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday',
months: 'January,February,March,April,May,June,July,August,September,October,November,December'
});
addLocale('ru', {
weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота',
months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' +
'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь'
});
core.locale = function(locale){
return $.has(locales, locale) ? current = locale : current;
};
core.addLocale = addLocale;
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
var $def = __webpack_require__(9);
$def($def.G + $def.F, {global: __webpack_require__(2).g});
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, log = {}
, enabled = true;
// Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md
$.each.call(('assert,clear,count,debug,dir,dirxml,error,exception,' +
'group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,' +
'markTimeline,profile,profileEnd,table,time,timeEnd,timeline,' +
'timelineEnd,timeStamp,trace,warn').split(','), function(key){
log[key] = function(){
if(enabled && $.g.console && $.isFunction(console[key])){
return Function.apply.call(console[key], console, arguments);
}
};
});
$def($def.G + $def.F, {log: __webpack_require__(23)(log.log, log, {
enable: function(){
enabled = true;
},
disable: function(){
enabled = false;
}
})});
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
// JavaScript 1.6 / Strawman array statics shim
var $ = __webpack_require__(2)
, $def = __webpack_require__(9)
, $Array = $.core.Array || Array
, statics = {};
function setStatics(keys, length){
$.each.call(keys.split(','), function(key){
if(length == undefined && key in $Array)statics[key] = $Array[key];
else if(key in [])statics[key] = __webpack_require__(12)(Function.call, [][key], length);
});
}
setStatics('pop,reverse,shift,keys,values,entries', 1);
setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3);
setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' +
'reduce,reduceRight,copyWithin,fill,turn');
$def($def.S, 'Array', statics);
/***/ }
/******/ ]);
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = __e;
// RequireJS export
else if(typeof define == 'function' && define.amd)define(function(){return __e});
// Export to global object
else __g.core = __e;
}(); |
docs/0.5d174723c0c06b2232a2.js | lhf-nife/quark-ui | webpackJsonp([0],{"0P4F":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("Jmof"),l=(n.n(a),n("lkey")),s=n("UJDU"),i=n("Pp2j"),o=n("WB2H"),r=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e=()=>{s.a.config({placement:"bottomRight",bottom:50,duration:0,getContainer:"App"}),o.a.success("全局配置成功")},t=()=>{s.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})},n=e=>{s.a.open({placement:e,message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本使用"),React.createElement("p",null,"最简单的用法,4.5 秒后自动关闭"),React.createElement(l.a,{onClick:t},"open")," ",React.createElement("h3",null,"带有图标的通知提醒框"),React.createElement("p",null,"通知提醒框左侧有图标"),React.createElement(l.a,{onClick:()=>{s.a.open({type:"info",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"info")," ",React.createElement(l.a,{onClick:()=>{s.a.open({type:"success",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"success")," ",React.createElement(l.a,{onClick:()=>{s.a.open({type:"error",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"error")," ",React.createElement(l.a,{onClick:()=>{s.a.open({type:"warning",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"waring")," ",React.createElement(l.a,{onClick:()=>{s.a.open({type:"caution",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"caution")," ",React.createElement("h3",null,"自定义图标"),React.createElement("p",null,"可自定义图标"),React.createElement(l.a,{onClick:()=>{s.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案",duration:0,icon:React.createElement(i.a,{style:{top:"16px",left:"24px",position:"absolute"},name:"clock"})})}},"openIcon")," ",React.createElement("h3",null,"自动关闭的延时"),React.createElement("p",null,"取消4.5秒自动关闭"),React.createElement(l.a,{onClick:()=>{s.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案",duration:0})}},"open")," ",React.createElement("h3",null,"自定义按钮"),React.createElement("p",null,"可以置入功能按钮"),React.createElement(l.a,{onClick:()=>{var e=`open${Date.now()}`,t=()=>{s.a.close(e)},n=React.createElement("div",null,React.createElement(l.a,{type:"primary",size:"small",onClick:t},"立即更新")," ",React.createElement(l.a,{type:"secondary",size:"small",onClick:t},"今晚提醒"));s.a.open({type:"warning",message:"请更新系统",description:"如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。",key:e,btn:n})}},"openButton")," ",React.createElement(l.a,{onClick:()=>{var e=React.createElement("a",{href:"./notification"},"查看");s.a.open({type:"warning",message:"请更新系统",description:"如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。",btn:e})}},"openLink")," ",React.createElement("h3",null,"位置"),React.createElement("p",null,"从右上角、右下角、左下角、左上角弹出"),React.createElement(l.a,{onClick:()=>n("topRight")},"topRight")," ",React.createElement(l.a,{onClick:()=>n("topLeft")},"topLeft")," ",React.createElement(l.a,{onClick:()=>n("bottomLeft")},"bottomLeft")," ",React.createElement(l.a,{onClick:()=>n("bottomRight")},"bottomRight")," ",React.createElement("h3",null,"全局配置"),React.createElement("p",null,"在调用前提前配置,全局一次生效"),React.createElement("p",null,`notification.config({\n placement: 'bottomRight',\n bottom:50,\n duration:0,\n getContainer:'App'\n });`),React.createElement(l.a,{onClick:()=>e()},"config")," ",React.createElement(l.a,{onClick:t},"open")," ")}}},"0h7d":function(e,t){e.exports="import { Component } from 'react';\nimport Icon from '../../icon';\nimport Radio from '../../radio';\nimport Button from '../../button';\nimport Tabs from '../Tabs';\nimport Panel from '../Panel';\n\nTabs.Panel = Panel;\n\nclass TabsDemo1 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>标准线条式页签</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo2 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>禁用</h3>\n <p>对某项实行禁用</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 1</span>} key=\"1\">\n Tab 1\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 2</span>} key=\"2\">\n Tab 2\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 3</span>} key=\"3\" disabled >\n Tab 3\n </Panel>\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo3 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>迷你</h3>\n <p>用在狭小的区块或子级Tab</p>\n <Tabs\n size={'small'}\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo4 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>带图标</h3>\n <p>带图标的Tab</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 1</span>} key=\"1\">\n Tab 1\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 2</span>} key=\"2\">\n Tab 2\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 3</span>} key=\"3\" >\n Tab 3\n </Panel>\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo5 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>纵向</h3>\n <p>纵向的Tab</p>\n <Tabs\n activeKey={this.state.activeKey}\n tabPosition={'left'}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo6 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>卡片式</h3>\n <p>卡片式的页签,常用于容器顶部</p>\n <Tabs\n activeKey={this.state.activeKey}\n type={'card'}\n tabDeleteButton\n deleteButton={this.deleteButton}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo7 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <p>button可作为更次级的页签来使用</p>\n <Tabs\n activeKey={this.state.activeKey}\n type={'button'}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nexport default class TabsDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <TabsDemo1 />\n <br /><br />\n <TabsDemo2 />\n <br /><br />\n <TabsDemo3 />\n <br /><br />\n <TabsDemo4 />\n <br /><br />\n <TabsDemo5 />\n <br /><br />\n <TabsDemo6 />\n <br /><br />\n <TabsDemo7 />\n <br /><br />\n </div>\n );\n }\n}\n"},"13mF":function(e,t,n){"use strict";function a(e,t){if(t)for(var n=Object.keys(t),a=0,l=n.length;a<l;a++)e[n[a]]=t[n[a]];return e}function l(e){return a({},e)}function s(e){var t=l(p);if(e)for(var n=Object.keys(e),a=0,s=n.length;a<s;a++){var i=n[a];null==e[i]?delete t[i]:t[i]=e[i]}return t}function i(e,t,n,a){if(!(this instanceof i))return new i(e,t,n);this.placeholderChar=n||u,this.formatCharacters=t||p,this.source=e,this.pattern=[],this.length=0,this.firstEditableIndex=null,this.lastEditableIndex=null,this._editableIndices={},this.isRevealingMask=a||!1,this._parse()}function o(e){if(!(this instanceof o))return new o(e);if(null==(e=a({formatCharacters:null,pattern:null,isRevealingMask:!1,placeholderChar:u,selection:{start:0,end:0},value:""},e)).pattern)throw new Error("InputMask: you must provide a pattern.");if("string"!=typeof e.placeholderChar||e.placeholderChar.length>1)throw new Error("InputMask: placeholderChar should be a single character or an empty string.");this.placeholderChar=e.placeholderChar,this.formatCharacters=s(e.formatCharacters),this.setPattern(e.pattern,{value:e.value,selection:e.selection,isRevealingMask:e.isRevealingMask})}var r=/^\d$/,c=/^[A-Za-z]$/,m=/^[\dA-Za-z]$/,u="_",p={"*":{validate:function(e){return m.test(e)}},1:{validate:function(e){return r.test(e)}},a:{validate:function(e){return c.test(e)}},A:{validate:function(e){return c.test(e)},transform:function(e){return e.toUpperCase()}},"#":{validate:function(e){return m.test(e)},transform:function(e){return e.toUpperCase()}}};i.prototype._parse=function(){for(var e=this.source.split(""),t=0,n=[],a=0,l=e.length;a<l;a++){var s=e[a];if("\\"===s){if(a===l-1)throw new Error("InputMask: pattern ends with a raw \\");s=e[++a]}else s in this.formatCharacters&&(null===this.firstEditableIndex&&(this.firstEditableIndex=t),this.lastEditableIndex=t,this._editableIndices[t]=!0);n.push(s),t++}if(null===this.firstEditableIndex)throw new Error('InputMask: pattern "'+this.source+'" does not contain any editable characters.');this.pattern=n,this.length=n.length},i.prototype.formatValue=function(e){for(var t=new Array(this.length),n=0,a=0,l=this.length;a<l;a++)if(this.isEditableIndex(a)){if(this.isRevealingMask&&e.length<=n&&!this.isValidAtIndex(e[n],a))break;t[a]=e.length>n&&this.isValidAtIndex(e[n],a)?this.transform(e[n],a):this.placeholderChar,n++}else t[a]=this.pattern[a],e.length>n&&e[n]===this.pattern[a]&&n++;return t},i.prototype.isEditableIndex=function(e){return!!this._editableIndices[e]},i.prototype.isValidAtIndex=function(e,t){return this.formatCharacters[this.pattern[t]].validate(e)},i.prototype.transform=function(e,t){var n=this.formatCharacters[this.pattern[t]];return"function"==typeof n.transform?n.transform(e):e},o.prototype.input=function(e){if(this.selection.start===this.selection.end&&this.selection.start===this.pattern.length)return!1;var t=l(this.selection),n=this.getValue(),a=this.selection.start;if(a<this.pattern.firstEditableIndex&&(a=this.pattern.firstEditableIndex),this.pattern.isEditableIndex(a)){if(!this.pattern.isValidAtIndex(e,a))return!1;this.value[a]=this.pattern.transform(e,a)}for(var s=this.selection.end-1;s>a;)this.pattern.isEditableIndex(s)&&(this.value[s]=this.placeholderChar),s--;for(this.selection.start=this.selection.end=a+1;this.pattern.length>this.selection.start&&!this.pattern.isEditableIndex(this.selection.start);)this.selection.start++,this.selection.end++;return null!=this._historyIndex&&(this._history.splice(this._historyIndex,this._history.length-this._historyIndex),this._historyIndex=null),("input"!==this._lastOp||t.start!==t.end||null!==this._lastSelection&&t.start!==this._lastSelection.start)&&this._history.push({value:n,selection:t,lastOp:this._lastOp}),this._lastOp="input",this._lastSelection=l(this.selection),!0},o.prototype.backspace=function(){if(0===this.selection.start&&0===this.selection.end)return!1;var e=l(this.selection),t=this.getValue();if(this.selection.start===this.selection.end)this.pattern.isEditableIndex(this.selection.start-1)&&(this.value[this.selection.start-1]=this.placeholderChar),this.selection.start--,this.selection.end--;else{for(var n=this.selection.end-1;n>=this.selection.start;)this.pattern.isEditableIndex(n)&&(this.value[n]=this.placeholderChar),n--;this.selection.end=this.selection.start}return null!=this._historyIndex&&this._history.splice(this._historyIndex,this._history.length-this._historyIndex),("backspace"!==this._lastOp||e.start!==e.end||null!==this._lastSelection&&e.start!==this._lastSelection.start)&&this._history.push({value:t,selection:e,lastOp:this._lastOp}),this._lastOp="backspace",this._lastSelection=l(this.selection),!0},o.prototype.paste=function(e){var t={value:this.value.slice(),selection:l(this.selection),_lastOp:this._lastOp,_history:this._history.slice(),_historyIndex:this._historyIndex,_lastSelection:l(this._lastSelection)};if(this.selection.start<this.pattern.firstEditableIndex){for(var n=0,s=this.pattern.firstEditableIndex-this.selection.start;n<s;n++)if(e.charAt(n)!==this.pattern.pattern[n])return!1;e=e.substring(this.pattern.firstEditableIndex-this.selection.start),this.selection.start=this.pattern.firstEditableIndex}for(n=0,s=e.length;n<s&&this.selection.start<=this.pattern.lastEditableIndex;n++)if(!this.input(e.charAt(n))){if(this.selection.start>0){var i=this.selection.start-1;if(!this.pattern.isEditableIndex(i)&&e.charAt(n)===this.pattern.pattern[i])continue}return a(this,t),!1}return!0},o.prototype.undo=function(){if(0===this._history.length||0===this._historyIndex)return!1;var e;if(null==this._historyIndex){this._historyIndex=this._history.length-1,e=this._history[this._historyIndex];var t=this.getValue();e.value===t&&e.selection.start===this.selection.start&&e.selection.end===this.selection.end||this._history.push({value:t,selection:l(this.selection),lastOp:this._lastOp,startUndo:!0})}else e=this._history[--this._historyIndex];return this.value=e.value.split(""),this.selection=e.selection,this._lastOp=e.lastOp,!0},o.prototype.redo=function(){if(0===this._history.length||null==this._historyIndex)return!1;var e=this._history[++this._historyIndex];return this._historyIndex===this._history.length-1&&(this._historyIndex=null,e.startUndo&&this._history.pop()),this.value=e.value.split(""),this.selection=e.selection,this._lastOp=e.lastOp,!0},o.prototype.setPattern=function(e,t){t=a({selection:{start:0,end:0},value:""},t),this.pattern=new i(e,this.formatCharacters,this.placeholderChar,t.isRevealingMask),this.setValue(t.value),this.emptyValue=this.pattern.formatValue([]).join(""),this.selection=t.selection,this._resetHistory()},o.prototype.setSelection=function(e){if(this.selection=l(e),this.selection.start===this.selection.end){if(this.selection.start<this.pattern.firstEditableIndex)return this.selection.start=this.selection.end=this.pattern.firstEditableIndex,!0;for(var t=this.selection.start;t>=this.pattern.firstEditableIndex;){if(this.pattern.isEditableIndex(t-1)&&this.value[t-1]!==this.placeholderChar||t===this.pattern.firstEditableIndex){this.selection.start=this.selection.end=t;break}t--}return!0}return!1},o.prototype.setValue=function(e){null==e&&(e=""),this.value=this.pattern.formatValue(e.split(""))},o.prototype.getValue=function(){return this.value.join("")},o.prototype.getRawValue=function(){for(var e=[],t=0;t<this.value.length;t++)!0===this.pattern._editableIndices[t]&&e.push(this.value[t]);return e.join("")},o.prototype._resetHistory=function(){this._history=[],this._historyIndex=null,this._lastOp=null,this._lastSelection=l(this.selection)},o.Pattern=i,e.exports=o},"1nuA":function(e,t,n){"use strict";t.decode=t.parse=n("kMPS"),t.encode=t.stringify=n("xaZU")},"1ptM":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return m});var a=n("Jmof"),l=(n.n(a),n("rEdb")),s=n("lkey"),i=l.a.Group,o=["Apple","Pear","Orange"],r=["Apple","Orange"],c=e=>{console.log(e.target.checked,e.target.value)},m=class extends a.Component{constructor(e){super(e),this.handleToggleDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.handleToggleChecked=(()=>{this.setState({checked:!this.state.checked})}),this.handleChange=(e=>{this.setState({checkedList:e,checkAll:e.length===o.length})}),this.handleAllChange=(e=>{this.setState({checkedList:e.target.checked?o:[],checkAll:e.target.checked})}),this.state={disabled:!1,checked:!0,checkedList:r,checkAll:!1}}render(){var e=this.state,t=e.checked,n=e.disabled,a=e.checkedList,r=e.checkAll;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"全选"),React.createElement("p",null,React.createElement(l.a,{checked:r,disabled:n,onChange:this.handleAllChange}," 全选")),React.createElement(i,{options:o,value:a,disabled:n,onChange:this.handleChange}),React.createElement("h3",null,"一组checkbox"),React.createElement("div",null,React.createElement(i,{onChange:e=>{this.checkValue.innerHTML=e},disabled:n},React.createElement(l.a,{value:"A"}," A"),React.createElement(l.a,{value:"B"}," B"),React.createElement(l.a,{value:"C"}," C"),React.createElement(l.a,{value:"D"}," D"))),React.createElement("p",{ref:e=>{this.checkValue=e}}),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(l.a,{checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{name:"my-check",checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{name:"my-check",checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("h3",null,"非受控方式"),React.createElement("p",null,React.createElement(l.a,{defaultChecked:!0,disabled:n,onChange:c}," 非控的CheckBox组件")),React.createElement(s.a,{onClick:this.handleToggleDisabled},n?"启用":"禁用")," ",React.createElement(s.a,{onClick:this.handleToggleChecked},t?"取消选中":"选中"))}}},"2YTV":function(e,t){e.exports="import { Component } from 'react';\nimport Checkbox from '../Checkbox';\n// import {Checkbox} from 'antd'\nimport Button from '../../button';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst plainOptions = ['Apple', 'Pear', 'Orange'];\nconst defaultCheckedList = ['Apple', 'Orange'];\nconst onChange = (e) => {\n console.log(e.target.checked, e.target.value);\n};\nexport default class CheckboxDemo extends Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n disabled: false,\n checked: true,\n\n checkedList: defaultCheckedList,\n checkAll: false,\n };\n }\n\n handleToggleDisabled=() => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n handleToggleChecked=() => {\n this.setState({\n checked: !this.state.checked,\n });\n }\n\n handleChange=(checkedList) => {\n this.setState({\n checkedList,\n checkAll: checkedList.length === plainOptions.length,\n });\n }\n\n handleAllChange=(e) => {\n // const { checkedList, checkAll } = this.state;\n this.setState({\n checkedList: e.target.checked ? plainOptions : [],\n checkAll: e.target.checked,\n });\n }\n\n\n render() {\n const { checked, disabled, checkedList, checkAll } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>全选</h3>\n <p>\n <Checkbox\n checked={checkAll}\n disabled={disabled}\n onChange={this.handleAllChange}\n > 全选</Checkbox>\n </p>\n <CheckboxGroup\n options={plainOptions}\n value={checkedList}\n disabled={disabled}\n onChange={this.handleChange}\n />\n\n <h3>一组checkbox</h3>\n <div>\n <CheckboxGroup onChange={(v) => { this.checkValue.innerHTML = v; }} disabled={disabled}>\n <Checkbox value=\"A\"> A</Checkbox>\n <Checkbox value=\"B\"> B</Checkbox>\n <Checkbox value=\"C\"> C</Checkbox>\n <Checkbox value=\"D\"> D</Checkbox>\n </CheckboxGroup>\n </div>\n <p ref={(v) => { this.checkValue = v; }} />\n <h3>受控方式</h3>\n <p>\n <Checkbox\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n > 受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n > 受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n name=\"my-check\"\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n > 受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n name=\"my-check\"\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n > 受控的CheckBox组件</Checkbox>\n </p>\n <h3>非受控方式</h3>\n <p>\n <Checkbox\n defaultChecked\n disabled={disabled}\n onChange={onChange}\n > 非控的CheckBox组件</Checkbox>\n </p>\n <Button onClick={this.handleToggleDisabled}>{disabled ? '启用' : '禁用'}</Button> \n <Button onClick={this.handleToggleChecked}>{checked ? '取消选中' : '选中'}</Button>\n </div>\n );\n }\n}\n"},"3lqj":function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Menu\n\nMenu Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|inline|菜单类型,可选值:horizontal-h(水平菜单,子菜单水平),horizontal-v(水平菜单,子菜单垂直),vertical-h(垂直菜单,子菜单水平向右弹出),vertical-v(垂直菜单,子菜单内嵌在菜单区域)|\n|colorType|String|warm|颜色,可选值:warm(暖色),cold(冷色)|\n|selectedKeys|string[]|[]|选中的菜单项,数组,值为key|\n|defaultOpenKeys|string[]|[]|默认打开的菜单,数组,值为key|\n|onClick|function|null|点击 menuitem 调用此函数,参数为 {item, key, keyPath}|\n|onOpenChange|function|null|点击 menuitem 调用此函数,参数为 {item, key, keyPath}|\n\n### Api"},"5krA":function(e,t){e.exports="import { Component } from 'react';\nimport moment from 'moment';\nimport DatePicker from '../index';\nimport Checkbox from '../../checkbox';\n\nconst { MonthPicker, RangePicker } = DatePicker;\n\nexport default class DatePickerDemo extends Component {\n state = {\n disabled: false,\n date: moment().add(1, 'M'),\n }\n onChange(m) {\n console.log(m);\n }\n changeDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n render() {\n const { date, disabled } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>\n <Checkbox\n checked={disabled}\n onChange={this.changeDisabled}\n >\n 禁用\n </Checkbox>\n </h3>\n \n <h3>日期选择</h3>\n <table>\n <thead>\n <tr>\n <th>非受控方式</th>\n <th>受控方式</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <DatePicker\n disabled={disabled}\n onChange={this.onChange}\n />\n </td>\n <td style={{position: 'relative'}}>\n <DatePicker\n disabled={disabled}\n value={date}\n onChange={(d) => {\n this.setState({\n date: d,\n });\n }}\n />\n <p style={{position: 'absolute', right: '20px', top: '15px'}}>选择时间: {date.format()}</p>\n </td>\n </tr>\n </tbody>\n </table>\n \n <h3>不可选日期</h3>\n <p>可用 disabledDate 禁止选择部分日期</p>\n <DatePicker\n disabled={disabled}\n disabledDate={(current) => {\n return current && current.valueOf() < Date.now();\n }}\n ></DatePicker>\n <h3>月份选择</h3>\n <MonthPicker onChange={this.onChange} disabled={disabled} />\n <h3>预设范围</h3>\n <p>RangePicker 可以设置常用的 预设范围 提高用户体验。</p>\n <RangePicker onChange={this.onChange} disabled={disabled} />\n </div>\n );\n }\n}\n"},"5oN3":function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Dropdown\n\nDropdown Component.\n\n### Props\n\n#### Dropdown\n|name|type|default|description|\n|---|---|---|---|\n|trigger|`hover` or `click`|click|触发方式|\n|overlay|element|-|菜单内容|\n|placement|string|bottomLeft|定位|\n\n#### Dropdown.DropdownButton\n|name|type|default|description|\n|---|---|---|---|\n|type|string|`primary`|按钮类型|\n|trigger|`hover` or `click`|click|触发方式|\n|overlay|element|-|菜单内容|\n|placement|string|bottomRight|定位|\n\n#### Dropdown.Menu\n|name|type|default|description|\n|---|---|---|---|\n\n#### Dropdown.Menu.Item\n|name|type|default|description|\n|---|---|---|---|\n\n### Api"},"5xuW":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("kbwb")),s=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"按钮类型"),React.createElement("p",null,"按钮有四种类型:主按钮、次按钮、虚线按钮、危险按钮。主按钮在同一个操作区域最多出现一次。"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"主按钮"),React.createElement("th",null,"次按钮"),React.createElement("th",null,"虚线按钮"),React.createElement("th",null,"危险按钮"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{type:"primary"},"主按钮")),React.createElement("td",null,React.createElement(l.a,{type:"secondary"},"次按钮")),React.createElement("td",null,React.createElement(l.a,{type:"dashed"},"虚线按钮")),React.createElement("td",null,React.createElement(l.a,{type:"danger"},"危险按钮"))))),React.createElement("h3",null,"按钮尺寸"),React.createElement("p",null,"按钮有大、中、小三种尺寸。"),React.createElement("p",null,"通过设置 size 为 large small 分别把按钮设为大、小尺寸。若不设置 size,则尺寸为中。"),React.createElement(l.a,{size:"large"},"主要按钮(大)")," ",React.createElement(l.a,null,"主要按钮(中)")," ",React.createElement(l.a,{size:"small"},"主要按钮(小)"),React.createElement("h3",null,"不可用状态"),React.createElement("p",null,"添加 disabled 属性即可让按钮处于不可用状态,同时按钮样式也会改变。"),React.createElement(l.a,{size:"large",disabled:!0},"不可用按钮")," ",React.createElement(l.a,{disabled:!0},"不可用按钮")," ",React.createElement(l.a,{size:"small",disabled:!0},"不可用按钮"))}}},"6wLY":function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/olivianate/\n---\n\n## Input\n\n通过鼠标或键盘输入内容,是最基础的表单域的包装。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|'text'|button type, `text` or `textarea`|\n|value|String||输入框内容|\n|defaultValue|String||输入框默认内容|\n|prefix|string ReactNode||带有前缀图标的 input|\n|suffix|string ReactNode||带有后缀图标的 input|\n|size|String|'normal'|input size, `normal` `large` or `small` |\n|disabled|boolean|'false'|input disabled, `false` or `true` |\n\n##### Input.Search\n|name|type|default|description|\n|---|---|---|---|\n|onSearch|function(value)||点击搜索回调|\n\n\n### Api"},"7Lsv":function(e,t){e.exports="import { Component } from 'react';\nimport Icon from '../Icon';\nimport styles from './index.css';\nimport Icons from '../icons/';\n\nconst IconList = Object.keys(Icons);\n\nexport default class IconDemo extends Component {\n state = {\n color: document.documentElement.style.getPropertyValue('--brand-primary'),\n }\n componentDidMount() {\n if (typeof MutationObserver === 'function') {\n const observer = new MutationObserver((mutations) => {\n mutations.forEach(() => {\n this.setState({\n color: document.documentElement.style.getPropertyValue('--brand-primary'),\n });\n });\n });\n\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['style'],\n });\n }\n }\n render() {\n return (\n <div className={styles.Icon__wrap}>\n {\n IconList.map(name => (\n <div className={styles.Icon__grid} key={name}>\n <Icon size={36} name={name} color={this.state.color} />\n <span className={styles.Icon__name}>{name}</span>\n </div>\n ))\n }\n </div>\n );\n }\n}\n"},"8fnD":function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Pagination\n\n采用分页的形式分隔长列表,每次只加载一个页面。\n\n### 何时使用\n\n- 当加载/渲染所有数据将花费很多时间时;\n- 可切换页码浏览数据。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n| current | number | - | 当前页数 |\n| current | number | 1 | 默认当前页数 |\n| total | number | 0 | 总数 |\n| pageSize | number | - | 每页条数 |\n| defaultPageSize | number | 10 | 默认每页条数 |\n| onChange | function(page, pageSize) | noop | 页码改变回调,参数 |\n| showSizeChanger | boolean | false | 显示分页条数选择 |\n| onSizeChange | function(size, current) | noop | pageSize 变化回调 |\n| pageSizeOptions| number[] | [10, 20, 30, 40] | 指定每页可以显示多少条 |\n| showQuickJumper| boolean | false | 是否展示跳转输入框 |\n| size| string | '' | `small` 指定小尺寸分页 |\n| showTotal | boolean | false | 展示总数 |\n\n### Api"},"8ovY":function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../Button\';\n\nexport default class ButtonDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <h3>按钮类型</h3>\n <p>按钮有四种类型:主按钮、次按钮、虚线按钮、危险按钮。主按钮在同一个操作区域最多出现一次。</p>\n <table>\n <thead>\n <tr>\n <th>主按钮</th>\n <th>次按钮</th>\n <th>虚线按钮</th>\n <th>危险按钮</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td><Button type="primary">主按钮</Button></td>\n <td><Button type="secondary">次按钮</Button></td>\n <td><Button type="dashed">虚线按钮</Button></td>\n <td><Button type="danger">危险按钮</Button></td>\n </tr>\n </tbody>\n </table>\n <h3>按钮尺寸</h3>\n <p>按钮有大、中、小三种尺寸。</p>\n <p>通过设置 size 为 large small 分别把按钮设为大、小尺寸。若不设置 size,则尺寸为中。</p>\n <Button size="large">主要按钮(大)</Button>\n \n <Button>主要按钮(中)</Button>\n \n <Button size="small">主要按钮(小)</Button>\n <h3>不可用状态</h3>\n <p>添加 disabled 属性即可让按钮处于不可用状态,同时按钮样式也会改变。</p>\n <Button size="large" disabled>不可用按钮</Button>\n \n <Button disabled>不可用按钮</Button>\n \n <Button size="small" disabled>不可用按钮</Button>\n </div>\n );\n }\n}\n'},"8wBc":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("tObA")),s=n("o8IH"),i=n("lkey"),o=n("KIYf"),r=n.n(o),c=class extends a.Component{constructor(e){super(e),this.swichHandle1=(()=>{this.setState({isShow1:!this.state.isShow1})}),this.swichHandle2=(()=>{this.setState({isShow2:!this.state.isShow2})}),this.state={isShow1:!0,isShow2:!1}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本用法"),React.createElement(l.a,null),React.createElement("h3",null,"自定义大小"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"小"),React.createElement("th",null,"中"),React.createElement("th",null,"大"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{size:"small"})),React.createElement("td",null,React.createElement(l.a,{size:"default"})),React.createElement("td",null,React.createElement(l.a,{size:"large"}))))),React.createElement("h3",null,"自定义描述文案"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"小"),React.createElement("th",null,"中"),React.createElement("th",null,"大"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{size:"small",tip:"loading..."})),React.createElement("td",null,React.createElement(l.a,{size:"default",tip:"loading..."})),React.createElement("td",null,React.createElement(l.a,{size:"large",tip:"loading..."}))))),React.createElement("h3",null,"容器中使用"),React.createElement("div",{className:r.a.example1},React.createElement(l.a,null)),React.createElement("div",{className:r.a.example1},React.createElement(l.a,{tip:"loading..."})),React.createElement("h3",null,"提示中使用"),React.createElement("div",null,React.createElement(l.a,{spinning:this.state.isShow1},React.createElement(s.a,{type:"info",message:"警告提示内容",description:`警告提示的辅助性文字介绍警告提示的辅助\n 性文字介绍警告提示的辅助性文字介绍警告提示的辅助性文\n 字介绍警告提示的辅助性文字介绍警告提示的辅助性文字介\n 绍警告提示的辅助性文字介绍警告提示的辅助性文字介绍警\n 告提示的辅助性文字介绍警告提示的辅助性文字介绍`})),React.createElement("p",null,React.createElement(i.a,{type:"primary",onClick:this.swichHandle1},"显示/隐藏"))),React.createElement("h3",null,"延迟"),React.createElement("div",null,React.createElement(l.a,{spinning:this.state.isShow2,delay:600},React.createElement(s.a,{type:"info",message:"警告提示内容",description:`警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍`})),React.createElement("p",null,React.createElement(i.a,{type:"primary",onClick:this.swichHandle2},"显示/隐藏"))))}}},"9aTS":function(e,t){e.exports="import React, { Component } from 'react';\nimport Progress from '../Progress';\n\nexport default class ProgressDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>标准进度条</h3>\n <div>\n <Progress percent={30} />\n <Progress percent={70} status=\"exception\" />\n <Progress percent={70} status=\"pause\" />\n <Progress percent={100} status=\"success\" />\n <Progress percent={100} />\n <Progress percent={50} showInfo={false} />\n </div>\n <h3>小型进度条</h3>\n <p>适合放在较狭窄的区域内</p>\n <div style={{ width: 170 }}>\n <Progress percent={30} size={'mini'} />\n <Progress percent={70} size={'mini'} status=\"exception\" />\n <Progress percent={70} size={'mini'} status=\"pause\" />\n <Progress percent={100} size={'mini'} status=\"success\" />\n <Progress percent={100} size={'mini'} />\n </div>\n </div>\n );\n }\n}\n"},BtTj:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return i});var a=n("Jmof"),l=(n.n(a),n("lkey")),s=n("WB2H"),i=class extends a.Component{constructor(e){super(e),this.state={}}render(){return s.a.config({top:60,duration:10}),React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"全局提示"),React.createElement("p",null,"各种类型的全局提示,自动消失"),React.createElement(l.a,{onClick:()=>{s.a.info("这是一条提示信息(信息内容)。")}},"info")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{s.a.success("这是一条提示信息(信息内容)。")}},"success")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{s.a.error("这是一条提示信息(信息内容)。")}},"error")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{s.a.warning("这是一条提示信息(信息内容)。")}},"warning"))}}},CKXR:function(e,t){e.exports='import { Component } from \'react\';\nimport Input from \'../Input\';\nimport Icon from \'../../icon\';\nimport Search from \'../Search\';\nimport CardInput from \'../CardInput\';\n\nexport default class InputDemo extends Component {\n\n constructor(props) {\n super(props);\n this.state = { value: \'1234-1234-1234-1234\' };\n }\n\n onChangeCard = (e) => {\n const value = e.target.value;\n this.setState({ value });\n }\n\n render() {\n const prefix = (<Icon size={12} name={\'account\'} />);\n\n return (\n <div className="markdown-block">\n <h3>基本</h3>\n <p>输入框</p>\n <Input placeholder="请输入" defaultValue="12345465" />\n <h3>图标</h3>\n <p>图标输入框</p>\n <Input placeholder="请输入" prefix={prefix} />\n <h3>大小</h3>\n <p>三种大小的数字输入框</p>\n <Input size="large" placeholder="large size" />\n <p></p>\n <Input size="normal" placeholder="normal size" />\n <p></p>\n <Input size="small" placeholder="small size" />\n <h3>禁用</h3>\n <p>输入框禁用</p>\n <p>\n <Input placeholder="input disabled" defaultValue="12345465" disabled />\n </p>\n <h3>搜索框</h3>\n <p>带有搜索按钮的输入框</p>\n <Search size="large" placeholder="input search text" style={{ width: 240 }} />\n <p></p>\n <Search placeholder="input search text" style={{ width: 240 }} />\n <p></p>\n <Search size="small" placeholder="input search text" style={{ width: 240 }} />\n <h3>文本域</h3>\n <p>用于多行输入</p>\n <Input type="textarea" placeholder="请输入" autosize rows={1} />\n <Input type="textarea" placeholder="请输入" rows={6} />\n <h3>格式化</h3>\n <p>针对16或多位格式化输入</p>\n <CardInput\n size="large"\n mask="1111-1111-1111-1111"\n placeholder="1234-1234-1234-1234"\n value={this.state.value}\n onChange={this.onChangeCard}\n />\n <p></p>\n <CardInput\n size="normal"\n mask="111111-111111-111111-111111"\n onChange={this.onChangeCard}\n />\n </div>\n );\n }\n}\n'},CvA4:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,".IATVnLg{padding-top:30px}._1gVznGn{margin-top:8px;font-size:12px}",""]),t.locals={"upload-btn":"IATVnLg","upload-text":"_1gVznGn"}},DAzN:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("IggZ")),s=class extends a.Component{constructor(){var e;return e=super(...arguments),this.onChange=(e=>{console.log("changed",e)}),e}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"数字输入框"),React.createElement(l.a,{style:{width:200},min:1,max:10,defaultValue:3,onChange:this.onChange}),React.createElement("h3",null,"禁用"),React.createElement("p",null,"数字输入框禁用"),React.createElement(l.a,{min:1,max:10,disabled:!0,defaultValue:3}),React.createElement("h3",null,"小数"),React.createElement("p",null,"和原生的数字输入框一样,鼠标离开输入框时自动取值。目前设定小数位两位。"),React.createElement(l.a,{min:0,max:10,defaultValue:3,step:1,onChange:this.onChange}),React.createElement("h3",null,"大小"),React.createElement("p",null,"三种大小的数字输入框。"),React.createElement(l.a,{size:"large",min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{size:"small",min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("h3",null,"格式化展示"),React.createElement("p",null,"展示具有具体含义的数据"),React.createElement(l.a,{formatter:e=>`$ ${e.replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,parser:e=>e.replace(/\$\s?|(,*)/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1e3,formatter:e=>`¥ ${e.replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,parser:e=>e.replace(/\¥\s?|(,*)/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} m`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} ㎡`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} t`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} L`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} min`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:1e3,formatter:e=>`${e} m³`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}))}}},EfKb:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,".ZwxVSXL{margin-right:8px}._2aC88hA{float:right;margin-top:16px;transform:scale(.8);transition:transform .3s}.menu-inline .menu-submenu-open>.menu-submenu-title ._2aC88hA{transform:scale(.8) rotate(270deg);transition:transform .3s}",""]),t.locals={"menu--icon":"ZwxVSXL","menu--icon__pullright":"_2aC88hA"}},Eiul:function(e,t){e.exports='import { Component } from \'react\';\nimport Spin from \'../Spin\';\nimport Alert from \'../../alert\';\nimport Button from \'../../button\';\nimport style from \'./index.css\';\n\nexport default class SpinDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n isShow1: true,\n isShow2: false,\n };\n }\n\n swichHandle1 = () => {\n this.setState({\n isShow1: !this.state.isShow1\n })\n }\n\n swichHandle2 = () => {\n this.setState({\n isShow2: !this.state.isShow2\n })\n }\n\n render() {\n return (\n <div className="markdown-block">\n <h3>基本用法</h3>\n <Spin />\n <h3>自定义大小</h3>\n <table>\n <thead>\n <tr>\n <th>小</th>\n <th>中</th>\n <th>大</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <Spin size="small" />\n </td>\n <td>\n <Spin size="default" />\n </td>\n <td>\n <Spin size="large" />\n </td>\n </tr>\n </tbody>\n </table>\n <h3>自定义描述文案</h3>\n <table>\n <thead>\n <tr>\n <th>小</th>\n <th>中</th>\n <th>大</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <Spin size="small" tip="loading..." />\n </td>\n <td>\n <Spin size="default" tip="loading..." />\n </td>\n <td>\n <Spin size="large" tip="loading..." />\n </td>\n </tr>\n </tbody>\n </table>\n <h3>容器中使用</h3>\n <div className={style.example1}>\n <Spin />\n </div>\n <div className={style.example1}>\n <Spin tip="loading..." />\n </div>\n <h3>提示中使用</h3>\n <div>\n <Spin spinning={this.state.isShow1}>\n <Alert\n type="info"\n message="警告提示内容"\n description={`警告提示的辅助性文字介绍警告提示的辅助\n 性文字介绍警告提示的辅助性文字介绍警告提示的辅助性文\n 字介绍警告提示的辅助性文字介绍警告提示的辅助性文字介\n 绍警告提示的辅助性文字介绍警告提示的辅助性文字介绍警\n 告提示的辅助性文字介绍警告提示的辅助性文字介绍`}\n />\n </Spin>\n <p>\n <Button type="primary" onClick={this.swichHandle1}>显示/隐藏</Button>\n </p>\n </div>\n <h3>延迟</h3>\n <div>\n <Spin spinning={this.state.isShow2} delay={600}>\n <Alert\n type="info"\n message="警告提示内容"\n description={`警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍`}\n />\n </Spin>\n <p>\n <Button type="primary" onClick={this.swichHandle2}>显示/隐藏</Button>\n </p>\n </div>\n </div>\n );\n }\n}\n'},Ek3L:function(e,t){e.exports="import { Component } from 'react';\nimport Trigger from '../Trigger';\nimport Button from '../../button';\nimport Radio, { RadioGroup } from '../../radio';\n\nconst PLACEMENT_ENUM = {\n left: {\n points: ['cr', 'cl'],\n },\n right: {\n points: ['cl', 'cr'],\n },\n top: {\n points: ['bc', 'tc'],\n },\n bottom: {\n points: ['tc', 'bc'],\n },\n topLeft: {\n points: ['bl', 'tl'],\n },\n topRight: {\n points: ['br', 'tr'],\n },\n bottomRight: {\n points: ['tr', 'br'],\n },\n bottomLeft: {\n points: ['tl', 'bl'],\n },\n};\n\nconst ActionType = [\n 'hover',\n 'click',\n];\n\nexport default class TriggerDemo extends Component {\n state = {\n placement: 'bottom',\n action: 'click',\n visible: false,\n }\n onChangePlacement = (e) => {\n this.setState({\n placement: e.target.value,\n });\n }\n onChangeActionType = (e) => {\n this.setState({\n action: e.target.value,\n });\n }\n onClosePopup = () => {\n this.setState({\n visible: false,\n });\n }\n onPopupVisibleChange = (visible) => {\n console.log('onPopupVisibleChange', visible);\n this.setState({\n visible,\n });\n }\n renderPlacementSelector() {\n const { placement } = this.state;\n return (\n <select value={placement} onChange={this.onChangePlacement}>\n {\n Object.keys(PLACEMENT_ENUM).map(p => (\n <option key={p}>{p}</option>\n ))\n }\n </select>\n );\n }\n render() {\n const {\n placement,\n action,\n } = this.state;\n return (\n <div className=\"markdown-block\">\n <h5>普通用法</h5>\n <label htmlFor=\"placement\">对齐方式</label>\n {\n this.renderPlacementSelector()\n }\n <label htmlFor=\"action\">触发方式</label>\n <RadioGroup value={action} onChange={this.onChangeActionType}>\n {\n ActionType.map(type => (\n <Radio\n value={type}\n key={type}\n >{type}</Radio>\n ))\n }\n </RadioGroup>\n <Trigger\n action={action}\n popup={\n <div style={{ border: '1px solid #000', padding: 10, background: '#fff' }}>popup content</div>\n }\n placement={PLACEMENT_ENUM[placement].points}\n mouseLeaveDelay={100}\n >\n <Button>{`${action} me`}</Button>\n </Trigger>\n <h5>手动控制关闭</h5>\n <Trigger\n action={'click'}\n popupVisible={this.state.visible}\n popup={\n <div onClick={this.onClosePopup}>click me to close</div>\n }\n onPopupVisibleChange={this.onPopupVisibleChange}\n >\n <Button>click</Button>\n </Trigger>\n </div>\n );\n }\n}\n"},FaRr:function(e,t,n){var a=n("EfKb");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},FuzX:function(e,t,n){"use strict";var a=n("Jmof"),l=n.n(a),s=n("KSGD"),i=n.n(s),o=n("WKZb"),r=n.n(o),c=e=>{var t=e.className,n=e.children;return l.a.createElement("div",{className:r.a[t]},n)};c.defaultProps={className:""},c.propTypes={className:i.a.string},t.a=c},GuEn:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/olivianate/\n---\n\n## Notification\n\n全局展示通知提醒信息.\n\n### 何时使用\n\n在系统四个角显示通知提醒信息。经常用于以下情况:\n较为复杂的通知内容。\n带有交互的通知,给出用户下一步的行动点。\n系统主动推送。\n\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|message|string||通知提醒标题,必选|\n|description|string||通知提醒内容,必选|\n|duration|number|4.5|默认 4.5 秒后自动关闭,配置为 0 则不自动关闭|\n|icon|ReactNode||自定义图标|\n|btn|ReactNode||自定义关闭按钮|\n|placement|string|topRight|弹出位置,可选 topLeft topRight bottomLeft bottomRight|\n\n\n#### notification.config(options)\n|name|type|default|description|\n|---|---|---|---|\n|placement|string|topRight|弹出位置,可选 topLeft topRight bottomLeft bottomRight|\n|top|number|24|消息从顶部弹出时,距离顶部的位置,单位像素|\n|bottom|number|24|消息从底部弹出时,距离底部的位置,单位像素|\n|duration|number|4.5|默认自动关闭延时,单位秒|\n\n\n### Api"},Hn9c:function(e,t){e.exports="import { Component } from 'react';\nimport Modal from '../Modal';\nimport Button from '../../button';\n\nexport default class ModalDemo extends Component {\n constructor(props) {\n super(props);\n this.openModal = this.openModal.bind(this);\n this.state = {\n visible: false,\n };\n }\n openModal() {\n this.setState({\n visible: true,\n });\n }\n closeModal() {\n this.setState({\n visible: false,\n });\n }\n render() {\n const { visible } = this.state;\n const modalProps = {\n title: '标题',\n visible,\n onOk: () => {\n this.closeModal();\n console.log('onOK');\n },\n onCancel: () => {\n this.closeModal();\n console.log('onCancel');\n },\n afterClose() {\n console.log('afterClose');\n },\n };\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <Button type=\"secondary\" onClick={this.openModal}>open modal</Button>\n <Modal {...modalProps}>\n <p>这是一段信息。</p>\n </Modal>\n <h3>信息提示</h3>\n <p>各种类型的信息提示,只提供一个按钮用于关闭。</p>\n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.info({\n content: '这是提示信息',\n closable: true,\n });\n }}\n >info</Button> \n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.success({\n content: '这是成功消息',\n });\n }}\n >success</Button> \n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.error({\n content: '这是错误提示',\n });\n }}\n >error</Button> \n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.warning({\n content: '这是警告信息',\n });\n }}\n >warning</Button>\n </div>\n );\n }\n}\n"},I045:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Icon\n\n图标。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|name|string|''|图标名称|\n|size|number|32|尺寸|\n|color|string|-|颜色|\n"},J2TD:function(e,t){e.exports='import Button from \'quark-ui/button\';\nimport Dropdown from \'../Dropdown\';\n\nconst { Menu } = Dropdown;\nconst { Item } = Menu;\n\nconst DropdownDemo = () => {\n const menu = (\n <Menu>\n <Item>\n <a href="https://www.ehuodi.com">易货嘀</a>\n </Item>\n <Item>\n <a href="http://www.lujing56.cn/">陆鲸</a>\n </Item>\n <Item>\n <a href="https://ecargo.ehuodi.com/">加盟车队管理系统</a>\n </Item>\n </Menu>\n );\n return (\n <div className="markdown-block">\n <h3>带下拉框的按钮</h3>\n <Dropdown overlay={menu}>\n <Button>菜单</Button>\n </Dropdown>\n <h3>Dropdown内置按钮</h3>\n <Dropdown.Button type="secondary" overlay={menu} trigger={\'click\'}>\n 菜单\n </Dropdown.Button>\n </div>\n );\n};\n\nexport default DropdownDemo;\n'},KIYf:function(e,t,n){var a=n("fIw2");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},KOED:function(e,t){e.exports='import { Component } from \'react\';\nimport Breadcrumb from \'../index\';\n\nexport default class BreadcrumbDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <h3>基本面包屑</h3>\n <p><Breadcrumb>\n <Breadcrumb.Item>home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb></p>\n\n <Breadcrumb separator=">">\n <Breadcrumb.Item>home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb>\n\n <h3>带返回的面包屑</h3>\n <p><Breadcrumb hasBackIcon >\n <Breadcrumb.Item href="/">home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb></p>\n\n <Breadcrumb hasBackIcon separator=">">\n <Breadcrumb.Item href="/">home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb>\n </div>\n );\n }\n}\n'},KOOh:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Button\n\n按钮用于开始一个即时操作。\n\n### 何时使用\n\n标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|'primary'|button type, `primary` `secondary` `dashed` or `danger`|\n|size|String|'normal'|button size, `normal` `large` or `small` |\n\n### Api"},"M1/m":function(e,t){e.exports="import { Component } from 'react';\nimport InputNumber from '../InputNumber';\n\nexport default class InputNumberDemo extends Component {\n onChange = (value) => {\n console.log('changed', value);\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>数字输入框</p>\n <InputNumber style={{ width: 200 }} min={1} max={10} defaultValue={3} onChange={this.onChange} />\n <h3>禁用</h3>\n <p>数字输入框禁用</p>\n <InputNumber min={1} max={10} disabled defaultValue={3} />\n <h3>小数</h3>\n <p>和原生的数字输入框一样,鼠标离开输入框时自动取值。目前设定小数位两位。</p>\n <InputNumber min={0} max={10} defaultValue={3} step={1.00} onChange={this.onChange} />\n <h3>大小</h3>\n <p>三种大小的数字输入框。</p>\n <InputNumber size=\"large\" min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <br /><br />\n <InputNumber min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <br /><br />\n <InputNumber size=\"small\" min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <h3>格式化展示</h3>\n <p>展示具有具体含义的数据</p>\n <InputNumber\n formatter={value => `$ ${value.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')}`}\n parser={value => value.replace(/\\$\\s?|(,*)/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1000}\n formatter={value => `¥ ${value.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')}`}\n parser={value => value.replace(/\\¥\\s?|(,*)/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} m`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} ㎡`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} t`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} L`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} min`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={1000}\n formatter={value => `${value} m³`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n </div>\n );\n }\n}\n"},Mdu8:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("b7MC"),l=n("Jmof"),s=(n.n(l),class extends l.Component{constructor(){var e;return e=super(...arguments),this.state={current:3},e}render(){var e=this.state.current;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"基础分页。"),React.createElement(a.a,{current:e,total:50}),React.createElement("h3",null,"更多分页"),React.createElement(a.a,{defaultCurrent:1,total:500,showSizeChanger:!0,onSizeChange:(e,t)=>{console.log(`size: ${e} current: ${t}`)}}),React.createElement("h3",null,"跳转"),React.createElement("p",null,"快速跳转到某一页。"),React.createElement(a.a,{showTotal:!0,total:100,showQuickJumper:!0}),React.createElement("h3",null,"迷你"),React.createElement("p",null,"用于弹窗等页面展示区域狭小的场景。"),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(a.a,{current:e,total:50,onChange:e=>{this.setState({current:e})}})),React.createElement(a.a,{total:100,showQuickJumper:!0,showSizeChanger:!0,size:"small"}),React.createElement("h3",null,"非受控方式"),React.createElement(a.a,{defaultCurrent:1,total:50}))}})},PKY1:function(e,t,n){var a,l,s;!function(n,i){l=[t,e],void 0!==(s="function"==typeof(a=i)?a.apply(t,l):a)&&(e.exports=s)}(0,function(e,t){"use strict";function n(){return"jsonp_"+Date.now()+"_"+Math.ceil(1e5*Math.random())}function a(e){try{delete window[e]}catch(t){window[e]=void 0}}function l(e){var t=document.getElementById(e);t&&document.getElementsByTagName("head")[0].removeChild(t)}var s={timeout:5e3,jsonpCallback:"callback",jsonpCallbackFunction:null};t.exports=function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=e,o=t.timeout||s.timeout,r=t.jsonpCallback||s.jsonpCallback,c=void 0;return new Promise(function(s,m){var u=t.jsonpCallbackFunction||n(),p=r+"_"+u;window[u]=function(e){s({ok:!0,json:function(){return Promise.resolve(e)}}),c&&clearTimeout(c),l(p),a(u)},i+=-1===i.indexOf("?")?"?":"&";var h=document.createElement("script");h.setAttribute("src",""+i+r+"="+u),t.charset&&h.setAttribute("charset",t.charset),h.id=p,document.getElementsByTagName("head")[0].appendChild(h),c=setTimeout(function(){m(new Error("JSONP request to "+e+" timed out")),a(u),l(p),window[u]=function(){a(u)}},o),h.onerror=function(){m(new Error("JSONP request to "+e+" failed")),a(u),l(p),c&&clearTimeout(c)}})}})},PXi9:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/ryan.bian/\n email: [email protected]\n---\n\n## Animation\n\nAnimation Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|duration|number|500|持续时间|\n|motion|string|`fade`|效果|\n|timingFunction|string|`linear`|时间函数|\n|in|boolean|false|状态|\n|`...otherProps`|-|-|refer to https://reactcommunity.org/react-transition-group/#Transition|\n\n### Api"},PgBk:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return y});var a=n("Jmof"),l=n.n(a),s=n("xLxO"),i=n("hFTO"),o=n("kbwb"),r=n("WB2H"),c=n("kimJ"),m=n.n(c),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},p=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={name:"file",action:"https://jsonplaceholder.typicode.com/posts/",headers:{authorization:"authorization-text"},multiple:!0,disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(e){e.file.status,"done"===e.file.status?r.a.success(`${e.file.name} 文件上传成功.`):"error"===e.file.status&&r.a.error(`${e.file.name} 文件上传失败!`)}};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"1、经典款式,用户点击按钮弹出文件选择框。"),l.a.createElement(s.a,e,l.a.createElement(o.a,{size:"small",type:"secondary",disabled:e.disabled},l.a.createElement(i.a,{size:12,name:"upload"})," 上传文件")))}},h=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={name:"file",action:"https://jsonplaceholder.typicode.com/posts/",headers:{authorization:"authorization-text"},multiple:!0,disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(e){e.file.status,"done"===e.file.status?r.a.success(`${e.file.name} 文件上传成功.`):"error"===e.file.status&&r.a.error(`${e.file.name} 文件上传失败!`)},defaultFileList:[{uid:1,name:"图片1.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"},{uid:2,name:"图片2.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"},{uid:3,name:"图片3.png",status:"error",response:"上传失败,图片太大"}]};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"2、已上传文件的列表"),l.a.createElement("p",null,"使用 defaultFileList 设置已上传的内容。"),l.a.createElement(s.a,e,l.a.createElement(o.a,{size:"small",type:"secondary",disabled:e.disabled},l.a.createElement(i.a,{size:12,name:"upload"})," 上传文件")))}},d=class extends a.Component{constructor(e){super(e),this.state={fileList:[{uid:-1,name:"xxx.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"}]}}render(){var e=this,t={action:"//jsonplaceholder.typicode.com/posts/",disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(t){var n=t.fileList;n=(n=n.slice(-1)).map(e=>(e.response&&(e.url=e.response.url),e)),e.setState({fileList:n})}};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"3、使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:"),l.a.createElement("p",null,"1) 上传列表数量的限制。"),l.a.createElement("p",null,"2) 读取远程路径并显示链接。"),l.a.createElement("p",null,"3) 按照服务器返回信息筛选成功上传的文件。"),l.a.createElement(s.a,u({},t,{fileList:this.state.fileList}),l.a.createElement(o.a,{size:"small",type:"secondary",disabled:t.disabled},l.a.createElement(i.a,{size:12,name:"upload"})," 上传文件")))}},g=class extends a.Component{constructor(e){super(e),this.handlePreview=(e=>{window.open(e.url)}),this.handleChange=(e=>{this.setState({fileList:e.fileList})}),this.state={fileList:[{uid:-1,name:"xxx.png",status:"done",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}]}}beforeUpload(e){var t="image/png"===e.type;t||r.a.error("请上传.png文件!");var n=e.size<1024e3;return n||r.a.error("图片不能超过1000KB!"),t&&n}render(){var e={action:"//jsonplaceholder.typicode.com/posts/",disabled:!1,listType:"picture-card",fileList:this.state.fileList,onPreview:this.handlePreview,onChange:this.handleChange,beforeUpload:this.beforeUpload,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg}},t=l.a.createElement("div",{className:m.a["upload-btn"]},l.a.createElement(i.a,{name:"plus",size:25}),l.a.createElement("div",{className:m.a["upload-text"]},"上传"));return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"4、显示上传缩略图"),l.a.createElement("p",null,"点击上传图片,并使用 beforeUpload 限制用户上传的图片格式和大小。"),l.a.createElement(s.a,e,this.state.fileList.length>=3?null:t))}},y=class extends a.Component{render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement(p,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(h,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(d,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(g,null))}}},RPTQ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return m});var a=n("Jmof"),l=(n.n(a),n("PJh5")),s=n.n(l),i=n("k44X"),o=n("qoUc"),r=i.a.MonthPicker,c=i.a.RangePicker,m=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={disabled:!1,date:s()().add(1,"M")},this.changeDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),e}onChange(e){console.log(e)}render(){var e=this.state,t=e.date,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,React.createElement(o.a,{checked:n,onChange:this.changeDisabled},"禁用")),React.createElement("h3",null,"日期选择"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"非受控方式"),React.createElement("th",null,"受控方式"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(i.a,{disabled:n,onChange:this.onChange})),React.createElement("td",{style:{position:"relative"}},React.createElement(i.a,{disabled:n,value:t,onChange:e=>{this.setState({date:e})}}),React.createElement("p",{style:{position:"absolute",right:"20px",top:"15px"}},"选择时间: ",t.format()))))),React.createElement("h3",null,"不可选日期"),React.createElement("p",null,"可用 disabledDate 禁止选择部分日期"),React.createElement(i.a,{disabled:n,disabledDate:e=>e&&e.valueOf()<Date.now()}),React.createElement("h3",null,"月份选择"),React.createElement(r,{onChange:this.onChange,disabled:n}),React.createElement("h3",null,"预设范围"),React.createElement("p",null,"RangePicker 可以设置常用的 预设范围 提高用户体验。"),React.createElement(c,{onChange:this.onChange,disabled:n}))}}},Rloj:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return y});var a=n("Jmof"),l=(n.n(a),n("kbwb")),s=n("HDB8"),i=n("QES8"),o=n("6Fy1"),r=n("1nuA"),c=n.n(r),m=n("PKY1"),u=n.n(m),p=class extends a.Component{constructor(){super(),this.onChange=(e=>{var t=e.text,n=e.value;this.setState({value:n,text:t})}),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setSelect=(()=>{this.setState({value:"B"})}),this.state={disabled:!1,value:null,text:null}}render(){var e=this.state,t=e.value,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},n?"启用":"禁用")," ",React.createElement(l.a,{onClick:this.setSelect},"选中BB"),React.createElement("h3",null,"受控"),React.createElement("p",null),React.createElement(s.a,{style:{width:250},disabled:n,defaultValue:"C",value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(o.a,{value:"A"},"AA"),React.createElement(o.a,{value:"B"},"BB"),React.createElement(o.a,{value:"C"},"CC"),React.createElement(o.a,{value:"D"},"DD"),React.createElement(o.a,{value:"E"},"EE"),React.createElement(o.a,{value:"F"},"FF"),React.createElement(o.a,{value:"G"},"GG")),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`),React.createElement("h3",null,"非受控"),React.createElement("p",null),React.createElement(s.a,{style:{width:250},disabled:n,defaultValue:"C",onChange:this.onChange,placeholder:"请选择"},React.createElement(o.a,{value:"A"},"AA"),React.createElement(o.a,{value:"B"},"BB"),React.createElement(o.a,{value:"C"},"CC"),React.createElement(o.a,{value:"D"},"DD"),React.createElement(o.a,{value:"E"},"EE"),React.createElement(o.a,{value:"F"},"FF"),React.createElement(o.a,{value:"G"},"GG")),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},h=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setSelect=(()=>{this.setState({value:"B"})}),this.onChange=(e=>{var t=e.text,n=e.value;this.setState({value:n,text:t})}),this.state={disabled:!1,value:null,text:null}}render(){var e=this.state,t=e.value,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"分组"),React.createElement("p",null),React.createElement(s.a,{style:{width:250},disabled:n,value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(i.a,{label:"分组1"},React.createElement(o.a,{value:"A"},"AA"),React.createElement(o.a,{value:"B"},"BB")),React.createElement(i.a,{label:"分组2"},React.createElement(o.a,{value:"C"},"CC"),React.createElement(o.a,{value:"D"},"DD")),React.createElement(i.a,{label:"分组3"},React.createElement(o.a,{value:"E"},"EE"),React.createElement(o.a,{value:"F"},"FF"),React.createElement(o.a,{value:"G"},"GG"))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`),React.createElement("h3",null,"复杂选项。"),React.createElement("p",null),React.createElement(s.a,{style:{width:250},disabled:n,value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(o.a,{value:"A",text:"李大力"},React.createElement("div",null,"李大力"),React.createElement("div",null,"1354534324"),React.createElement("div",null,"杭州萧山区民和路")),React.createElement(o.a,{value:"B",text:"李启"},React.createElement("div",null,"李启"),React.createElement("div",null,"1356664324"),React.createElement("div",null,"杭州江干区")),React.createElement(o.a,{value:"C",text:"李宇"},React.createElement("div",null,"李宇"),React.createElement("div",null,"1377534324"),React.createElement("div",null,"杭州富阳")),React.createElement(o.a,{value:"D",text:"李琦"},React.createElement("div",null,"李琦"),React.createElement("div",null,"1354554324"),React.createElement("div",null,"杭州滨江区江")),React.createElement(o.a,{value:"E",text:"李小燕"},React.createElement("div",null,"李小燕"),React.createElement("div",null,"1387564324"),React.createElement("div",null,"上海黄埔区"))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},d=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setDefaultValue=(()=>{this.setState({value:"CPU",text:"CPU"})}),this.onSearch=(e=>{var t=c.a.encode({code:"utf-8",q:e});u()(`https://suggest.taobao.com/sug?${t}`).then(e=>e.json()).then(e=>{var t=[];e.result.forEach(e=>{t.push({value:e[0],text:e[0]})}),this.setState({searchData:t})})}),this.onChange=(e=>{var t=e.value,n=e.text;this.setState({value:t,text:n})}),this.state={disabled:!1,value:null,text:null,searchData:[]}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},this.state.disabled?"启用":"禁用")," ",React.createElement(l.a,{onClick:this.setDefaultValue},"设值"),React.createElement("h3",null,"带搜索框。"),React.createElement("p",null),React.createElement(s.a,{style:{width:250},disabled:this.state.disabled,value:this.state.value,text:this.state.text,type:"combobox",onSearch:this.onSearch,onCancelChange:this.onCancelChange,onChange:this.onChange,placeholder:"请输入查询条件"},this.state.searchData.map(e=>React.createElement(o.a,{key:e.value,value:e.value},e.text))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},g=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.onChangeProvince=(e=>{var t=e.value,n=e.text;this.setState({province:t,provinceText:n,city:null,cityText:null})}),this.onChangeCity=(e=>{var t=e.value,n=e.text;this.setState({city:t,cityText:n})}),this.getCitysByProvince=(e=>{switch(e){case"1":return[{value:"11",text:"杭州"},{value:"12",text:"湖州"},{value:"13",text:"绍兴"}];case"2":return[{value:"21",text:"广州"},{value:"22",text:"东莞"},{value:"23",text:"中山"}];case"3":return[{value:"31",text:"福州"},{value:"32",text:"泉州"},{value:"33",text:"厦门"}];default:return[]}}),this.state={value:null,text:null,disabled:!1,province:null,city:null}}render(){var e=this.getCitysByProvince(this.state.province).map((e,t)=>React.createElement(o.a,{value:e.value,key:t},e.text));return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},this.state.disabled?"启用":"禁用"),React.createElement("h3",null,"联动。"),React.createElement("p",null),"省:",React.createElement(s.a,{style:{width:250},disabled:this.state.disabled,value:this.state.province,onChange:this.onChangeProvince},React.createElement(o.a,{value:"1"},"浙江省"),React.createElement(o.a,{value:"2"},"广东省"),React.createElement(o.a,{value:"3"},"福建省")),"市:",React.createElement(s.a,{style:{width:250},disabled:this.state.disabled,value:this.state.city,onChange:this.onChangeCity},e),React.createElement("span",null,"选中值:",`${this.state.province}-${this.state.provinceText},${this.state.city}-${this.state.cityText}`))}},y=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement(p,null),React.createElement("br",null),React.createElement("br",null),React.createElement(h,null),React.createElement("br",null),React.createElement("br",null),React.createElement(d,null),React.createElement("br",null),React.createElement("br",null),React.createElement(g,null))}}},RtOM:function(e,t){e.exports="import { Component } from 'react';\nimport Button from '../../button';\nimport message from '../index';\n\nexport default class MessageDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n message.config({\n top: 60,\n duration: 10,\n });\n return (\n <div className=\"markdown-block\">\n <h3>全局提示</h3>\n <p>各种类型的全局提示,自动消失</p>\n <Button onClick={() => { message.info('这是一条提示信息(信息内容)。'); }}>info</Button> \n <Button type=\"secondary\" onClick={() => { message.success('这是一条提示信息(信息内容)。'); }}>success</Button> \n <Button type=\"secondary\" onClick={() => { message.error('这是一条提示信息(信息内容)。'); }}>error</Button> \n <Button type=\"secondary\" onClick={() => { message.warning('这是一条提示信息(信息内容)。'); }}>warning</Button>\n </div>\n );\n }\n}\n"},SH3Z:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## DatePicker\n\n输入或选择日期的控件。\n\n### 何时使用\n\n当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。\n\n### Props\n\n#### DatePicker\n\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)|无|日期|\n|defaultValue|[moment](http://momentjs.com/)|无|默认日期|\n|disabledDate|func|无|不可选择的日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|220|输入框宽度|\n|format|string|YYYY-MM-DD|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n#### MonthPicker\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)|无|日期|\n|defaultValue|[moment](http://momentjs.com/)|无|默认日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|220|输入框宽度|\n|format|string|YYYY-MM|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n#### RangePicker\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)[]|无|日期|\n|defaultValue|[moment](http://momentjs.com/)[]|无|默认日期|\n|disabledDate|func|无|不可选择的日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|null|输入框宽度|\n|format|string|YYYY-MM-DD|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n\n### Api"},Sf3G:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n("lkey"),l=n("JJqH"),s=l.a.Menu,i=s.Item;t.default=(()=>{var e=React.createElement(s,null,React.createElement(i,null,React.createElement("a",{href:"https://www.ehuodi.com"},"易货嘀")),React.createElement(i,null,React.createElement("a",{href:"http://www.lujing56.cn/"},"陆鲸")),React.createElement(i,null,React.createElement("a",{href:"https://ecargo.ehuodi.com/"},"加盟车队管理系统")));return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"带下拉框的按钮"),React.createElement(l.a,{overlay:e},React.createElement(a.a,null,"菜单")),React.createElement("h3",null,"Dropdown内置按钮"),React.createElement(l.a.Button,{type:"secondary",overlay:e,trigger:"click"},"菜单"))})},SfWF:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return o});var a=n("Jmof"),l=(n.n(a),n("lkey")),s=n("eo4W"),i=s.a.Step,o=class extends a.Component{constructor(e){super(e),this.state={current:0},this.handleNext=this.handleNext.bind(this),this.handlePrev=this.handlePrev.bind(this)}handleNext(){this.setState(e=>e.current<3?{current:e.current+1}:{current:3})}handlePrev(){this.setState(e=>e.current>0?{current:e.current-1}:{current:0})}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,React.createElement(l.a,{disabled:this.state.current<=0,onClick:this.handlePrev},"上一步")," ",React.createElement(l.a,{disabled:this.state.current>=3,onClick:this.handleNext},"下一步")),React.createElement("h3",null,"横向步骤条"),React.createElement(s.a,{current:this.state.current,style:{marginBottom:10}},React.createElement(i,{title:"步骤1"}),React.createElement(i,{title:"步骤2"}),React.createElement(i,{title:"步骤3"}),React.createElement(i,{title:"步骤4"})),React.createElement(s.a,{current:this.state.current,isFinishIcon:!0,style:{marginBottom:10}},React.createElement(i,{title:"已完成"}),React.createElement(i,{title:"进行中"}),React.createElement(i,{title:"未进行"}),React.createElement(i,{title:"未进行"})),React.createElement(s.a,{current:this.state.current,style:{marginBottom:10}},React.createElement(i,{title:"步骤1",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤2",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤3",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤4",description:"这是一段很长很长很长的描述性文字"})),React.createElement("h3",null,"竖向步骤条"),React.createElement("div",{style:{width:400,display:"inline-block"}},React.createElement(s.a,{current:this.state.current,direction:"vertical"},React.createElement(i,{title:"步骤1",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤2",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤3",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"步骤4"}))),React.createElement("div",{style:{display:"inline-block"}},React.createElement(s.a,{current:this.state.current,size:"small",direction:"vertical",isFinishIcon:!0},React.createElement(i,{title:"已完成",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"进行中",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"未进行",description:"这是一段很长很长很长的描述性文字"}),React.createElement(i,{title:"未进行",description:"这是一段很长很长很长的描述性文字"}))))}}},TJ8L:function(e,t){e.exports="import { Component } from 'react';\nimport Button from '../../button';\nimport notification from '../index';\nimport Icon from '../../icon';\nimport message from '../../message';\n\n\nexport default class PopoverDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n const config = () => {\n notification.config({\n placement: 'bottomRight',\n bottom: 50,\n duration: 0,\n getContainer: 'App',\n });\n message.success('全局配置成功');\n };\n\n const openNotification = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openInfo = () => {\n notification.open({\n type: 'info',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openSuccess = () => {\n notification.open({\n type: 'success',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openError = () => {\n notification.open({\n type: 'error',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openWaring = () => {\n notification.open({\n type: 'warning',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openCaution = () => {\n notification.open({\n type: 'caution',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openNoDuration = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n duration: 0,\n });\n };\n\n const openIcon = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n duration: 0,\n icon: <Icon\n style={{\n top: '16px',\n left: '24px',\n position: 'absolute',\n }}\n name={'clock'}\n />,\n });\n };\n\n const openButton = () => {\n const key = `open${Date.now()}`;\n const btnClick = () => {\n notification.close(key);\n };\n const btn = (\n <div>\n <Button type=\"primary\" size=\"small\" onClick={btnClick}>\n 立即更新\n </Button>\n  \n <Button type=\"secondary\" size=\"small\" onClick={btnClick}>\n 今晚提醒\n </Button>\n </div>\n );\n\n notification.open({\n type: 'warning',\n message: '请更新系统',\n description: '如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。',\n key,\n btn,\n });\n };\n\n\n const openButtonLink = () => {\n const btnlink = (\n <a href=\"./notification\">查看</a>\n );\n notification.open({\n type: 'warning',\n message: '请更新系统',\n description: '如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。',\n btn: btnlink,\n });\n };\n\n const openPlacement = (placement) => {\n notification.open({\n placement,\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>基本使用</h3>\n <p>最简单的用法,4.5 秒后自动关闭</p>\n <Button onClick={openNotification}>open</Button> \n <h3>带有图标的通知提醒框</h3>\n <p>通知提醒框左侧有图标</p>\n <Button onClick={openInfo}>info</Button> \n <Button onClick={openSuccess}>success</Button> \n <Button onClick={openError}>error</Button> \n <Button onClick={openWaring}>waring</Button> \n <Button onClick={openCaution}>caution</Button> \n <h3>自定义图标</h3>\n <p>可自定义图标</p>\n <Button onClick={openIcon}>openIcon</Button> \n <h3>自动关闭的延时</h3>\n <p>取消4.5秒自动关闭</p>\n <Button onClick={openNoDuration}>open</Button> \n <h3>自定义按钮</h3>\n <p>可以置入功能按钮</p>\n <Button onClick={openButton}>openButton</Button> \n <Button onClick={openButtonLink}>openLink</Button> \n <h3>位置</h3>\n <p>从右上角、右下角、左下角、左上角弹出</p>\n <Button onClick={() => openPlacement('topRight')}>topRight</Button> \n <Button onClick={() => openPlacement('topLeft')}>topLeft</Button> \n <Button onClick={() => openPlacement('bottomLeft')}>bottomLeft</Button> \n <Button onClick={() => openPlacement('bottomRight')}>bottomRight</Button> \n <h3>全局配置</h3>\n <p>在调用前提前配置,全局一次生效</p>\n <p>\n {`notification.config({\n placement: 'bottomRight',\n bottom:50,\n duration:0,\n getContainer:'App'\n });`}\n </p>\n <Button onClick={() => config()}>config</Button> \n <Button onClick={openNotification}>open</Button> \n </div>\n );\n }\n}\n"},"TL+L":function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._10nfZ5r{display:flex;flex-wrap:wrap}.GsIgpmR{display:inline-flex;margin:1px;width:80px;height:80px;border:1px solid var(--border-color);flex-direction:column;justify-content:space-around;text-align:center}.GsIgpmR>svg{margin:0 auto}._25I3NhY{display:block;font-size:12px;line-height:1}",""]),t.locals={Icon__wrap:"_10nfZ5r",Icon__grid:"GsIgpmR",Icon__name:"_25I3NhY"}},Uy2q:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("hFTO")),s=n("c+Ev"),i=n.n(s),o=n("Ni2A"),r=Object.keys(o.a),c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={color:document.documentElement.style.getPropertyValue("--brand-primary")},e}componentDidMount(){"function"==typeof MutationObserver&&new MutationObserver(e=>{e.forEach(()=>{this.setState({color:document.documentElement.style.getPropertyValue("--brand-primary")})})}).observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}render(){return React.createElement("div",{className:i.a.Icon__wrap},r.map(e=>React.createElement("div",{className:i.a.Icon__grid,key:e},React.createElement(l.a,{size:36,name:e,color:this.state.color}),React.createElement("span",{className:i.a.Icon__name},e))))}}},Vc5Z:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Trigger\n\n触发器。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|action| `hover` or `click`|`hover`|触发类型|\n|placement|`array`||弹出层定位|\n|offset|`array`|[0, 0]|定位偏移|\n|popup|`string` or `react.element`|弹出层内容|\n|popupVisible|bool|undefined|控制弹出层visible|\n|mouseEnterDelay|number|0|鼠标进入延时|\n|mouseLeaveDelay|number|100|鼠标移出延时|\n|onPopupVisibleChange|`function`|弹出层visible变化时触发|"},VscV:function(e,t){e.exports="import { Component } from 'react';\nimport Animation from '../Animation';\nimport Select from '../../select';\nimport Button from '../../button';\nimport MOTIONS, { TIMING_FUNCTION } from '../motions';\nconst { Option } = Select;\n\nexport default class AnimationDemo extends Component {\n state = {\n timeFunction: 'ease',\n status: false,\n motion: 'fade',\n };\n render() {\n const TFS = Object.keys(TIMING_FUNCTION);\n return (\n <div>\n <h3>TIME FUNCTION</h3>\n <Select\n value={this.state.timeFunction}\n onChange={({ value }) => {\n this.setState({\n timeFunction: value,\n });\n }}\n >\n {\n TFS.map(name => (\n <Option key={name} value={name}>{name}</Option>\n ))\n }\n </Select>\n <h3>MOTIONS</h3>\n <Select\n value={this.state.motion}\n onChange={({ value }) => {\n this.setState({\n motion: value,\n });\n }}\n >\n {\n MOTIONS.map(name => (\n <Option key={name} value={name}>{name}</Option>\n ))\n }\n </Select>\n <Button\n onClick={() => {\n this.setState({\n status: !this.state.status,\n });\n }}\n >toggle</Button>\n <div>\n <Animation\n in={this.state.status}\n timingFunction={this.state.timeFunction}\n motion={this.state.motion}\n style={{\n marginTop: 20,\n display: 'inline-block',\n }}\n >\n <div style={{\n width: 100,\n height: 100,\n border: '1px solid var(--brand-primary)',\n }}></div>\n </Animation>\n </div>\n </div>\n );\n }\n}\n"},W6RA:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("RfUY")),s=n("lkey"),i=n("TDF1"),o={left:{points:["cr","cl"]},right:{points:["cl","cr"]},top:{points:["bc","tc"]},bottom:{points:["tc","bc"]},topLeft:{points:["bl","tl"]},topRight:{points:["br","tr"]},bottomRight:{points:["tr","br"]},bottomLeft:{points:["tl","bl"]}},r=["hover","click"],c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={placement:"bottom",action:"click",visible:!1},this.onChangePlacement=(e=>{this.setState({placement:e.target.value})}),this.onChangeActionType=(e=>{this.setState({action:e.target.value})}),this.onClosePopup=(()=>{this.setState({visible:!1})}),this.onPopupVisibleChange=(e=>{console.log("onPopupVisibleChange",e),this.setState({visible:e})}),e}renderPlacementSelector(){var e=this.state.placement;return React.createElement("select",{value:e,onChange:this.onChangePlacement},Object.keys(o).map(e=>React.createElement("option",{key:e},e)))}render(){var e=this.state,t=e.placement,n=e.action;return React.createElement("div",{className:"markdown-block"},React.createElement("h5",null,"普通用法"),React.createElement("label",{htmlFor:"placement"},"对齐方式"),this.renderPlacementSelector(),React.createElement("label",{htmlFor:"action"},"触发方式"),React.createElement(i.a,{value:n,onChange:this.onChangeActionType},r.map(e=>React.createElement(i.b,{value:e,key:e},e))),React.createElement(l.a,{action:n,popup:React.createElement("div",{style:{border:"1px solid #000",padding:10,background:"#fff"}},"popup content"),placement:o[t].points,mouseLeaveDelay:100},React.createElement(s.a,null,`${n} me`)),React.createElement("h5",null,"手动控制关闭"),React.createElement(l.a,{action:"click",popupVisible:this.state.visible,popup:React.createElement("div",{onClick:this.onClosePopup},"click me to close"),onPopupVisibleChange:this.onPopupVisibleChange},React.createElement(s.a,null,"click")))}}},"WL//":function(e,t,n){"use strict";function a(e){console.log(`radio checked:${e.target.value}`)}Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return h});var l=n("Jmof"),s=(n.n(l),n("TDF1")),i=n("lkey"),o=n("Cs5U"),r=s.b.Group,c=s.b.Button,m=["Apple","Pear","Orange"],u=[{label:"Apple",value:"Apple"},{label:"Pear",value:"Pear"},{label:"Orange",value:"Orange"}],p=[{label:"Apple",value:"Apple"},{label:"Pear",value:"Pear"},{label:"Orange",value:"Orange",disabled:!1}],h=class extends l.Component{constructor(e){super(e),this.onChange=(e=>{console.log("radio checked",e.target.value),this.setState({value:e.target.value})}),this.onChange1=(e=>{this.setState({value1:e.target.value})}),this.onChange2=(e=>{this.setState({value2:e.target.value})}),this.onChange3=(e=>{this.setState({value3:e.target.value})}),this.handleChange=(()=>{this.setState({checked:!this.state.checked})}),this.handleToggle=(()=>{this.setState({disabled:!this.state.disabled})}),this.state={disabled:!1,checked:!1,value:1,value1:"Apple",value2:"Apple",value3:"Apple"}}render(){var e=this.state,t=e.checked,n=e.disabled,l=e.value1,h=e.value2,d=e.value3,g=e.value;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"通过配置 options 参数来渲染单选框"),React.createElement("p",null,React.createElement(r,{options:m,onChange:this.onChange1,value:l,disabled:n})),React.createElement("p",null,React.createElement(r,{options:u,onChange:this.onChange2,value:h,disabled:n})),React.createElement("p",null,React.createElement(r,{options:p,onChange:this.onChange3,value:d,disabled:n})),React.createElement("h3",null,"嵌套的RadioGroup"),React.createElement(r,{onChange:this.onChange,value:g,disabled:n},React.createElement(s.b,{value:1},"Option A"),React.createElement(s.b,{value:2},"Option B"),React.createElement(s.b,{value:3},"Option C"),React.createElement(s.b,{value:4},"More...",4==g?React.createElement(o.a,{style:{width:100,marginLeft:10}}):null)),React.createElement("h3",null,"按钮样式的单选组合"),React.createElement(r,{onChange:a,defaultValue:"a",disabled:n},React.createElement(c,{value:"a"},"Hangzhou"),React.createElement(c,{value:"b"},"Shanghai"),React.createElement(c,{value:"c"},"Beijing"),React.createElement(c,{value:"d"},"Chengdu")),React.createElement("h3",null,"非受控方式"),React.createElement("p",null,React.createElement(s.b,{defaultChecked:!0,name:"my-radio",disabled:n}," 默认选中")),React.createElement("p",null,React.createElement(s.b,{name:"my-radio",disabled:n}," 默认")),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(s.b,{checked:t,onChange:this.handleChange,disabled:n}," ",t?"选中":"未选中")),React.createElement("p",null,React.createElement(s.b,{checked:t,onChange:this.handleChange,disabled:n}," ",t?"选中":"未选中")),React.createElement(i.a,{onClick:this.handleToggle},n?"启用":"禁用")," ",React.createElement(i.a,{onClick:this.handleChange},t?"取消选中":"选中"))}}},Xnxm:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/olivianate/\n---\n\n## Tabs\n\n选项卡切换组件\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|defaultActiveKey|number|第一个面板|初始化选中面板的 key|\n|onClick|Function|无|切换面板的回调|\n|type|String|'line'|页签的基本样式,可选 line、card、button 类型|\n|size|String|'default'|大小,提供 default 和 small 两种大小|\n|tabPosition|String||页签位置,可选值有 left|\n\n### Tabs.Panel\n|name|type|default|description|\n|---|---|---|---|\n|key|String|无|对应 activeKey|\n|title|string|无|选项卡头显示文字|\n\n### Api"},Xrcb:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Checkbox\n\nCheckbox Component.\n\n### Props\n#### Checkbox\n|name|type|default|description|\n|---|---|---|---|\n|checked|boolean|false|指定当前是否选中|\n|defaultChecked|boolean|false|初始是否选中|\n|onChange|Function(e:Event)|-|变化时回调函数|\n\n\n#### CheckboxGroup \n|name|type|default|description|\n|---|---|:---:|:---:|\n|defaultValue|Array|[]|默认选中的选项|\n|value|Array|[]|指定选中的选项|\n|options|Array|[]|指定可选项|\n|onChange|Function|-|变化时回调函数|\n### Api"},YCo2:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=n.n(a),s=n("L2Pg"),i=n("hFTO"),o=n("FaRr"),r=n.n(o),c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={theme:"dark",selectedKeys:[".$.$m0"],openKeys:null},this.handleClick=(e=>{this.setState({selectedKeys:[e.key]})}),this.handleOpenChange=(e=>{this.setState({openKeys:e})}),e}render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("table",{style:{width:"100%"}},l.a.createElement("tbody",null,l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"1、水平菜单,子菜单水平")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-h",colorType:"warm"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3"),l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用"))),l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-h",colorType:"cold"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3"),l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"2、水平菜单,子菜单垂直")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-v",colorType:"warm"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(s.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(s.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用"))),l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-v",colorType:"cold"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(s.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(s.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"3、垂直菜单,子菜单水平向右弹出")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240,height:500},defaultOpenKeys:null,type:"vertical-h",colorType:"warm"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(s.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(s.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮"))),l.a.createElement("td",null,l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240,height:500},defaultOpenKeys:null,type:"vertical-h",colorType:"cold"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(s.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(s.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"4、垂直菜单,子菜单内嵌在菜单区域")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",{style:{verticalAlign:"top"}},l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240},defaultOpenKeys:null,selectedKeys:this.state.selectedKeys,openKeys:this.state.openKeys,type:"vertical-v",colorType:"warm"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m2m2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2i2"},"三级菜单2"),l.a.createElement(s.a.Item,{key:"m2m2i3"},"三级菜单3"),l.a.createElement(s.a.Item,{key:"m2m2i4"},"三级菜单4"))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮"))),l.a.createElement("td",{style:{verticalAlign:"top"}},l.a.createElement(s.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240},defaultOpenKeys:null,selectedKeys:this.state.selectedKeys,openKeys:this.state.openKeys,type:"vertical-v",colorType:"cold"},l.a.createElement(s.a.Item,{key:"m0"},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(s.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(s.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(s.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(s.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(s.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(s.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(s.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(s.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(s.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(s.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(s.a.Item,{key:"m2m2i1"},"三级菜单1"),l.a.createElement(s.a.Item,{key:"m2m2i2"},"三级菜单2"),l.a.createElement(s.a.Item,{key:"m2m2i3"},"三级菜单3"),l.a.createElement(s.a.Item,{key:"m2m2i4"},"三级菜单4"))),l.a.createElement(s.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(i.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(s.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(s.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(s.a.Item,{key:"m4",disabled:!0},l.a.createElement(i.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮")))))))}}},YWGe:function(e,t){e.exports="---\nauthor:\n name: Northerner\n email: [email protected]\n---\n\n## Spin\n\nSpin Component.\n\n### Props\n|name|type|default|description|\n|---|---|:---:|:---:|\n|size|String|'default'|spin size,`default` `large` or `small`|\n|tip|String|-|延迟显示加载效果的时间|\n|spinning|boolean|true|是否旋转|\n|delay|number|-|延迟显示加载效果的时间|\n\n### Api"},ag5k:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Alert\n\nAlert Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|string|'info'|指定警告提示的样式,有四种选择 success、info、warning、error|\n|closable|boolean|false|\t显示关闭按钮|\n|showIcon|boolean|true|\t显示图标|\n|closeText|string or ReactNode|无|自定义关闭按钮|\n|message|string or ReactNode|无|警告提示内容|\n|description|string or ReactNode|无|警告提示的辅助性文字介绍|\n|onClose|Function|无|关闭时触发的回调函数|\n### Api"},azB9:function(e,t){e.exports="import { Component } from 'react';\nimport Alert from '../index';\n\nexport default class AlertDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n const successProps = {\n type: 'success',\n message: '这是一条正确的提示信息(信息内容)。',\n };\n const infoProps = {\n type: 'info',\n message: 'info信息',\n description: 'info描info描述info描述info描述info描述info描述info描述info描述info描述info描述info描述述',\n };\n const errorProps = {\n type: 'error',\n message: '这是一条错误的提示信息(信息内容)。',\n onClose() { console.log('error'); },\n };\n const warnProps = {\n type: 'warning',\n message: '这是一条错误的提示信息(信息内容)。',\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>基本的提示</h3>\n <Alert {...successProps} />\n <h3>可关闭的提示</h3>\n <Alert {...errorProps} closable />\n <Alert type=\"warning\" message=\"这是一条警告的提示信息(信息内容)。\" showIcon closable closeText=\"close me\" />\n <h3>带图标的提示</h3>\n <Alert {...infoProps} showIcon />\n <Alert {...successProps} showIcon />\n <Alert {...errorProps} showIcon />\n <Alert {...warnProps} showIcon />\n <h3>含有辅助性文字介绍的提示</h3>\n <Alert {...infoProps} closable showIcon />\n <Alert type=\"error\" message=\"error信息\" description=\"这是一条错误的提示信息(信息内容)。\" />\n </div>\n );\n }\n}\n"},"c+Ev":function(e,t,n){var a=n("TL+L");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},cJNF:function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../../button\';\nimport Steps from \'../Steps\';\n\nconst Step = Steps.Step;\n\nexport default class StepDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n current: 0,\n };\n this.handleNext = this.handleNext.bind(this);\n this.handlePrev = this.handlePrev.bind(this);\n }\n\n handleNext() {\n this.setState((preState) => {\n if (preState.current < 3) {\n return { current: preState.current + 1 };\n }\n return { current: 3 };\n });\n }\n\n handlePrev() {\n this.setState((preState) => {\n if (preState.current > 0) {\n return { current: preState.current - 1 };\n }\n return { current: 0 };\n });\n }\n\n render() {\n return (\n <div className="markdown-block">\n <h3><Button disabled={this.state.current <= 0} onClick={this.handlePrev}>上一步</Button> \n <Button disabled={this.state.current >= 3} onClick={this.handleNext}>下一步</Button></h3>\n <h3>横向步骤条</h3>\n <Steps current={this.state.current} style={{ marginBottom: 10 }}>\n <Step title="步骤1" />\n <Step title="步骤2" />\n <Step title="步骤3" />\n <Step title="步骤4" />\n </Steps>\n <Steps current={this.state.current} isFinishIcon style={{ marginBottom: 10 }}>\n <Step title="已完成" />\n <Step title="进行中" />\n <Step title="未进行" />\n <Step title="未进行" />\n </Steps>\n <Steps current={this.state.current} style={{ marginBottom: 10 }}>\n <Step title="步骤1" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤2" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤3" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤4" description="这是一段很长很长很长的描述性文字" />\n </Steps>\n\n <h3>竖向步骤条</h3>\n <div style={{ width: 400, display: \'inline-block\' }}>\n <Steps current={this.state.current} direction="vertical">\n <Step title="步骤1" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤2" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤3" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤4" />\n </Steps>\n </div>\n <div style={{ display: \'inline-block\' }}>\n <Steps current={this.state.current} size={\'small\'} direction="vertical" isFinishIcon>\n <Step title="已完成" description="这是一段很长很长很长的描述性文字" />\n <Step title="进行中" description="这是一段很长很长很长的描述性文字" />\n <Step title="未进行" description="这是一段很长很长很长的描述性文字" />\n <Step title="未进行" description="这是一段很长很长很长的描述性文字" />\n </Steps>\n </div>\n </div>\n );\n }\n\n}\n'},cjKs:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return i});var a=n("Jmof"),l=(n.n(a),n("o8IH")),s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},i=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={type:"success",message:"这是一条正确的提示信息(信息内容)。"},t={type:"info",message:"info信息",description:"info描info描述info描述info描述info描述info描述info描述info描述info描述info描述info描述述"},n={type:"error",message:"这是一条错误的提示信息(信息内容)。",onClose(){console.log("error")}},a={type:"warning",message:"这是一条错误的提示信息(信息内容)。"};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本的提示"),React.createElement(l.a,e),React.createElement("h3",null,"可关闭的提示"),React.createElement(l.a,s({},n,{closable:!0})),React.createElement(l.a,{type:"warning",message:"这是一条警告的提示信息(信息内容)。",showIcon:!0,closable:!0,closeText:"close me"}),React.createElement("h3",null,"带图标的提示"),React.createElement(l.a,s({},t,{showIcon:!0})),React.createElement(l.a,s({},e,{showIcon:!0})),React.createElement(l.a,s({},n,{showIcon:!0})),React.createElement(l.a,s({},a,{showIcon:!0})),React.createElement("h3",null,"含有辅助性文字介绍的提示"),React.createElement(l.a,s({},t,{closable:!0,showIcon:!0})),React.createElement(l.a,{type:"error",message:"error信息",description:"这是一条错误的提示信息(信息内容)。"}))}}},fIw2:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._3jypcj4{text-align:center;background:rgba(0,0,0,.05);border-radius:4px;margin-bottom:20px;padding:30px 50px;margin:20px 0}",""]),t.locals={example1:"_3jypcj4"}},fgYh:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return d});var a=n("Jmof"),l=(n.n(a),n("Pp2j")),s=(n("TDF1"),n("lkey"),n("a8z9")),i=n("FuzX");s.a.Panel=i.a;var o=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"标准线条式页签"),React.createElement(s.a,{activeKey:this.state.activeKey,onClick:this.onClick},this.state.panes.map(e=>React.createElement(i.a,{title:e.title,key:e.key,closable:e.closable},e.content))))}},r=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"禁用"),React.createElement("p",null,"对某项实行禁用"),React.createElement(s.a,{activeKey:this.state.activeKey,onClick:this.onClick},React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 1"),key:"1"},"Tab 1"),React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 2"),key:"2"},"Tab 2"),React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 3"),key:"3",disabled:!0},"Tab 3")))}},c=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"迷你"),React.createElement("p",null,"用在狭小的区块或子级Tab"),React.createElement(s.a,{size:"small",activeKey:this.state.activeKey,onClick:this.onClick},this.state.panes.map(e=>React.createElement(i.a,{title:e.title,key:e.key,closable:e.closable},e.content))))}},m=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"带图标"),React.createElement("p",null,"带图标的Tab"),React.createElement(s.a,{activeKey:this.state.activeKey,onClick:this.onClick},React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 1"),key:"1"},"Tab 1"),React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 2"),key:"2"},"Tab 2"),React.createElement(i.a,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 3"),key:"3"},"Tab 3")))}},u=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"纵向"),React.createElement("p",null,"纵向的Tab"),React.createElement(s.a,{activeKey:this.state.activeKey,tabPosition:"left",onClick:this.onClick},this.state.panes.map(e=>React.createElement(i.a,{title:e.title,key:e.key,closable:e.closable},e.content))))}},p=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"卡片式"),React.createElement("p",null,"卡片式的页签,常用于容器顶部"),React.createElement(s.a,{activeKey:this.state.activeKey,type:"card",tabDeleteButton:!0,deleteButton:this.deleteButton,onClick:this.onClick},this.state.panes.map(e=>React.createElement(i.a,{title:e.title,key:e.key,closable:e.closable},e.content))))}},h=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("p",null,"button可作为更次级的页签来使用"),React.createElement(s.a,{activeKey:this.state.activeKey,type:"button",onClick:this.onClick},this.state.panes.map(e=>React.createElement(i.a,{title:e.title,key:e.key,closable:e.closable},e.content))))}},d=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement(o,null),React.createElement("br",null),React.createElement("br",null),React.createElement(r,null),React.createElement("br",null),React.createElement("br",null),React.createElement(c,null),React.createElement("br",null),React.createElement("br",null),React.createElement(m,null),React.createElement("br",null),React.createElement("br",null),React.createElement(u,null),React.createElement("br",null),React.createElement("br",null),React.createElement(p,null),React.createElement("br",null),React.createElement("br",null),React.createElement(h,null),React.createElement("br",null),React.createElement("br",null))}}},frv8:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Message\n\nMessage Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|duration|Number|1.8|message 1.8s之后关闭|\n|onClose|Function|function(){}|message 关闭之后的回调|\n|type|String|'info'|message 提示类型|\n### Api\n组件提供了一些静态方法,使用方式和参数如下:\n\n - message.success(content, duration, onClose)\n - message.error(content, duration, onClose)\n - message.info(content, duration, onClose)\n - message.warning(content, duration, onClose)\n\n\n#### 参数\n|name|type|default|description|\n|---|---|---|---|\n|content|string|''|提示内容\n|duration|Number|1.8|message 默认1.8s之后关闭,可通过config设置|\n|onClose|Function|function(){}|message 关闭之后的回调,可通过config设置|\n\n还提供了全局配置和全局销毁方法:\n\n - message.config(options)\n - message.destroty() \n\n\n#### config方法参数\n|name|type|default|description|\n|---|---|---|---|\n|top|number|50px|消息距离顶部的距离\n|duration|Number|1.8|message 默认1.8s之后关闭,可通过config设置|\n|getContainer|Function|function(){}|配置渲染节点的输出位置|\n\n"},iBQZ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return i});var a=n("Jmof"),l=n.n(a),s=n("E7AL"),i=class extends a.Component{render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"标准进度条"),l.a.createElement("div",null,l.a.createElement(s.a,{percent:30}),l.a.createElement(s.a,{percent:70,status:"exception"}),l.a.createElement(s.a,{percent:70,status:"pause"}),l.a.createElement(s.a,{percent:100,status:"success"}),l.a.createElement(s.a,{percent:100}),l.a.createElement(s.a,{percent:50,showInfo:!1})),l.a.createElement("h3",null,"小型进度条"),l.a.createElement("p",null,"适合放在较狭窄的区域内"),l.a.createElement("div",{style:{width:170}},l.a.createElement(s.a,{percent:30,size:"mini"}),l.a.createElement(s.a,{percent:70,size:"mini",status:"exception"}),l.a.createElement(s.a,{percent:70,size:"mini",status:"pause"}),l.a.createElement(s.a,{percent:100,size:"mini",status:"success"}),l.a.createElement(s.a,{percent:100,size:"mini"})))}}},iHBT:function(e,t){e.exports='import React, { Component } from \'react\';\nimport Menu from \'../Menu\';\nimport Icon from \'../../icon/Icon\';\nimport styles from \'./index.css\';\n\nexport default class MenuDemo extends Component {\n state = {\n theme: \'dark\',\n selectedKeys: [\'.$.$m0\'],\n openKeys: null,\n }\n\n handleClick = (e) => {\n this.setState({\n selectedKeys: [e.key],\n });\n }\n handleOpenChange = (openKeys) => {\n this.setState({\n openKeys,\n });\n }\n\n render() {\n // const defaultOpenKeys = [\'.$m1\', \'.$.$m2\', \'.$.$m2m2\'];\n const defaultOpenKeys = null;\n\n return (\n <div className="markdown-block">\n <table style={{ width: \'100%\' }}>\n <tbody>\n <tr>\n <td colSpan="2">1、水平菜单,子菜单水平</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-h"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-h"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">2、水平菜单,子菜单垂直</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-v"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-v"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">3、垂直菜单,子菜单水平向右弹出</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240, height: 500 }}\n defaultOpenKeys={defaultOpenKeys}\n type="vertical-h"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240, height: 500 }}\n defaultOpenKeys={defaultOpenKeys}\n type="vertical-h"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">4、垂直菜单,子菜单内嵌在菜单区域</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td style={{ verticalAlign: \'top\' }}>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240 }}\n defaultOpenKeys={defaultOpenKeys}\n selectedKeys={this.state.selectedKeys}\n openKeys={this.state.openKeys}\n type="vertical-v"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m2m2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2i2">三级菜单2</Menu.Item>\n <Menu.Item key="m2m2i3">三级菜单3</Menu.Item>\n <Menu.Item key="m2m2i4">三级菜单4</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n <td style={{ verticalAlign: \'top\' }}>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240 }}\n defaultOpenKeys={defaultOpenKeys}\n selectedKeys={this.state.selectedKeys}\n openKeys={this.state.openKeys}\n type="vertical-v"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m2m2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2i2">三级菜单2</Menu.Item>\n <Menu.Item key="m2m2i3">三级菜单3</Menu.Item>\n <Menu.Item key="m2m2i4">三级菜单4</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n }\n}\n'},jC5m:function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../../button/Button\';\nimport Select from \'../Select\';\nimport OptGroup from \'../OptGroup\';\nimport Option from \'../Option\';\nimport querystring from \'querystring\';\nimport jsonp from \'fetch-jsonp\';\n\nclass SelectDemo1 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n };\n }\n\n onChange = ({ text, value }) => {\n this.setState({\n value,\n text,\n });\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setSelect = () => {\n this.setState({\n value: \'B\',\n });\n }\n\n render() {\n const { value, disabled } = this.state;\n\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ disabled ? \'启用\' : \'禁用\'}</Button> \n <Button onClick={this.setSelect}>{ \'选中BB\' }</Button>\n <h3>受控</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} defaultValue="C" value={value} onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n\n <h3>非受控</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} defaultValue="C" onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\n\nclass SelectDemo2 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setSelect = () => {\n this.setState({\n value: \'B\',\n });\n }\n\n onChange = ({ text, value }) => {\n this.setState({\n value,\n text,\n });\n }\n\n render() {\n const { value, disabled } = this.state;\n\n return (\n <div className="markdown-block">\n <h3>分组</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} value={value} onChange={this.onChange} placeholder={"请选择"}>\n <OptGroup label="分组1">\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n </OptGroup>\n <OptGroup label="分组2">\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n </OptGroup>\n <OptGroup label="分组3">\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </OptGroup>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n\n <h3>复杂选项。</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} value={value} onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A" text="李大力">\n <div>李大力</div><div>1354534324</div><div>杭州萧山区民和路</div>\n </Option>\n <Option value="B" text="李启">\n <div>李启</div><div>1356664324</div><div>杭州江干区</div>\n </Option>\n <Option value="C" text="李宇">\n <div>李宇</div><div>1377534324</div><div>杭州富阳</div>\n </Option>\n <Option value="D" text="李琦">\n <div>李琦</div><div>1354554324</div><div>杭州滨江区江</div>\n </Option>\n <Option value="E" text="李小燕">\n <div>李小燕</div><div>1387564324</div><div>上海黄埔区</div>\n </Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\n\nclass SelectDemo3 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n searchData: [],\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setDefaultValue = () => {\n this.setState({\n value: \'CPU\',\n text: \'CPU\',\n });\n }\n\n onSearch = (value) => {\n const str = querystring.encode({\n code: \'utf-8\',\n q: value,\n });\n jsonp(`https://suggest.taobao.com/sug?${str}`)\n .then(response => response.json())\n .then((d) => {\n const result = d.result;\n const data = [];\n result.forEach((r) => {\n data.push({\n value: r[0],\n text: r[0],\n });\n });\n this.setState({\n searchData: data,\n });\n });\n }\n\n onChange = ({ value, text }) => {\n this.setState({\n value,\n text,\n });\n }\n\n render() {\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ this.state.disabled ? \'启用\' : \'禁用\'}</Button> \n <Button onClick={this.setDefaultValue}>设值</Button>\n <h3>带搜索框。</h3>\n <p />\n <Select\n style={{ width: 250 }}\n disabled={this.state.disabled}\n value={this.state.value}\n text={this.state.text}\n type="combobox"\n onSearch={this.onSearch}\n onCancelChange={this.onCancelChange}\n onChange={this.onChange}\n placeholder="请输入查询条件"\n >\n {\n this.state.searchData.map(d => <Option key={d.value} value={d.value}>{d.text}</Option>)\n }\n </Select>\n\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\nclass SelectDemo4 extends Component {\n constructor() {\n super();\n this.state = {\n value: null,\n text: null,\n disabled: false,\n province: null,\n city: null,\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n onChangeProvince = ({ value, text }) => {\n this.setState({\n province: value,\n provinceText: text,\n city: null,\n cityText: null,\n });\n }\n onChangeCity = ({ value, text }) => {\n this.setState({\n city: value,\n cityText: text,\n });\n }\n\n getCitysByProvince = (province) => {\n switch (province) {\n case \'1\':\n return [{ value: \'11\', text: \'杭州\' },\n { value: \'12\', text: \'湖州\' },\n { value: \'13\', text: \'绍兴\' }];\n case \'2\':\n return [{ value: \'21\', text: \'广州\' },\n { value: \'22\', text: \'东莞\' },\n { value: \'23\', text: \'中山\' }];\n case \'3\':\n return [{ value: \'31\', text: \'福州\' },\n { value: \'32\', text: \'泉州\' },\n { value: \'33\', text: \'厦门\' }];\n default:\n return [];\n }\n }\n\n render() {\n const citys = this.getCitysByProvince(this.state.province).map((v, i) => <Option value={v.value} key={i}>{v.text}</Option>);\n\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ this.state.disabled ? \'启用\' : \'禁用\'}</Button>\n <h3>联动。</h3>\n <p />\n 省:\n <Select style={{ width: 250 }} disabled={this.state.disabled} value={this.state.province} onChange={this.onChangeProvince}>\n <Option value="1">浙江省</Option>\n <Option value="2">广东省</Option>\n <Option value="3">福建省</Option>\n </Select>\n 市:\n <Select style={{ width: 250 }} disabled={this.state.disabled} value={this.state.city} onChange={this.onChangeCity}>\n {citys}\n </Select>\n <span>选中值:{`${this.state.province}-${this.state.provinceText},${this.state.city}-${this.state.cityText}`}</span>\n </div>\n );\n }\n}\n\nexport default class SelectDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <SelectDemo1 />\n <br /><br />\n <SelectDemo2 />\n <br /><br />\n <SelectDemo3 />\n <br /><br />\n <SelectDemo4 />\n </div>\n );\n }\n}\n'},kMPS:function(e,t,n){"use strict";function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,n,s){t=t||"&",n=n||"=";var i={};if("string"!=typeof e||0===e.length)return i;var o=/\+/g;e=e.split(t);var r=1e3;s&&"number"==typeof s.maxKeys&&(r=s.maxKeys);var c=e.length;r>0&&c>r&&(c=r);for(var m=0;m<c;++m){var u,p,h,d,g=e[m].replace(o,"%20"),y=g.indexOf(n);y>=0?(u=g.substr(0,y),p=g.substr(y+1)):(u=g,p=""),h=decodeURIComponent(u),d=decodeURIComponent(p),a(i,h)?l(i[h])?i[h].push(d):i[h]=[i[h],d]:i[h]=d}return i};var l=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},kimJ:function(e,t,n){var a=n("CvA4");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},liFK:function(e,t){e.exports="import React, { Component } from 'react';\nimport Upload from '../Upload';\nimport Icon from '../../icon/Icon';\nimport Button from '../../button/Button';\nimport message from '../../message/index';\nimport styles from './index.css';\n\nclass UploadDemo1 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n };\n }\n render() {\n const props = {\n name: 'file',\n action: 'https://jsonplaceholder.typicode.com/posts/',\n headers: {\n authorization: 'authorization-text',\n },\n multiple: true,\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url,\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n if (info.file.status !== 'uploading') {\n // console.log(info.file, info.fileList);\n }\n if (info.file.status === 'done') {\n message.success(`${info.file.name} 文件上传成功.`);\n } else if (info.file.status === 'error') {\n message.error(`${info.file.name} 文件上传失败!`);\n }\n },\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>1、经典款式,用户点击按钮弹出文件选择框。</h3>\n <Upload {...props}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo2 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n };\n }\n render() {\n const props = {\n name: 'file',\n action: 'https://jsonplaceholder.typicode.com/posts/',\n headers: {\n authorization: 'authorization-text',\n },\n multiple: true,\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url,\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n if (info.file.status !== 'uploading') {\n // console.log(info.file, info.fileList);\n }\n if (info.file.status === 'done') {\n message.success(`${info.file.name} 文件上传成功.`);\n } else if (info.file.status === 'error') {\n message.error(`${info.file.name} 文件上传失败!`);\n }\n },\n defaultFileList: [{\n uid: 1,\n name: '图片1.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }, {\n uid: 2,\n name: '图片2.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }, {\n uid: 3,\n name: '图片3.png',\n status: 'error',\n response: '上传失败,图片太大',\n }],\n };\n\n\n return (\n <div className=\"markdown-block\">\n <h3>2、已上传文件的列表</h3>\n <p>使用 defaultFileList 设置已上传的内容。</p>\n <Upload {...props}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo3 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n fileList: [{\n uid: -1,\n name: 'xxx.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }],\n };\n }\n\n render() {\n const I = this;\n const props = {\n action: '//jsonplaceholder.typicode.com/posts/',\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url, // 上传成功的图片路径\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n let fileList = info.fileList;\n\n // 最多只留1个文件,前面的将会被替换\n fileList = fileList.slice(-1);\n\n // 读取上传后的文件链接\n fileList = fileList.map((file) => {\n if (file.response) {\n file.url = file.response.url;\n }\n return file;\n });\n\n // // 过滤上传成功的文件\n // fileList = fileList.filter((file) => {\n // if (file.response) {\n // return file.status === 'done';\n // }\n // return true;\n // });\n\n I.setState({ fileList });\n },\n };\n return (\n <div className=\"markdown-block\">\n <h3>3、使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:</h3>\n <p>1) 上传列表数量的限制。</p>\n <p>2) 读取远程路径并显示链接。</p>\n <p>3) 按照服务器返回信息筛选成功上传的文件。</p>\n <Upload {...props} fileList={this.state.fileList}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo4 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n fileList: [{\n uid: -1,\n name: 'xxx.png',\n status: 'done',\n url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',\n }],\n };\n }\n // 点击查看源图时触发\n handlePreview = (file) => {\n window.open(file.url);\n }\n\n handleChange = (info) => {\n this.setState({ fileList: info.fileList });\n }\n beforeUpload(file) {\n const isJPG = file.type === 'image/png';\n if (!isJPG) {\n message.error('请上传.png文件!');\n }\n const isLt2M = file.size < 1024 * 1000;\n if (!isLt2M) {\n message.error('图片不能超过1000KB!');\n }\n return isJPG && isLt2M;\n }\n render() {\n const props = {\n action: '//jsonplaceholder.typicode.com/posts/',\n disabled: false,\n listType: 'picture-card',\n fileList: this.state.fileList,\n onPreview: this.handlePreview,\n onChange: this.handleChange,\n beforeUpload: this.beforeUpload,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' }; // mock数据\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url, // 上传成功的图片路径\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n };\n\n const uploadButton = (\n <div className={styles['upload-btn']}>\n <Icon name=\"plus\" size={25} />\n <div className={styles['upload-text']}>上传</div>\n </div>\n );\n return (\n <div className=\"markdown-block\">\n <h3>4、显示上传缩略图</h3>\n <p>点击上传图片,并使用 beforeUpload 限制用户上传的图片格式和大小。</p>\n <Upload {...props}>\n {this.state.fileList.length >= 3 ? null : uploadButton}\n </Upload>\n </div>\n );\n }\n}\n\nexport default class UploadDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <UploadDemo1 />\n <br /><br />\n <UploadDemo2 />\n <br /><br />\n <UploadDemo3 />\n <br /><br />\n <UploadDemo4 />\n </div>\n );\n }\n}\n"},"n+PT":function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Steps\n\nSteps Component.\n\n### Props\n#### Steps 整体步骤条\n|name|type|default|description|\n|---|---|:---:|:---:|\n|current|number|0|指定当前步骤,从 0 开始记数|\n|status|string|process|指定当前步骤的状态,可选 `wait` `process` `finish`|\n|direction|string|horizontal|指定步骤条方向。默认水平|\n|isFinishIcon|boolean|false|指定finish状态的显示方式是否使用Icon|\n\n#### Steps.Step 步骤条内的每一个步骤\n|name|type|default|description|\n|---|---|:---:|:---:|\n|status|string|wait|指定状态。当不配置该属性时,会使用 Steps 的 current 来自动指定状态。|\n|title|string or ReactNode|无|标题|\n|description|string or ReactNode|无|描述,可选|\n### Api"},nYGS:function(e,t){e.exports="---\nauthor:\n name: ryan.bian / lhf-nife\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Modal\n\n模态对话框。\n\n### 何时使用\n\n需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 Modal 在当前页面正中打开一个浮层,承载相应的操作。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|title|string|--|对话框标题\n|closable|boolean|true|是否显示关闭按钮\n|width|number|520|对话框宽度\n|visible|boolean|false|对话框是否显示\n|footer|element|--|对话框底部按钮\n|onOk|func|--|确认按钮触发事件\n|onCancel|func|--|取消按钮触发事件\n|afterClose|func|--|对话框关闭后事件\n\n### Api\n#### Modal.method()\n\n- 包括:\n - Modal.info\n - Modal.success\n - Modal.error\n - Modal.warning\n- 以上均为一个函数,参数为object,具体属性如下:\n\n|name|type|default|description|\n|---|---|---|---|\n|title|string|info/success/eror/warning|对话框标题\n|content|string|--|对话框内容\n|closable|boolean|false|是否显示关闭按钮"},o3DI:function(e,t){e.exports="class Playground extends React.Component {\n render() {\n return <Button>Button</Button>;\n }\n}\n\nreturn <Playground />;"},pIU7:function(e,t,n){"use strict";function a(e,t){var n={};for(var a in e)t.indexOf(a)>=0||Object.prototype.hasOwnProperty.call(e,a)&&(n[a]=e[a]);return n}function l(e){return(e.ctrlKey||e.metaKey)&&e.keyCode===(e.shiftKey?C:v)}function s(e){return(e.ctrlKey||e.metaKey)&&e.keyCode===(e.shiftKey?v:C)}function i(e){var t=void 0,n=void 0,a=void 0,l=void 0;if(void 0!==e.selectionStart)t=e.selectionStart,n=e.selectionEnd;else try{e.focus(),l=(a=e.createTextRange()).duplicate(),a.moveToBookmark(document.selection.createRange().getBookmark()),l.setEndPoint("EndToStart",a),n=(t=l.text.length)+a.text.length}catch(e){}return{start:t,end:n}}function o(e,t){var n=void 0;try{void 0!==e.selectionStart?(e.focus(),e.setSelectionRange(t.start,t.end)):(e.focus(),(n=e.createTextRange()).collapse(!0),n.moveStart("character",t.start),n.moveEnd("character",t.end-t.start),n.select())}catch(e){}}var r,c,m=n("Jmof"),u=n.n(m),p=n("13mF"),h=n.n(p),d=n("KSGD"),g=n.n(d),y=n("HW6M"),b=n.n(y),k=n("PewI"),f=n.n(k),E=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},v=90,C=89,I=(c=r=class extends m.PureComponent{constructor(){var e;return e=super(...arguments),this.onChange=(e=>{var t=this.mask.getValue();if(e.target.value!==t){if(e.target.value.length<t.length){var n=t.length-e.target.value.length;this.mask.selection=i(this.input),this.mask.selection.end=this.mask.selection.start+n,this.mask.backspace()}var a=this.getDisplayValue();e.target.value=a,a&&o(this.input,this.mask.selection)}this.props.onChange&&this.props.onChange(e)}),this.onKeyPress=(e=>{e.metaKey||e.altKey||e.ctrlKey||"Enter"===e.key||(e.preventDefault(),this.mask.selection=i(this.input),this.mask.input(e.key||e.data)&&(e.target.value=this.mask.getValue(),o(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)))}),this.onKeyDown=(e=>{if(l(e))return e.preventDefault(),void(this.mask.undo()&&(e.target.value=this.getDisplayValue(),o(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)));if(s(e))return e.preventDefault(),void(this.mask.redo()&&(e.target.value=this.getDisplayValue(),o(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)));if("Backspace"===e.key&&(e.preventDefault(),this.mask.selection=i(this.input),this.mask.backspace())){var t=this.getDisplayValue();e.target.value=t,t&&o(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)}}),this.onPaste=(e=>{e.preventDefault(),this.mask.selection=i(this.input),this.mask.paste(e.clipboardData.getData("Text"))&&(e.target.value=this.mask.getValue(),o(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e))}),this.getDisplayValue=(()=>{var e=this.mask.getValue();return e===this.mask.emptyValue?"":e}),this.getEventHandlers=(()=>({onChange:this.onChange,onKeyDown:this.onKeyDown,onPaste:this.onPaste,onKeyPress:this.onKeyPress})),e}componentWillMount(){var e={pattern:this.props.mask,value:this.props.value,formatCharacters:this.props.formatCharacters};this.props.placeholderChar&&(e.placeholderChar=this.props.placeholderChar),this.mask=new h.a(e)}render(){var e=this.mask.pattern.length,t=this.getDisplayValue(),n=this.getEventHandlers(),l=this.props,s=l.disabled,i=l.size,o=void 0===i?e:i,r=l.placeholder,c=void 0===r?this.mask.emptyValue:r,m=this.props,p=(m.placeholderChar,m.formatCharacters,a(m,["placeholderChar","formatCharacters"])),h=E({},p,n,{ref:e=>this.input=e,maxLength:e,value:t,size:o,placeholder:c,className:b()(f.a[`${s?"input__disabled":""}`],f.a[`input__${o}`])});return u.a.createElement("input",h)}},r.displayName="CardInput",r.defaultProps={size:"normal",disabled:!1,mask:"1111-1111-1111-1111",value:""},r.propTypes={size:g.a.oneOf(["normal","large","small"]),disabled:g.a.bool,mask:g.a.string.isRequired,formatCharacters:g.a.object,placeholderChar:g.a.string,onChange:g.a.func},c);t.a=I},qeLS:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("Jmof"),l=(n.n(a),n("XFRO")),s=n("Pp2j"),i=n("mkCw"),o=n("pIU7"),r=class extends a.Component{constructor(e){super(e),this.onChangeCard=(e=>{var t=e.target.value;this.setState({value:t})}),this.state={value:"1234-1234-1234-1234"}}render(){var e=React.createElement(s.a,{size:12,name:"account"});return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"输入框"),React.createElement(l.a,{placeholder:"请输入",defaultValue:"12345465"}),React.createElement("h3",null,"图标"),React.createElement("p",null,"图标输入框"),React.createElement(l.a,{placeholder:"请输入",prefix:e}),React.createElement("h3",null,"大小"),React.createElement("p",null,"三种大小的数字输入框"),React.createElement(l.a,{size:"large",placeholder:"large size"}),React.createElement("p",null),React.createElement(l.a,{size:"normal",placeholder:"normal size"}),React.createElement("p",null),React.createElement(l.a,{size:"small",placeholder:"small size"}),React.createElement("h3",null,"禁用"),React.createElement("p",null,"输入框禁用"),React.createElement("p",null,React.createElement(l.a,{placeholder:"input disabled",defaultValue:"12345465",disabled:!0})),React.createElement("h3",null,"搜索框"),React.createElement("p",null,"带有搜索按钮的输入框"),React.createElement(i.a,{size:"large",placeholder:"input search text",style:{width:240}}),React.createElement("p",null),React.createElement(i.a,{placeholder:"input search text",style:{width:240}}),React.createElement("p",null),React.createElement(i.a,{size:"small",placeholder:"input search text",style:{width:240}}),React.createElement("h3",null,"文本域"),React.createElement("p",null,"用于多行输入"),React.createElement(l.a,{type:"textarea",placeholder:"请输入",autosize:!0,rows:1}),React.createElement(l.a,{type:"textarea",placeholder:"请输入",rows:6}),React.createElement("h3",null,"格式化"),React.createElement("p",null,"针对16或多位格式化输入"),React.createElement(o.a,{size:"large",mask:"1111-1111-1111-1111",placeholder:"1234-1234-1234-1234",value:this.state.value,onChange:this.onChangeCard}),React.createElement("p",null),React.createElement(o.a,{size:"normal",mask:"111111-111111-111111-111111",onChange:this.onChangeCard}))}}},tTp3:function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Button\n\n按钮用于开始一个即时操作。\n\n### 何时使用\n\n标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|placeholder|String|'请选择'|选择框默认文字|\n|type|String|dropdown|单选(dropdown),搜索(combobox)|\n|style|Object|{width: 200}|{width: 100},目录支持宽度|\n|disabled|bool|false|是否禁用|\n|value|String|''|选中的值,与子控件Option的value对应|\n|onSearch|function(value)|null|当type为combobox有效,搜索文本框内容改变时回调,用于过滤数据|\n|onChange|function({value,text})|null|选中项改变时回调|\n|onCancelChange|function()|null|当type为combobox有效,搜索文本框内容取消改变时回调|\n\n### Api"},tsro:function(e,t){e.exports="import { Component } from 'react';\nimport Radio from '../index';\nimport Button from '../../button';\nimport Input from '../../input';\n\nconst RadioGroup = Radio.Group;\nconst RadioButton = Radio.Button;\n\nconst plainOptions = ['Apple', 'Pear', 'Orange'];\nconst options = [\n { label: 'Apple', value: 'Apple' },\n { label: 'Pear', value: 'Pear' },\n { label: 'Orange', value: 'Orange' },\n];\nconst optionsWithDisabled = [\n { label: 'Apple', value: 'Apple' },\n { label: 'Pear', value: 'Pear' },\n { label: 'Orange', value: 'Orange', disabled: false },\n];\n\nfunction onChange(e) {\n console.log(`radio checked:${e.target.value}`);\n}\nexport default class RadioDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n disabled: false,\n checked: false,\n\n\n value: 1,\n value1: 'Apple',\n value2: 'Apple',\n value3: 'Apple',\n };\n }\n\n onChange=(e) => {\n console.log('radio checked', e.target.value);\n this.setState({\n value: e.target.value,\n });\n }\n\n onChange1=(e) => {\n this.setState({\n value1: e.target.value,\n });\n }\n\n onChange2=(e) => {\n this.setState({\n value2: e.target.value,\n });\n }\n\n onChange3=(e) => {\n this.setState({\n value3: e.target.value,\n });\n }\n\n handleChange=() => {\n this.setState({\n checked: !this.state.checked,\n });\n }\n\n handleToggle=() => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n render() {\n const { checked, disabled, value1, value2, value3, value } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>通过配置 options 参数来渲染单选框</h3>\n <p><RadioGroup options={plainOptions} onChange={this.onChange1} value={value1} disabled={disabled} /></p>\n <p><RadioGroup options={options} onChange={this.onChange2} value={value2} disabled={disabled} /></p>\n <p><RadioGroup options={optionsWithDisabled} onChange={this.onChange3} value={value3} disabled={disabled} /></p>\n\n <h3>嵌套的RadioGroup</h3>\n <RadioGroup onChange={this.onChange} value={value} disabled={disabled}>\n <Radio value={1}>Option A</Radio>\n <Radio value={2}>Option B</Radio>\n <Radio value={3}>Option C</Radio>\n <Radio value={4}>\n More...\n {value == 4 ? <Input style={{ width: 100, marginLeft: 10 }} /> : null}\n </Radio>\n </RadioGroup>\n\n <h3>按钮样式的单选组合</h3>\n <RadioGroup onChange={onChange} defaultValue=\"a\" disabled={disabled}>\n <RadioButton value=\"a\">Hangzhou</RadioButton>\n <RadioButton value=\"b\">Shanghai</RadioButton>\n <RadioButton value=\"c\">Beijing</RadioButton>\n <RadioButton value=\"d\">Chengdu</RadioButton>\n </RadioGroup>\n\n <h3>非受控方式</h3>\n <p><Radio defaultChecked name={'my-radio'} disabled={disabled}> 默认选中</Radio></p>\n <p>\n <Radio name={'my-radio'} disabled={disabled}> 默认</Radio>\n </p>\n <h3>受控方式</h3>\n <p>\n <Radio checked={checked} onChange={this.handleChange} disabled={disabled}> {checked ? '选中' : '未选中'}</Radio></p>\n <p>\n <Radio checked={checked} onChange={this.handleChange} disabled={disabled}> {checked ? '选中' : '未选中'}</Radio>\n </p>\n <Button onClick={this.handleToggle}>{disabled ? '启用' : '禁用'}</Button> \n <Button onClick={this.handleChange}>{checked ? '取消选中' : '选中'}</Button>\n </div>\n );\n }\n}\n"},vMWu:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Radio\n\nRadio Component.\n\n### Props\n#### Radio\n|name|type|default|description|\n|---|---|---|---|\n|checked|boolean|false|指定当前是否选中|\n|defaultChecked|boolean|false|初始是否选中|\n|value|any|无|根据 value 进行比较,判断是否选中|\n\n#### RadioGroup \n|name|type|default|description|\n|---|---|:---:|:---:|\n|onChange|Function|-|选项变化时的回调函数|\n|value|any|-|用于设置当前选中的值|\n|defaultValue|any|-|默认选中的值|\n|options|string[] or Array|-|以配置形式设置子元素|\n### Api"},"w+gr":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return i});var a=n("Jmof"),l=(n.n(a),n("gPfh")),s=n("lkey"),i=class extends a.Component{constructor(e){super(e),this.openModal=this.openModal.bind(this),this.state={visible:!1}}openModal(){this.setState({visible:!0})}closeModal(){this.setState({visible:!1})}render(){var e={title:"标题",visible:this.state.visible,onOk:()=>{this.closeModal(),console.log("onOK")},onCancel:()=>{this.closeModal(),console.log("onCancel")},afterClose(){console.log("afterClose")}};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement(s.a,{type:"secondary",onClick:this.openModal},"open modal"),React.createElement(l.a,e,React.createElement("p",null,"这是一段信息。")),React.createElement("h3",null,"信息提示"),React.createElement("p",null,"各种类型的信息提示,只提供一个按钮用于关闭。"),React.createElement(s.a,{type:"secondary",onClick:()=>{l.a.info({content:"这是提示信息",closable:!0})}},"info")," ",React.createElement(s.a,{type:"secondary",onClick:()=>{l.a.success({content:"这是成功消息"})}},"success")," ",React.createElement(s.a,{type:"secondary",onClick:()=>{l.a.error({content:"这是错误提示"})}},"error")," ",React.createElement(s.a,{type:"secondary",onClick:()=>{l.a.warning({content:"这是警告信息"})}},"warning"))}}},wVe3:function(e,t){e.exports='---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Upload\n\nUpload Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|name|String|file|发到后台的文件参数名|\n|defaultFileList|object[]|[]|默认已经上传的文件列表|\n|action|String|\'\'|必选参数, 上传的地址|\n|data|object|function(file)|上传所需参数或返回上传参数的方法|\n|headers|object|null|设置上传的请求头部,IE10 以上有效|\n|showUploadList|bool or { showPreviewIcon?: boolean, showRemoveIcon?: boolean }|true|是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon|\n|multiple|bool|false|是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。|\n|accept|String|\'\'|接受上传的文件类型|\n|beforeUpload|(file, fileList) => boolean 或 Promise|null|上传文件之前的钩子,参数为上传的文件,若返回 false 或者 Promise 则停止上传。注意:该方法不支持老 IE。|\n|customRequest|Function|null|通过覆盖默认的上传行为,可以自定义自己的上传实现|\n|onChange|Function|null|上传文件改变时的状态,详见 onChange|\n|listType|String|\'text\'|上传列表的内建样式,支持两种基本样式 text or picture-card|\n|onPreview|Function(file)|null|点击文件链接或预览图标时的回调|\n|onRemove|Function(file): boolean 或 Promise|null|点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象,Promise 对象 resolve(false) 或 reject 时不移除。|\n|disabled|bool|false|是否禁用|\n|withCredentials|bool|false|上传请求时是否携带 cookie|\n|onResponse|Function(response)|默认根据下面结构处理:{"result":"success","msg":"上传成功", url:"http://abc.jpg"}|根据服务端返回的内容,判断是否上传成功|\n\n\n\n### Api'},whSr:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/olivianate/\n---\n\n## InputNumber\n\n通过鼠标或键盘,输入范围内的数值\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|min|number||最小值|\n|max|number||最大值|\n|value|number||当前值|\n|step|number,string|1|每次改变步数,可以为小数|\n|defaultValue|number||初始值|\n|onChange|Function(value)||变化回调|\n|disabled|boolean|false|禁用|\n|formatter|function(value)||指定输入框展示值的格式|\n|parser|function( string): number||指定从 formatter 里转换回数字的方式,和 formatter 搭配使用|\n|style|CSSProperties||||\n\n### Api"},xaZU:function(e,t,n){"use strict";function a(e,t){if(e.map)return e.map(t);for(var n=[],a=0;a<e.length;a++)n.push(t(e[a],a));return n}var l=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,n,o){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?a(i(e),function(i){var o=encodeURIComponent(l(i))+n;return s(e[i])?a(e[i],function(e){return o+encodeURIComponent(l(e))}).join(t):o+encodeURIComponent(l(e[i]))}).join(t):o?encodeURIComponent(l(o))+n+encodeURIComponent(l(e)):""};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},xiJQ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("WG9z")),s=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本面包屑"),React.createElement("p",null,React.createElement(l.a,null,React.createElement(l.a.Item,null,"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb"))),React.createElement(l.a,{separator:">"},React.createElement(l.a.Item,null,"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb")),React.createElement("h3",null,"带返回的面包屑"),React.createElement("p",null,React.createElement(l.a,{hasBackIcon:!0},React.createElement(l.a.Item,{href:"/"},"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb"))),React.createElement(l.a,{hasBackIcon:!0,separator:">"},React.createElement(l.a.Item,{href:"/"},"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb")))}}},"y/Xd":function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n---\n\n## Progress\n\nProgress Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|status|string|normal|`normal` `exception` `pause` or `success`|\n|percent|number|0|进度百分比|\n|showInfo|true|boolean|是否显示进度数值或状态图标|\n|size|string|normal|进度条尺寸,`normal` or `mini`|\n\n### Api"},yHpG:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("9q7S")),s=n("2tft"),i=n("lkey"),o=n("YSWR"),r=s.a.Option,c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={timeFunction:"ease",status:!1,motion:"fade"},e}render(){var e=Object.keys(o.a);return React.createElement("div",null,React.createElement("h3",null,"TIME FUNCTION"),React.createElement(s.a,{value:this.state.timeFunction,onChange:e=>{var t=e.value;this.setState({timeFunction:t})}},e.map(e=>React.createElement(r,{key:e,value:e},e))),React.createElement("h3",null,"MOTIONS"),React.createElement(s.a,{value:this.state.motion,onChange:e=>{var t=e.value;this.setState({motion:t})}},o.b.map(e=>React.createElement(r,{key:e,value:e},e))),React.createElement(i.a,{onClick:()=>{this.setState({status:!this.state.status})}},"toggle"),React.createElement("div",null,React.createElement(l.a,{in:this.state.status,timingFunction:this.state.timeFunction,motion:this.state.motion,style:{marginTop:20,display:"inline-block"}},React.createElement("div",{style:{width:100,height:100,border:"1px solid var(--brand-primary)"}}))))}}},yL0p:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Breadcrumb\n\nBreadcrumb Component.\n\n### Props\n|name|type|default|description|\n|---|---|:---:|---|\n|prefixCls|String|'breadcrumb'|预先定义的样式前缀|\n|separator|String|'/'|面包屑的分隔符|\n|hasBackIcon|Boolean|false|是否显示回退按钮|\n### Api\n"},yPNB:function(e,t){e.exports="import Pagination from '../Pagination';\nimport { Component } from 'react';\n\nexport default class PaginationDemo extends Component {\n state = {\n current: 3,\n };\n render() {\n const { current } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>基础分页。</p>\n <Pagination current={current} total={50} />\n <h3>更多分页</h3>\n <Pagination\n defaultCurrent={1}\n total={500}\n showSizeChanger\n onSizeChange={(size, cur) => {\n console.log(`size: ${size} current: ${cur}`);\n }}\n />\n <h3>跳转</h3>\n <p>快速跳转到某一页。</p>\n <Pagination showTotal total={100} showQuickJumper />\n <h3>迷你</h3>\n <p>用于弹窗等页面展示区域狭小的场景。</p>\n <h3>受控方式</h3>\n <p><Pagination\n current={current}\n total={50}\n onChange={(c) => {\n this.setState({\n current: c,\n });\n }}\n /></p>\n <Pagination total={100} showQuickJumper showSizeChanger size=\"small\" />\n <h3>非受控方式</h3>\n <Pagination defaultCurrent={1} total={50} />\n </div>\n );\n }\n}\n"}});
//# sourceMappingURL=0.5d174723c0c06b2232a2.js.map |
ajax/libs/flocks.js/1.4.0/flocks.js | kentcdodds/cdnjs |
/** @jsx React.DOM */
/* jshint node: true, browser: true, newcap: false */
/* eslint max-statements: 0, no-else-return: 0, brace-style: 0 */
/* eslint-env node,browser */
/**
* The Flocks library module. Load this module and use either the
* flocks <tt>flocks.createClass</tt> wrapper or the <tt>flocks plumbing</tt>
* mixin to create <tt>flocks controls</tt>. Place them into your document
* using <tt>flocks.mount</tt>, and use the returned function or the data and
* method that the mixin provides, <tt>this.fctx</tt> and <tt>this.fset()</tt>
* respectively, to read and write to the <tt>flocks state</tt>.
*
* And suddenly you're done.
*
* Please see the <a href="http://flocks.rocks/what_is_flocks.html" target="_blank">tutorials</a>
* for more information.
*
* @module flocks
* @main createClass
* @class flocks
*/
// if it's in a <script> it's defined already
// otherwise assume commonjs
/* eslint-disable no-use-before-define, vars-on-top */
if (typeof React === "undefined") {
var React = require("react");
}
/* eslint-enable no-use-before-define, vars-on-top */
// wrap the remainder
(function() {
"use strict";
var Mixin,
exports,
initialized = false,
updateBlocks = 0,
tagtype,
/* eslint-disable no-unused-vars */
dirty = false,
handler = function(Ignored) { return true; },
/* eslint-ensable no-unused-vars */
finalizer = function() { return true; },
prevFCtx = {},
nextFCtx = {},
flocks2Ctxs = { "flocks2context" : React.PropTypes.object };
// ... lol
function arrayMember(Item, Array) {
return (!!(~( Array.indexOf(Item, 0) )));
}
function isArray(maybeArray) {
return (Object.prototype.toString.call(maybeArray) === "[object Array]");
}
function isUndefined(maybeUndefined) {
return (typeof maybeUndefined === "undefined");
}
function isNonArrayObject(maybeArray) {
if (typeof maybeArray !== "object") { return false; }
if (Object.prototype.toString.call(maybeArray) === "[object Array]") { return false; }
return true;
}
function flocksLog(Level, Message) {
if (typeof Level === "string") {
if (arrayMember(Level, ["warn","debug","error","log","info","exception","assert"])) {
console[Level]("Flocks2 [" + Level + "] " + Message.toString());
} else {
console.log("Flocks2 [Unknown level] " + Message.toString());
}
} else if (isUndefined(nextFCtx.flocks2Config)) {
console.log("Flocks2 pre-config [" + Level.toString() + "] " + Message.toString());
} else if (nextFCtx.flocks2Config.log_level >= Level) {
console.log("Flocks2 [" + Level.toString() + "] " + Message.toString());
}
}
function attemptUpdate() {
flocksLog(3, " - Flocks2 attempting update");
dirty = true;
if (!(initialized)) {
flocksLog(1, " x Flocks2 skipped update: root is not initialized");
return null;
}
if (updateBlocks) {
flocksLog(1, " x Flocks2 skipped update: lock count updateBlocks is non-zero");
return null;
}
/* todo see issue #9 https://github.com/StoneCypher/flocks.js/issues/9
if (deepCompare(nextFCtx, prevFCtx)) {
flocksLog(2, " x Flocks2 skipped update: no update to state");
return true;
}
*/
if (!(handler(nextFCtx))) {
flocksLog(0, " ! Flocks2 rolling back update: handler rejected propset");
nextFCtx = prevFCtx;
dirty = false;
return null;
}
prevFCtx = nextFCtx;
flocksLog(3, " - Flocks2 update passed");
if (prevFCtx.flocks2Config.target === 'detatched') {
flocksLog(3, " - Flocks2 skipping render because explicitly detatched");
} else {
flocksLog(3, " - Flocks2 rendering");
React.render( React.createFactory(tagtype)( { "flocks2context" : nextFCtx } ), prevFCtx.flocks2Config.target );
}
dirty = false;
flocksLog(3, " - Flocks2 update complete; finalizing");
finalizer();
return true;
}
function enforceString(On, Label) {
if (typeof On !== "string") {
throw Label || "Argument must be a string";
}
}
function enforceArray(On, Label) {
if (!isArray(On)) {
throw Label || "Argument must be an array";
}
}
function enforceNonArrayObject(On, Label) {
if (!isNonArrayObject(On)) {
throw Label || "Argument must be a non-array object";
}
}
function setByKey(Key, MaybeValue) {
enforceString(Key, "Flocks2 set/2 must take a string for its key");
nextFCtx[Key] = MaybeValue;
flocksLog(1, " - Flocks2 setByKey \"" + Key + "\"");
attemptUpdate();
}
function setTargetByPath(Path, Target, NewVal) {
var NextPath,
OldVal; // it gets hoisted anyway, so it triggers eslint warnings when inlined
// might as well be explicit about it
if (!(isArray(Path))) { throw "Path must be an array!"; }
if (Path.length === 0) {
OldVal = Target;
Target = NewVal;
return OldVal;
}
if (Path.length === 1) {
OldVal = Target[Path[0]];
Target[Path[0]] = NewVal;
return OldVal;
}
if (["string","number"].indexOf(typeof Path[0]) !== -1) {
NextPath = Path.splice(1, Number.MAX_VALUE);
return setTargetByPath(NextPath, Target[Path[0]], NewVal);
}
}
function setByPath(Path, NewVal) {
enforceArray(Path, "Flocks2 setByPathh/2 must take an array for its key");
flocksLog(1, " - Flocks2 setByPath \"" + Path.join("|") + "\"");
setTargetByPath(Path, nextFCtx, NewVal);
attemptUpdate();
}
// todo
// function setByObject(Key, MaybeValue) {
// flocksLog(0, " - Flocks2 setByObject stub");
// attemptUpdate();
// }
function set(Key, MaybeValue) {
flocksLog(3, " - Flocks2 multi-set");
if (typeof Key === "string") { return setByKey(Key, MaybeValue); }
else if (isArray(Key)) { return setByPath(Key, MaybeValue); }
// else if (isNonArrayObject(Key)) { return setByObject(Key); } // todo
else { throw "Flocks2 set/1,2 key must be a string or an array"; }
}
function get(Key) {
flocksLog(3, " - Flocks2 multi-get");
if (typeof Key === "string") { return getByKey(Key); }
else if (isArray(Key)) { return getByPath(Key); }
else { throw "Flocks2 get/1 key must be a string or an array"; }
}
function getByKey(Key) {
return prevFCtx[Key];
}
function getByPathImpl(Path, Target) {
var NextPath;
if (!(isArray(Path))) { throw "path must be an array!"; }
if (Path.length === 0) {
return Target;
}
if (Path.length === 1) {
return Target[Path[0]];
}
if (["string","number"].indexOf(typeof Path[0]) !== -1) {
NextPath = Path.splice(1, Number.MAX_VALUE);
return getByPathImpl(NextPath, Target[Path[0]]);
}
}
function getByPath(Path) {
return getByPathImpl(Path, prevFCtx);
}
function update(SparseObject) {
// todo
console.log("ERROR: stub called!");
enforceNonArrayObject(SparseObject, "Flocks2 update/1 must take a plain object");
}
function lock() {
++updateBlocks;
}
function unlock() {
if (updateBlocks <= 0) { throw "unlock()ed with no lock!"; }
--updateBlocks;
attemptUpdate();
}
function clone(obj) {
var copy = obj.constructor(),
attr;
if ((obj === null) || (typeof obj !== "object")) { return obj; }
for (attr in obj) {
if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; }
}
return copy;
}
function create(iFlocksConfig, iFlocksData) {
var FlocksConfig = iFlocksConfig || {},
FlocksData = iFlocksData || {},
target = FlocksConfig.target || document.body,
stub = function() { console.log("ERROR: stub called!"); attemptUpdate(); }, // todo
updater = {
"override" : stub, // todo
"clear" : stub, // todo
"get" : get,
"get_key" : getByKey,
"get_path" : getByPath,
"set" : set,
"set_path" : setByPath,
"update" : update,
"lock" : lock,
"unlock" : unlock
};
FlocksConfig.log_level = FlocksConfig.log_level || -1;
tagtype = FlocksConfig.control;
FlocksData.flocks2Config = FlocksConfig;
nextFCtx = FlocksData;
flocksLog(1, "Flocks2 root creation begins");
if (!(tagtype)) {
throw "Flocks2 fatal error: must provide a control in create/2 FlocksConfig";
}
if (FlocksConfig.handler) {
handler = FlocksConfig.handler;
flocksLog(3, " - Flocks2 handler assigned");
}
if (FlocksConfig.finalizer) {
finalizer = FlocksConfig.finalizer;
flocksLog(3, " - Flocks2 finalizer assigned");
}
if (FlocksConfig.preventAutoContext) {
flocksLog(2, " - Flocks2 skipping auto-context");
} else {
flocksLog(2, " - Flocks2 engaging auto-context");
this.fctx = clone(nextFCtx);
}
flocksLog(3, "Flocks2 creation finished; initializing");
initialized = true;
attemptUpdate();
flocksLog(3, "Flocks2 expose updater");
this.fupd = updater;
this.fset = updater.set;
this.fgetkey = updater.get_key;
this.fgetpath = updater.get_path;
this.flock = updater.lock;
this.funlock = updater.unlock;
this.fupdate = updater.update;
flocksLog(3, "Flocks2 initialization finished");
return updater;
}
// because of YUIdoc limitations, the extracted docs for the mixin are far
// below. search for the word "yuibama" to jump between these places.
Mixin = {
"contextTypes" : flocks2Ctxs,
"childContextTypes" : flocks2Ctxs,
"componentWillMount" : function() {
flocksLog(1, " - Flocks2 component will mount: " + this.constructor.displayName);
flocksLog(3, isUndefined(this.props.flocks2context)?
" - No F2 Context Prop"
: " - F2 Context Prop found");
flocksLog(3, isUndefined(this.context.flocks2context)?
" - No F2 Context"
: " - F2 Context found");
if (this.props.flocks2context) {
this.context.flocks2context = this.props.flocks2context;
}
this.fupdate = function(Obj) { return update(Obj); };
this.fget = function(K) { return get(K); };
this.fgetkey = function(K) { return getByKey(K); };
this.fgetpath = function(P) { return getByPath(P); };
this.fset = function(K,V) { return set(K,V); };
this.fsetpath = function(P,V) { return set(P,V); };
this.flock = function() { return lock(); };
this.funlock = function() { return unlock(); };
this.fctx = this.context.flocks2context;
},
"getChildContext" : function() {
return this.context;
}
};
function atLeastFlocks(OriginalList) {
var NewList;
if (isUndefined(OriginalList)) {
return [ Mixin ];
}
if (isArray(OriginalList)) {
if (arrayMember(Mixin, OriginalList)) {
return OriginalList;
} else {
NewList = clone(OriginalList);
NewList.push(Mixin);
return NewList;
}
}
throw "Original mixin list must be an array or undefined!";
}
function createClass(spec) {
spec.mixins = atLeastFlocks(spec.mixins);
return React.createClass(spec);
}
exports = {
/**
* <tt>version</tt> is an exposed string on the <tt>module export</tt>
* which mentions the current library version. This number should
* always be in sync with the <tt>package.json</tt> and <tt>bower.json</tt>
* version, the <tt>github tag</tt>, the <tt>npm version</tt>, and will
* define the paths available on <tt>cdnjs</tt>
*
* @property version
* @type {String}
*/
"version" : "1.4.0",
/**
* <tt>createClass</tt> is a wrapper for <tt>react.createClass</tt> which
* automatically adds the <tt>plumbing</tt> mixin to your control's spec,
* to keep visual noise down. If you prefer, you can add the <tt>plumbing</tt>
* mixin manually, in the standard fashion, instead; that may be more
* convenient in situations where many mixins are in use, or where other
* wrappers of <tt>createClass</tt> are in use.
*
* @method createClass
*/
"createClass" : createClass,
/**
* <tt>mount</tt> accepts a <tt>flocks config</tt> and an initial state,
* and then manages a root control for you. <tt>mount</tt> returns to
* you a function which you can use from outside the control tree to
* update the <tt>flocks state</tt>. From inside the control tree, a
* control decorated with the <tt>flocks plumbing</tt> has a member
* <tt>this.fctx</tt> which contains an up to date copy of the <tt>flocks
* state</tt>, and another member <tt>this.fset()</tt> which you can
* use to update the <tt>flocks state</tt>.
*
* To <tt>mount</tt> a control is to start the process by placing your
* top level control into the document through <tt>flocks</tt>.
*
* @method mount
*/
"mount" : create,
/**
* <tt>clone</tt> recursively deep-copies its argument.
*
* @method clone
*/
"clone" : clone,
/**
* <tt>isArray</tt> produces a boolean regarding whether its argument
* is a javascript <tt>Array</tt>.
*
* @method isArray
*/
"isArray" : isArray,
/**
* <tt>isUndefined</tt> produces a boolean regarding whether its argument
* is the javascript value <tt>undefined</tt>.
*
* @method isUndefined
*/
"isUndefined" : isUndefined,
/**
* <tt>isNonArrayObject</tt> produces a boolean regarding whether its
* argument is a javascript <tt>Object</tt>, but also goes to the effort
* to exclude javascript <tt>Array</tt>s.
*
* @method isNonArrayObject
*/
"isNonArrayObject" : isNonArrayObject,
/**
* <tt>enforceString</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is not of
* type <tt>string</tt>. The throw will be the explanation argument, or
* a default if the explanation is not present.
*
* @method enforceString
*/
"enforceString" : enforceString,
/**
* <tt>enforceArray</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is not of
* type <tt>Array</tt>. The throw will be the explanation argument, or
* a default if the explanation is not present.
*
* @method enforceArray
*/
"enforceArray" : enforceArray,
/**
* <tt>enforceNonArrayObject</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is of
* type <tt>Array</tt>, or not of type <tt>Object</tt>. The throw will be
* the explanation argument, or a default if the explanation is not present.
*
* @method enforceNonArrayObject
*/
"enforceNonArrayObject" : enforceNonArrayObject,
/**
* <tt>atLeastFlocks</tt> accepts a mixin set from a control spec, or
* the value <tt>undefined</tt>, and produces a mixin set in response,
* which contains the old mixin set if any, pre-pended with
* the <tt>flocks plumbing</tt> mixin, or a mixin set with just that
* mixin if the previous mixin set was empty or <tt>undefined</tt>.
* If the mixin set provided already contains flocks, it will be
* returned unaltered, in case the prior mixin set is order sensitive.
*
* This is not a method that the end user should expect to use.
*
* @method atLeastFlocks
*/
"atLeastFlocks" : atLeastFlocks,
/**
* <tt>plumbing</tt> is the <tt>flocks</tt> mixin which handles all of
* the behind-the-scenes work to make <tt>flocks</tt> function. The
* mixin is automatically added by calling <tt>flocks.createClass</tt>,
* or you can add it yourself in the standard mixin fashion if you prefer.
*
* @class plumbing
*/
// grossest doc structure ever. thanks yuibama.
/**
* Describes the context types accepted or required by any given React
* component; mixin hook notes the need for <tt>flocks2context : object</tt>
* as an incoming context to pay attention to.
*
* @property contextTypes
*/
/**
* Describes the context types provided by the React component; mixin
* hook notes that this provides <tt>flocks2context : object</tt> to
* subordinate controls.
*
* @property childContextTypes
*/
/**
* Called when the control is about to mount; mixin hooks this event to
* add the flocks context <tt>this.fctx</tt>, the flocks updater
* <tt>this.fset</tt>, and other flocks methods to the control object.
*
* @event componentWillMount
*/
/**
* Called when the control is about to pass context to children; the
* plumbing mixin hooks this event to do the simple job of passing the
* flocks context data downwards.
*
* @event getChildContext
*/
"plumbing" : Mixin
};
if (typeof module !== "undefined") {
module.exports = exports;
} else {
window.flocks = exports;
}
}());
|
packages/wix-style-react/src/Tabs/test/Tabs.visual.js | wix/wix-style-react | import React from 'react';
import { storiesOf } from '@storybook/react';
import Box from '../../Box';
import Tabs from '../Tabs';
const defaultProps = {
items: [1, 2, 3, 4, 5].map(index => ({
id: String(index),
title: `item ${index}`,
})),
activeId: '2',
};
const tests = [
{
describe: '',
its: [
{
it: 'selected',
props: {},
},
{
it: 'unselected',
props: { activeId: '' },
},
{
it: 'without a divider',
props: { hasDivider: false },
},
{
it: 'with side content',
props: { sideContent: <div>Side content!</div> },
},
{
it: 'with long names',
props: {
items: [1, 2, 3, 4, 5].map(index => ({
id: String(index),
title: `This is item number ${index}`,
})),
},
},
{
it: 'with 800px min container width',
props: { minWidth: '800px' },
},
],
},
];
tests.forEach(({ describe, its }) => {
its.forEach(({ it, props }) => {
storiesOf(`Tabs${describe ? '/' + describe : ''}`, module).add(it, () => (
<Box direction="vertical" maxWidth="800px">
<Box margin={2}>
<Tabs {...defaultProps} {...props} />
</Box>
<Box margin={2}>
<Tabs type="compact" {...defaultProps} {...props} />
</Box>
<Box margin={2}>
<Tabs type="compactSide" {...defaultProps} {...props} />
</Box>
<Box margin={2}>
<Tabs type="uniformSide" {...defaultProps} {...props} />
</Box>
<Box margin={2}>
<Tabs type="uniformFull" {...defaultProps} {...props} />
</Box>
</Box>
));
});
});
storiesOf('Tabs', module).add('with tab width (Uniform Side)', () => (
<Box direction="vertical">
<Box margin={2}>
<Tabs type="uniformSide" {...defaultProps} width="50px" />
</Box>
<Box margin={2}>
<Tabs type="uniformSide" {...defaultProps} width="100px" />
</Box>
<Box margin={2}>
<Tabs type="uniformSide" {...defaultProps} width="150px" />
</Box>
<Box margin={2}>
<Tabs type="uniformSide" {...defaultProps} width="200px" />
</Box>
</Box>
));
storiesOf('Tabs', module).add('with tab size (small)', () => (
<Box direction="vertical">
<Box margin={2}>
<Tabs size="small" {...defaultProps} />
</Box>
<Box margin={2}>
<Tabs size="small" {...defaultProps} type="compact" />
</Box>
<Box margin={2}>
<Tabs size="small" {...defaultProps} type="compactSide" />
</Box>
<Box margin={2}>
<Tabs size="small" {...defaultProps} type="uniformSide" />
</Box>
<Box margin={2}>
<Tabs size="small" {...defaultProps} type="uniformFull" />
</Box>
</Box>
));
|
ajax/libs/survey-react/0.12.11/survey.react.min.js | cdnjs/cdnjs | /*!
* surveyjs - Survey JavaScript library v0.12.11
* Copyright (c) 2015-2017 Devsoft Baltic OÜ - http://surveyjs.org/
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define("Survey",["react"],t):"object"==typeof exports?exports.Survey=t(require("react")):e.Survey=t(e.React)}(this,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=80)}([function(e,t,n){"use strict";function r(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}n.d(t,"a",function(){return i}),t.b=r,n.d(t,"c",function(){return o});var i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},o=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}},function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return i});var r={currentLocale:"",locales:{},getString:function(e){var t=this.currentLocale?this.locales[this.currentLocale]:i;return t&&t[e]||(t=i),t[e]},getLocales:function(){var e=[];e.push("");for(var t in this.locales)e.push(t);return e.sort(),e}},i={pagePrevText:"Previous",pageNextText:"Next",completeText:"Complete",otherItemText:"Other (describe)",progressText:"Page {0} of {1}",emptySurvey:"There is no visible page or question in the survey.",completingSurvey:"Thank you for completing the survey!",loadingSurvey:"Survey is loading...",optionsCaption:"Choose...",requiredError:"Please answer the question.",requiredInAllRowsError:"Please answer questions in all rows.",numericError:"The value should be numeric.",textMinLength:"Please enter at least {0} symbols.",textMaxLength:"Please enter less than {0} symbols.",textMinMaxLength:"Please enter more than {0} and less than {1} symbols.",minRowCountError:"Please fill in at least {0} rows.",minSelectError:"Please select at least {0} variants.",maxSelectError:"Please select no more than {0} variants.",numericMinMax:"The '{0}' should be equal or more than {1} and equal or less than {2}",numericMin:"The '{0}' should be equal or more than {1}",numericMax:"The '{0}' should be equal or less than {1}",invalidEmail:"Please enter a valid e-mail address.",urlRequestError:"The request returned error '{0}'. {1}",urlGetChoicesError:"The request returned empty data or the 'path' property is incorrect",exceedMaxSize:"The file size should not exceed {0}.",otherRequiredError:"Please enter the other value.",uploadingFile:"Your file is uploading. Please wait several seconds and try again.",addRow:"Add row",removeRow:"Remove",choices_firstItem:"first item",choices_secondItem:"second item",choices_thirdItem:"third item",matrix_column:"Column",matrix_row:"Row"};r.locales.en=i,String.prototype.format||(String.prototype.format=function(){var e=arguments;return this.replace(/{(\d+)}/g,function(t,n){return void 0!==e[n]?e[n]:t})})},function(e,t,n){"use strict";var r=n(0);n.d(t,"h",function(){return i}),n.d(t,"e",function(){return o}),n.d(t,"d",function(){return s}),n.d(t,"b",function(){return a}),n.d(t,"j",function(){return u}),n.d(t,"g",function(){return l}),n.d(t,"f",function(){return c}),n.d(t,"c",function(){return h}),n.d(t,"i",function(){return p}),n.d(t,"a",function(){return d});var i=function(){function e(e){this.name=e,this.typeValue=null,this.choicesValue=null,this.choicesfunc=null,this.className=null,this.alternativeName=null,this.classNamePart=null,this.baseClassName=null,this.defaultValue=null,this.readOnly=!1,this.visible=!0,this.isLocalizable=!1,this.serializationProperty=null,this.onGetValue=null}return Object.defineProperty(e.prototype,"type",{get:function(){return this.typeValue?this.typeValue:"string"},set:function(e){this.typeValue=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasToUseGetValue",{get:function(){return this.onGetValue||this.serializationProperty},enumerable:!0,configurable:!0}),e.prototype.isDefaultValue=function(e){return this.defaultValue?this.defaultValue==e:!e},e.prototype.getValue=function(e){return this.onGetValue?this.onGetValue(e):this.serializationProperty?e[this.serializationProperty].getJson():e[this.name]},e.prototype.getPropertyValue=function(e){return this.isLocalizable?e[this.serializationProperty].text:this.getValue(e)},Object.defineProperty(e.prototype,"hasToUseSetValue",{get:function(){return this.onSetValue||this.serializationProperty},enumerable:!0,configurable:!0}),e.prototype.setValue=function(e,t,n){this.onSetValue?this.onSetValue(e,t,n):this.serializationProperty?e[this.serializationProperty].setJson(t):e[this.name]=t},e.prototype.getObjType=function(e){return this.classNamePart?e.replace(this.classNamePart,""):e},e.prototype.getClassName=function(e){return this.classNamePart&&e.indexOf(this.classNamePart)<0?e+this.classNamePart:e},Object.defineProperty(e.prototype,"choices",{get:function(){return null!=this.choicesValue?this.choicesValue:null!=this.choicesfunc?this.choicesfunc():null},enumerable:!0,configurable:!0}),e.prototype.setChoices=function(e,t){this.choicesValue=e,this.choicesfunc=t},e}(),o=function(){function e(e,t,n,r){void 0===n&&(n=null),void 0===r&&(r=null),this.name=e,this.creator=n,this.parentName=r,this.properties=null,this.requiredProperties=null,this.properties=new Array;for(var i=0;i<t.length;i++){var o=this.createProperty(t[i]);o&&this.properties.push(o)}}return e.prototype.find=function(e){for(var t=0;t<this.properties.length;t++)if(this.properties[t].name==e)return this.properties[t];return null},e.prototype.createProperty=function(t){var n="string"==typeof t?t:t.name;if(n){var r=null,o=n.indexOf(e.typeSymbol);o>-1&&(r=n.substring(o+1),n=n.substring(0,o)),n=this.getPropertyName(n);var s=new i(n);if(r&&(s.type=r),"object"==typeof t){if(t.type&&(s.type=t.type),t.default&&(s.defaultValue=t.default),!1===t.visible&&(s.visible=!1),t.isRequired&&this.makePropertyRequired(s.name),t.choices){var a="function"==typeof t.choices?t.choices:null,u="function"!=typeof t.choices?t.choices:null;s.setChoices(u,a)}if(t.onGetValue&&(s.onGetValue=t.onGetValue),t.onSetValue&&(s.onSetValue=t.onSetValue),t.serializationProperty){s.serializationProperty=t.serializationProperty;s.serializationProperty&&0==s.serializationProperty.indexOf("loc")&&(s.isLocalizable=!0)}t.isLocalizable&&(s.isLocalizable=t.isLocalizable),t.className&&(s.className=t.className),t.baseClassName&&(s.baseClassName=t.baseClassName),t.classNamePart&&(s.classNamePart=t.classNamePart),t.alternativeName&&(s.alternativeName=t.alternativeName)}return s}},e.prototype.getPropertyName=function(t){return 0==t.length||t[0]!=e.requiredSymbol?t:(t=t.slice(1),this.makePropertyRequired(t),t)},e.prototype.makePropertyRequired=function(e){this.requiredProperties||(this.requiredProperties=new Array),this.requiredProperties.push(e)},e}();o.requiredSymbol="!",o.typeSymbol=":";var s=function(){function e(){this.classes={},this.childrenClasses={},this.classProperties={},this.classRequiredProperties={}}return e.prototype.addClass=function(e,t,n,r){void 0===n&&(n=null),void 0===r&&(r=null);var i=new o(e,t,n,r);if(this.classes[e]=i,r){this.childrenClasses[r]||(this.childrenClasses[r]=[]),this.childrenClasses[r].push(i)}return i},e.prototype.overrideClassCreatore=function(e,t){var n=this.findClass(e);n&&(n.creator=t)},e.prototype.getProperties=function(e){var t=this.classProperties[e];return t||(t=new Array,this.fillProperties(e,t),this.classProperties[e]=t),t},e.prototype.findProperty=function(e,t){for(var n=this.getProperties(e),r=0;r<n.length;r++)if(n[r].name==t)return n[r];return null},e.prototype.createClass=function(e){var t=this.findClass(e);return t?t.creator():null},e.prototype.getChildrenClasses=function(e,t){void 0===t&&(t=!1);var n=[];return this.fillChildrenClasses(e,t,n),n},e.prototype.getRequiredProperties=function(e){var t=this.classRequiredProperties[e];return t||(t=new Array,this.fillRequiredProperties(e,t),this.classRequiredProperties[e]=t),t},e.prototype.addProperty=function(e,t){var n=this.findClass(e);if(n){var r=n.createProperty(t);r&&(this.addPropertyToClass(n,r),this.emptyClassPropertiesHash(n))}},e.prototype.removeProperty=function(e,t){var n=this.findClass(e);if(!n)return!1;var r=n.find(t);r&&(this.removePropertyFromClass(n,r),this.emptyClassPropertiesHash(n))},e.prototype.addPropertyToClass=function(e,t){null==e.find(t.name)&&e.properties.push(t)},e.prototype.removePropertyFromClass=function(e,t){var n=e.properties.indexOf(t);n<0||(e.properties.splice(n,1),e.requiredProperties&&(n=e.requiredProperties.indexOf(t.name))>=0&&e.requiredProperties.splice(n,1))},e.prototype.emptyClassPropertiesHash=function(e){this.classProperties[e.name]=null;for(var t=this.getChildrenClasses(e.name),n=0;n<t.length;n++)this.classProperties[t[n].name]=null},e.prototype.fillChildrenClasses=function(e,t,n){var r=this.childrenClasses[e];if(r)for(var i=0;i<r.length;i++)t&&!r[i].creator||n.push(r[i]),this.fillChildrenClasses(r[i].name,t,n)},e.prototype.findClass=function(e){return this.classes[e]},e.prototype.fillProperties=function(e,t){var n=this.findClass(e);if(n){n.parentName&&this.fillProperties(n.parentName,t);for(var r=0;r<n.properties.length;r++)this.addPropertyCore(n.properties[r],t,t.length)}},e.prototype.addPropertyCore=function(e,t,n){for(var r=-1,i=0;i<n;i++)if(t[i].name==e.name){r=i;break}r<0?t.push(e):t[r]=e},e.prototype.fillRequiredProperties=function(e,t){var n=this.findClass(e);n&&(n.requiredProperties&&Array.prototype.push.apply(t,n.requiredProperties),n.parentName&&this.fillRequiredProperties(n.parentName,t))},e}(),a=function(){function e(e,t){this.type=e,this.message=t,this.description="",this.at=-1}return e.prototype.getFullDescription=function(){return this.message+(this.description?"\n"+this.description:"")},e}(),u=function(e){function t(t,n){var r=e.call(this,"unknownproperty","The property '"+t+"' in class '"+n+"' is unknown.")||this;r.propertyName=t,r.className=n;var i=d.metaData.getProperties(n);if(i){r.description="The list of available properties are: ";for(var o=0;o<i.length;o++)o>0&&(r.description+=", "),r.description+=i[o].name;r.description+="."}return r}return r.b(t,e),t}(a),l=function(e){function t(t,n,r){var i=e.call(this,n,r)||this;i.baseClassName=t,i.type=n,i.message=r,i.description="The following types are available: ";for(var o=d.metaData.getChildrenClasses(t,!0),s=0;s<o.length;s++)s>0&&(i.description+=", "),i.description+="'"+o[s].name+"'";return i.description+=".",i}return r.b(t,e),t}(a),c=function(e){function t(t,n){var r=e.call(this,n,"missingtypeproperty","The property type is missing in the object. Please take a look at property: '"+t+"'.")||this;return r.propertyName=t,r.baseClassName=n,r}return r.b(t,e),t}(l),h=function(e){function t(t,n){var r=e.call(this,n,"incorrecttypeproperty","The property type is incorrect in the object. Please take a look at property: '"+t+"'.")||this;return r.propertyName=t,r.baseClassName=n,r}return r.b(t,e),t}(l),p=function(e){function t(t,n){var r=e.call(this,"requiredproperty","The property '"+t+"' is required in class '"+n+"'.")||this;return r.propertyName=t,r.className=n,r}return r.b(t,e),t}(a),d=function(){function e(){this.errors=new Array}return Object.defineProperty(e,"metaData",{get:function(){return e.metaDataValue},enumerable:!0,configurable:!0}),e.prototype.toJsonObject=function(e){return this.toJsonObjectCore(e,null)},e.prototype.toObject=function(t,n){if(t){var r=null;if(n.getType&&(r=e.metaData.getProperties(n.getType())),r)for(var i in t)if(i!=e.typePropertyName)if(i!=e.positionPropertyName){var o=this.findProperty(r,i);o?this.valueToObj(t[i],n,i,o):this.addNewError(new u(i.toString(),n.getType()),t)}else n[i]=t[i]}},e.prototype.toJsonObjectCore=function(t,n){if(!t.getType)return t;var r={};null==n||n.className||(r[e.typePropertyName]=n.getObjType(t.getType()));for(var i=e.metaData.getProperties(t.getType()),o=0;o<i.length;o++)this.valueToJson(t,r,i[o]);return r},e.prototype.valueToJson=function(e,t,n){var r=n.getValue(e);if(void 0!==r&&null!==r&&!n.isDefaultValue(r)){if(this.isValueArray(r)){for(var i=[],o=0;o<r.length;o++)i.push(this.toJsonObjectCore(r[o],n));r=i.length>0?i:null}else r=this.toJsonObjectCore(r,n);n.isDefaultValue(r)||(t[n.name]=r)}},e.prototype.valueToObj=function(e,t,n,r){if(null!=e){if(null!=r&&r.hasToUseSetValue)return void r.setValue(t,e,this);if(this.isValueArray(e))return void this.valueToArray(e,t,r.name,r);var i=this.createNewObj(e,r);i.newObj&&(this.toObject(e,i.newObj),e=i.newObj),i.error||(t[r.name]=e)}},e.prototype.isValueArray=function(e){return e&&Array.isArray(e)},e.prototype.createNewObj=function(t,n){var r={newObj:null,error:null},i=t[e.typePropertyName];return!i&&null!=n&&n.className&&(i=n.className),i=n.getClassName(i),r.newObj=i?e.metaData.createClass(i):null,r.error=this.checkNewObjectOnErrors(r.newObj,t,n,i),r},e.prototype.checkNewObjectOnErrors=function(t,n,r,i){var o=null;if(t){var s=e.metaData.getRequiredProperties(i);if(s)for(var a=0;a<s.length;a++)if(!n[s[a]]){o=new p(s[a],i);break}}else r.baseClassName&&(o=i?new h(r.name,r.baseClassName):new c(r.name,r.baseClassName));return o&&this.addNewError(o,n),o},e.prototype.addNewError=function(t,n){n&&n[e.positionPropertyName]&&(t.at=n[e.positionPropertyName].start),this.errors.push(t)},e.prototype.valueToArray=function(e,t,n,r){t[n]&&e.length>0&&t[n].splice(0,t[n].length);for(var i=0;i<e.length;i++){var o=this.createNewObj(e[i],r);o.newObj?(t[n].push(o.newObj),this.toObject(e[i],o.newObj)):o.error||t[n].push(e[i])}},e.prototype.findProperty=function(e,t){if(!e)return null;for(var n=0;n<e.length;n++){var r=e[n];if(r.name==t||r.alternativeName==t)return r}return null},e}();d.typePropertyName="type",d.positionPropertyName="pos",d.metaDataValue=new s},function(t,n){t.exports=e},function(e,t,n){"use strict";var r=n(0),i=n(3);n.n(i);n.d(t,"a",function(){return o}),n.d(t,"b",function(){return s});var o=function(e){function t(t){var n=e.call(this,t)||this;return n.css=t.css,n.rootCss=t.rootCss,n.isDisplayMode=t.isDisplayMode||!1,n}return r.b(t,e),t.renderLocString=function(e,t){if(void 0===t&&(t=null),e.hasHtml){var n={__html:e.renderedHtml};return i.createElement("span",{style:t,dangerouslySetInnerHTML:n})}return i.createElement("span",{style:t},e.renderedHtml)},t.prototype.componentWillReceiveProps=function(e){this.css=e.css,this.rootCss=e.rootCss,this.isDisplayMode=e.isDisplayMode||!1},t.prototype.renderLocString=function(e,n){return void 0===n&&(n=null),t.renderLocString(e,n)},t}(i.Component),s=function(e){function t(t){var n=e.call(this,t)||this;return n.questionBase=t.question,n.creator=t.creator,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.questionBase=t.question,this.creator=t.creator},t.prototype.shouldComponentUpdate=function(){return!this.questionBase.customWidget||!!this.questionBase.customWidget.widgetJson.isNeedRender||!!this.questionBase.customWidget.widgetJson.render},t}(o)},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){this.creatorHash={}}return e.prototype.registerQuestion=function(e,t){this.creatorHash[e]=t},e.prototype.getAllTypes=function(){var e=new Array;for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createQuestion=function(e,t){var n=this.creatorHash[e];return null==n?null:n(t)},e}();r.Instance=new r},function(e,t,n){"use strict";n.d(t,"b",function(){return i}),n.d(t,"d",function(){return o}),n.d(t,"e",function(){return r}),n.d(t,"a",function(){return s}),n.d(t,"c",function(){return a});var r,i=function(){function e(){}return e.isValueEmpty=function(e){return!e&&0!==e&&!1!==e},e.prototype.getType=function(){throw new Error("This method is abstract")},e.prototype.isTwoValueEquals=function(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;for(var n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!this.isTwoValueEquals(e[n],t[n]))return!1}}for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0},e}(),o=function(){function e(){}return e.prototype.getText=function(){throw new Error("This method is abstract")},e}();r="sq_page";var s=function(){function e(){}return e.ScrollElementToTop=function(e){if(!e)return!1;var t=document.getElementById(e);if(!t||!t.scrollIntoView)return!1;var n=t.getBoundingClientRect().top;return n<0&&t.scrollIntoView(),n<0},e.GetFirstNonTextElement=function(e){if(e&&e.length){for(var t=0;t<e.length;t++)if("#text"!=e[t].nodeName&&"#comment"!=e[t].nodeName)return e[t];return null}},e.FocusElement=function(e){if(!e)return!1;var t=document.getElementById(e);return!!t&&(t.focus(),!0)},e}(),a=function(){function e(){}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return null==this.callbacks||0==this.callbacks.length},enumerable:!0,configurable:!0}),e.prototype.fire=function(e,t){if(null!=this.callbacks)for(var n=0;n<this.callbacks.length;n++){this.callbacks[n](e,t)}},e.prototype.add=function(e){null==this.callbacks&&(this.callbacks=new Array),this.callbacks.push(e)},e.prototype.remove=function(e){if(null!=this.callbacks){var t=this.callbacks.indexOf(e,0);void 0!=t&&this.callbacks.splice(t,1)}},e}()},function(e,t,n){"use strict";var r=n(1);n.d(t,"a",function(){return i}),n.d(t,"b",function(){return o});var i=function(){function e(){this.creatorHash={}}return Object.defineProperty(e,"DefaultChoices",{get:function(){return["1|"+r.a.getString("choices_firstItem"),"2|"+r.a.getString("choices_secondItem"),"3|"+r.a.getString("choices_thirdItem")]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultColums",{get:function(){var e=r.a.getString("matrix_column")+" ";return[e+"1",e+"2",e+"3"]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultRows",{get:function(){var e=r.a.getString("matrix_row")+" ";return[e+"1",e+"2"]},enumerable:!0,configurable:!0}),e.prototype.registerQuestion=function(e,t){this.creatorHash[e]=t},e.prototype.clear=function(){this.creatorHash={}},e.prototype.getAllTypes=function(){var e=new Array;for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createQuestion=function(e,t){var n=this.creatorHash[e];return null==n?null:n(t)},e}();i.Instance=new i;var o=function(){function e(){this.creatorHash={}}return e.prototype.registerElement=function(e,t){this.creatorHash[e]=t},e.prototype.clear=function(){this.creatorHash={}},e.prototype.getAllTypes=function(){var e=i.Instance.getAllTypes();for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createElement=function(e,t){var n=this.creatorHash[e];return null==n?i.Instance.createQuestion(e,t):n(t)},e}();o.Instance=new o},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(e,t){void 0===t&&(t=!1),this.owner=e,this.useMarkdown=t,this.values={},this.htmlValues={},this.onCreating()}return Object.defineProperty(e.prototype,"locale",{get:function(){return this.owner?this.owner.getLocale():""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){var t=Object.keys(this.values);if(0==t.length)return"";var n=this.locale;n||(n=e.defaultLocale);var r=this.values[n];return r||n===e.defaultLocale||(r=this.values[e.defaultLocale]),r||this.values[t[0]]},set:function(e){this.setLocaleText(this.locale,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasHtml",{get:function(){return this.hasHtmlValue()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"html",{get:function(){return this.hasHtml?this.getHtmlValue():""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textOrHtml",{get:function(){return this.hasHtml?this.getHtmlValue():this.text},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderedHtml",{get:function(){var e=this.textOrHtml;return this.onRenderedHtmlCallback?this.onRenderedHtmlCallback(e):e},enumerable:!0,configurable:!0}),e.prototype.getLocaleText=function(t){t||(t=e.defaultLocale);var n=this.values[t];return n||""},e.prototype.setLocaleText=function(t,n){n!=this.getLocaleText(t)&&(t||(t=e.defaultLocale),delete this.htmlValues[t],n?"string"==typeof n&&(t!=e.defaultLocale&&n==this.getLocaleText(e.defaultLocale)?this.setLocaleText(t,null):(this.values[t]=n,t==e.defaultLocale&&this.deleteValuesEqualsToDefault(n))):this.values[t]&&delete this.values[t],this.onChanged())},e.prototype.getJson=function(){var t=Object.keys(this.values);return 0==t.length?null:1==t.length&&t[0]==e.defaultLocale?this.values[t[0]]:this.values},e.prototype.setJson=function(e){if(this.values={},this.htmlValues={},e){if("string"==typeof e)this.setLocaleText(null,e);else for(var t in e)this.setLocaleText(t,e[t]);this.onChanged()}},e.prototype.onChanged=function(){},e.prototype.onCreating=function(){},e.prototype.hasHtmlValue=function(){if(!this.owner||!this.useMarkdown)return!1;var t=this.text;if(!t)return!1;var n=this.locale;return n||(n=e.defaultLocale),n in this.htmlValues||(this.htmlValues[n]=this.owner.getMarkdownHtml(t)),!!this.htmlValues[n]},e.prototype.getHtmlValue=function(){var t=this.locale;return t||(t=e.defaultLocale),this.htmlValues[t]},e.prototype.deleteValuesEqualsToDefault=function(t){for(var n=Object.keys(this.values),r=0;r<n.length;r++)n[r]!=e.defaultLocale&&this.values[n[r]]==t&&delete this.values[n[r]]},e}();r.defaultLocale="default"},function(e,t,n){"use strict";var r=n(0),i=n(1),o=n(6);n.d(t,"a",function(){return s}),n.d(t,"b",function(){return a}),n.d(t,"d",function(){return u}),n.d(t,"c",function(){return l});var s=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("requiredError")},t}(o.d),a=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("numericError")},t}(o.d),u=function(e){function t(t){var n=e.call(this)||this;return n.maxSize=t,n}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("exceedMaxSize").format(this.getTextSize())},t.prototype.getTextSize=function(){var e=["Bytes","KB","MB","GB","TB"],t=[0,0,2,3,3];if(0==this.maxSize)return"0 Byte";var n=Math.floor(Math.log(this.maxSize)/Math.log(1024));return(this.maxSize/Math.pow(1024,n)).toFixed(t[n])+" "+e[n]},t}(o.d),l=function(e){function t(t){var n=e.call(this)||this;return n.text=t,n}return r.b(t,e),t.prototype.getText=function(){return this.text},t}(o.d)},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(22),s=n(6),a=n(1),u=n(9),l=n(25),c=n(24),h=n(8);n.d(t,"a",function(){return p});var p=function(e){function t(t){var n=e.call(this,t)||this;n.name=t,n.isRequiredValue=!1,n.hasCommentValue=!1,n.hasOtherValue=!1,n.readOnlyValue=!1,n.errors=[],n.validators=new Array,n.isvalueChangedCallbackFiring=!1,n.isValueChangedInSurvey=!1,n.locTitleValue=new h.a(n,!0);var r=n;return n.locTitleValue.onRenderedHtmlCallback=function(e){return r.fullTitle},n.locCommentTextValue=new h.a(n,!0),n}return r.b(t,e),Object.defineProperty(t.prototype,"hasTitle",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInput",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputId",{get:function(){return this.id+"i"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){var e=this.locTitle.text;return e||this.name},set:function(e){this.locTitle.text=e,this.fireCallback(this.titleChangedCallback)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCommentText",{get:function(){return this.locCommentTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitleHtml",{get:function(){var e=this.locTitle.textOrHtml;return e||this.name},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locTitle.onChanged(),this.locCommentText.onChanged()},Object.defineProperty(t.prototype,"processedTitle",{get:function(){return null!=this.survey?this.survey.processText(this.locTitleHtml):this.locTitleHtml},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){if(this.survey&&this.survey.getQuestionTitleTemplate()){if(!this.textPreProcessor){var e=this;this.textPreProcessor=new c.a,this.textPreProcessor.onHasValue=function(t){return e.canProcessedTextValues(t.toLowerCase())},this.textPreProcessor.onProcess=function(t){return e.getProcessedTextValue(t)}}return this.textPreProcessor.process(this.survey.getQuestionTitleTemplate())}var t=this.requiredText;t&&(t+=" ");var n=this.no;return n&&(n+=". "),n+t+this.processedTitle},enumerable:!0,configurable:!0}),t.prototype.focus=function(e){void 0===e&&(e=!1),s.a.ScrollElementToTop(this.id);var t=e?this.getFirstErrorInputElementId():this.getFirstInputElementId();s.a.FocusElement(t)&&this.fireCallback(this.focusCallback)},t.prototype.getFirstInputElementId=function(){return this.inputId},t.prototype.getFirstErrorInputElementId=function(){return this.getFirstInputElementId()},t.prototype.canProcessedTextValues=function(e){return"no"==e||"title"==e||"require"==e},t.prototype.getProcessedTextValue=function(e){return"no"==e?this.no:"title"==e?this.processedTitle:"require"==e?this.requiredText:null},t.prototype.supportComment=function(){return!1},t.prototype.supportOther=function(){return!1},Object.defineProperty(t.prototype,"isRequired",{get:function(){return this.isRequiredValue},set:function(e){this.isRequired!=e&&(this.isRequiredValue=e,this.fireCallback(this.titleChangedCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasComment",{get:function(){return this.hasCommentValue},set:function(e){this.supportComment()&&(this.hasCommentValue=e,this.hasComment&&(this.hasOther=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"commentText",{get:function(){var e=this.locCommentText.text;return e||a.a.getString("otherItemText")},set:function(e){this.locCommentText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasOther",{get:function(){return this.hasOtherValue},set:function(e){this.supportOther()&&this.hasOther!=e&&(this.hasOtherValue=e,this.hasOther&&(this.hasComment=!1),this.hasOtherChanged())},enumerable:!0,configurable:!0}),t.prototype.hasOtherChanged=function(){},Object.defineProperty(t.prototype,"isReadOnly",{get:function(){return this.readOnly||this.survey&&this.survey.isDisplayMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"readOnly",{get:function(){return this.readOnlyValue},set:function(e){this.readOnly!=e&&(this.readOnlyValue=e,this.readOnlyChanged())},enumerable:!0,configurable:!0}),t.prototype.readOnlyChanged=function(){this.fireCallback(this.readOnlyChangedCallback)},Object.defineProperty(t.prototype,"no",{get:function(){if(this.visibleIndex<0)return"";var e=1,t=!0,n="";return this.survey&&this.survey.questionStartIndex&&(n=this.survey.questionStartIndex,parseInt(n)?e=parseInt(n):1==n.length&&(t=!1)),t?(this.visibleIndex+e).toString():String.fromCharCode(n.charCodeAt(0)+this.visibleIndex)},enumerable:!0,configurable:!0}),t.prototype.onSetData=function(){e.prototype.onSetData.call(this),this.onSurveyValueChanged(this.value)},Object.defineProperty(t.prototype,"value",{get:function(){return this.valueFromData(this.getValueCore())},set:function(e){this.setNewValue(e),this.isvalueChangedCallbackFiring||(this.isvalueChangedCallbackFiring=!0,this.fireCallback(this.valueChangedCallback),this.isvalueChangedCallbackFiring=!1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"comment",{get:function(){return this.getComment()},set:function(e){this.comment!=e&&(this.setComment(e),this.fireCallback(this.commentChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.getComment=function(){return null!=this.data?this.data.getComment(this.name):this.questionComment},t.prototype.setComment=function(e){this.setNewComment(e)},t.prototype.isEmpty=function(){return s.b.isValueEmpty(this.value)},t.prototype.hasErrors=function(e){return void 0===e&&(e=!0),this.checkForErrors(e),this.errors.length>0},Object.defineProperty(t.prototype,"currentErrorCount",{get:function(){return this.errors.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"requiredText",{get:function(){return null!=this.survey&&this.isRequired?this.survey.requiredText:""},enumerable:!0,configurable:!0}),t.prototype.addError=function(e){this.errors.push(e),this.fireCallback(this.errorsChangedCallback)},t.prototype.checkForErrors=function(e){var t=this.errors?this.errors.length:0;if(this.errors=[],this.onCheckForErrors(this.errors),0==this.errors.length&&this.value){var n=this.runValidators();n&&this.errors.push(n)}if(this.survey&&0==this.errors.length){var n=this.survey.validateQuestion(this.name);n&&this.errors.push(n)}e&&(t!=this.errors.length||t>0)&&this.fireCallback(this.errorsChangedCallback)},t.prototype.onCheckForErrors=function(e){this.hasRequiredError()&&this.errors.push(new u.a)},t.prototype.hasRequiredError=function(){return this.isRequired&&this.isEmpty()},t.prototype.runValidators=function(){return(new l.a).run(this)},t.prototype.setNewValue=function(e){this.setNewValueInData(e),this.onValueChanged()},t.prototype.setNewValueInData=function(e){this.isValueChangedInSurvey||(e=this.valueToData(e),this.setValueCore(e))},t.prototype.getValueCore=function(){return null!=this.data?this.data.getValue(this.name):this.questionValue},t.prototype.setValueCore=function(e){null!=this.data?this.data.setValue(this.name,e):this.questionValue=e},t.prototype.valueFromData=function(e){return e},t.prototype.valueToData=function(e){return e},t.prototype.onValueChanged=function(){},t.prototype.setNewComment=function(e){null!=this.data?this.data.setComment(this.name,e):this.questionComment=e},t.prototype.onSurveyValueChanged=function(e){this.isValueChangedInSurvey=!0,this.value=this.valueFromData(e),this.fireCallback(this.commentChangedCallback),this.isValueChangedInSurvey=!1},t.prototype.getValidatorTitle=function(){return null},t}(o.a);i.a.metaData.addClass("question",[{name:"title:text",serializationProperty:"locTitle"},{name:"commentText",serializationProperty:"locCommentText"},"isRequired:boolean","readOnly:boolean",{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],null,"questionbase")},function(e,t,n){"use strict";var r=n(8);n.d(t,"a",function(){return i});var i=function(){function e(e,t){void 0===t&&(t=null),this.locTextValue=new r.a(null,!0);var n=this;this.locTextValue.onRenderedHtmlCallback=function(e){return e||(n.value?n.value.toString():null)},t&&(this.locText.text=t),this.value=e}return e.createArray=function(t){var n=[];return e.setupArray(n,t),n},e.setupArray=function(e,t){e.push=function(e){var n=Array.prototype.push.call(this,e);return e.locOwner=t,n},e.splice=function(e,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var o=(a=Array.prototype.splice).call.apply(a,[this,e,n].concat(r));r||(r=[]);for(var s=0;s<r.length;s++)r[s].locOwner=t;return o;var a}},e.setData=function(t,n){t.length=0;for(var r=0;r<n.length;r++){var i=n[r],o=new e(null);o.setData(i),t.push(o)}},e.getData=function(e){for(var t=new Array,n=0;n<e.length;n++){var r=e[n];r.hasText?t.push({value:r.value,text:r.locText.getJson()}):t.push(r.value)}return t},e.getItemByValue=function(e,t){for(var n=0;n<e.length;n++)if(e[n].value==t)return e[n];return null},e.NotifyArrayOnLocaleChanged=function(e){for(var t=0;t<e.length;t++)e[t].locText.onChanged()},e.prototype.getType=function(){return"itemvalue"},Object.defineProperty(e.prototype,"locText",{get:function(){return this.locTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"locOwner",{get:function(){return this.locText.owner},set:function(e){this.locText.owner=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.itemValue},set:function(t){if(this.itemValue=t,this.itemValue){var n=this.itemValue.toString(),r=n.indexOf(e.Separator);r>-1&&(this.itemValue=n.slice(0,r),this.text=n.slice(r+1))}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasText",{get:function(){return!!this.locText.text},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){return this.hasText?this.locText.text:this.value?this.value.toString():null},set:function(e){this.locText.text=e},enumerable:!0,configurable:!0}),e.prototype.setData=function(t){if(void 0!==t.value){var n=null;this.isObjItemValue(t)&&(t.itemValue=t.itemValue,this.locText.setJson(t.locText.getJson()),n=e.itemValueProp),this.copyAttributes(t,n)}else this.value=t},e.prototype.isObjItemValue=function(e){return void 0!==e.getType&&"itemvalue"==e.getType()},e.prototype.copyAttributes=function(e,t){for(var n in e)"function"!=typeof e[n]&&(t&&t.indexOf(n)>-1||("text"==n?this.locText.setJson(e[n]):this[n]=e[n]))},e}();i.Separator="|",i.itemValueProp=["text","value","hasText","locOwner","locText"]},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"b",function(){return a}),n.d(t,"a",function(){return u});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={value:n.question.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state={value:this.question.value||""}},t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.question.value=e.target.value,this.setState({value:this.question.value||""})},t.prototype.render=function(){return this.question?this.isDisplayMode?i.createElement("div",{id:this.question.inputId,className:this.css},this.question.value):i.createElement("textarea",{id:this.question.inputId,className:this.css,type:"text",value:this.state.value,placeholder:this.question.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange,cols:this.question.cols,rows:this.question.rows}):null},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.question=t.question,n.comment=n.question.comment,n.state={value:n.comment},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.comment=e.target.value,this.setState({value:this.comment})},t.prototype.handleOnBlur=function(e){this.question.comment=this.comment},t.prototype.componentWillReceiveProps=function(e){this.question=e.question},t.prototype.render=function(){return this.question?this.isDisplayMode?i.createElement("div",{className:this.css.question.comment},this.comment):i.createElement("input",{type:"text",className:this.css.question.comment,value:this.state.value,onChange:this.handleOnChange,onBlur:this.handleOnBlur}):null},t}(o.a);s.a.Instance.registerQuestion("comment",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(10),s=n(11),a=n(1),u=n(9),l=n(19),c=n(8);n.d(t,"b",function(){return h}),n.d(t,"a",function(){return p});var h=function(e){function t(t){var n=e.call(this,t)||this;n.visibleChoicesCache=null,n.otherItemValue=new s.a("other",a.a.getString("otherItemText")),n.choicesFromUrl=null,n.cachedValueForUrlRequestion=null,n.storeOthersAsComment=!0,n.choicesOrderValue="none",n.isSettingComment=!1,n.choicesValues=s.a.createArray(n),n.choicesByUrl=n.createRestfull(),n.locOtherTextValue=new c.a(n,!0),n.locOtherErrorTextValue=new c.a(n,!0),n.otherItemValue.locOwner=n;var r=n;return n.choicesByUrl.getResultCallback=function(e){r.onLoadChoicesFromUrl(e)},n}return r.b(t,e),Object.defineProperty(t.prototype,"otherItem",{get:function(){return this.otherItemValue.text=this.otherText?this.otherText:a.a.getString("otherItemText"),this.otherItemValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isOtherSelected",{get:function(){return this.getStoreOthersAsComment()?this.getHasOther(this.value):this.getHasOther(this.cachedValue)},enumerable:!0,configurable:!0}),t.prototype.getHasOther=function(e){return e==this.otherItem.value},t.prototype.createRestfull=function(){return new l.a},t.prototype.getComment=function(){return this.getStoreOthersAsComment()?e.prototype.getComment.call(this):this.commentValue},t.prototype.setComment=function(t){this.getStoreOthersAsComment()?e.prototype.setComment.call(this,t):this.isSettingComment||t==this.commentValue||(this.isSettingComment=!0,this.commentValue=t,this.isOtherSelected&&this.setNewValueInData(this.cachedValue),this.isSettingComment=!1)},t.prototype.setNewValue=function(t){t&&(this.cachedValueForUrlRequestion=t),e.prototype.setNewValue.call(this,t)},t.prototype.valueFromData=function(t){return this.getStoreOthersAsComment()?e.prototype.valueFromData.call(this,t):(this.cachedValue=this.valueFromDataCore(t),this.cachedValue)},t.prototype.valueToData=function(t){return this.getStoreOthersAsComment()?e.prototype.valueToData.call(this,t):(this.cachedValue=t,this.valueToDataCore(t))},t.prototype.valueFromDataCore=function(e){return this.hasUnknownValue(e)?e==this.otherItem.value?e:(this.comment=e,this.otherItem.value):e},t.prototype.valueToDataCore=function(e){return e==this.otherItem.value&&this.getComment()&&(e=this.getComment()),e},t.prototype.hasUnknownValue=function(e){if(!e)return!1;for(var t=this.activeChoices,n=0;n<t.length;n++)if(t[n].value==e)return!1;return!0},Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValues},set:function(e){s.a.setData(this.choicesValues,e),this.onVisibleChoicesChanged()},enumerable:!0,configurable:!0}),t.prototype.hasOtherChanged=function(){this.onVisibleChoicesChanged()},Object.defineProperty(t.prototype,"choicesOrder",{get:function(){return this.choicesOrderValue},set:function(e){e!=this.choicesOrderValue&&(this.choicesOrderValue=e,this.onVisibleChoicesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"otherText",{get:function(){return this.locOtherText.text},set:function(e){this.locOtherText.text=e,this.onVisibleChoicesChanged()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"otherErrorText",{get:function(){return this.locOtherErrorText.text},set:function(e){this.locOtherErrorText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOtherText",{get:function(){return this.locOtherTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOtherErrorText",{get:function(){return this.locOtherErrorTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleChoices",{get:function(){return this.hasOther||"none"!=this.choicesOrder?(this.visibleChoicesCache||(this.visibleChoicesCache=this.sortVisibleChoices(this.activeChoices.slice()),this.hasOther&&this.visibleChoicesCache.push(this.otherItem)),this.visibleChoicesCache):this.activeChoices},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeChoices",{get:function(){return this.choicesFromUrl?this.choicesFromUrl:this.choices},enumerable:!0,configurable:!0}),t.prototype.supportComment=function(){return!0},t.prototype.supportOther=function(){return!0},t.prototype.onCheckForErrors=function(t){if(e.prototype.onCheckForErrors.call(this,t),this.isOtherSelected&&!this.comment){var n=this.otherErrorText;n||(n=a.a.getString("otherRequiredError")),t.push(new u.c(n))}},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.onVisibleChoicesChanged(),s.a.NotifyArrayOnLocaleChanged(this.visibleChoices)},t.prototype.getStoreOthersAsComment=function(){return this.storeOthersAsComment&&(null==this.survey||this.survey.storeOthersAsComment)},t.prototype.onSurveyLoad=function(){this.choicesByUrl&&this.choicesByUrl.run()},t.prototype.onLoadChoicesFromUrl=function(e){var t=this.errors.length;this.errors=[],this.choicesByUrl&&this.choicesByUrl.error&&this.errors.push(this.choicesByUrl.error),(t>0||this.errors.length>0)&&this.fireCallback(this.errorsChangedCallback);var n=null;e&&e.length>0&&(n=new Array,s.a.setData(n,e)),this.choicesFromUrl=n,this.onVisibleChoicesChanged(),this.cachedValueForUrlRequestion&&(this.value=this.cachedValueForUrlRequestion)},t.prototype.onVisibleChoicesChanged=function(){this.visibleChoicesCache=null,this.fireCallback(this.choicesChangedCallback)},t.prototype.sortVisibleChoices=function(e){var t=this.choicesOrder.toLowerCase();return"asc"==t?this.sortArray(e,1):"desc"==t?this.sortArray(e,-1):"random"==t?this.randomizeArray(e):e},t.prototype.sortArray=function(e,t){return e.sort(function(e,n){return e.text<n.text?-1*t:e.text>n.text?1*t:0})},t.prototype.randomizeArray=function(e){for(var t=e.length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),r=e[t];e[t]=e[n],e[n]=r}return e},t.prototype.clearUnusedValues=function(){e.prototype.clearUnusedValues.call(this),this.isOtherSelected||(this.comment=null)},t}(o.a),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.colCountValue=1,n}return r.b(t,e),Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<0||e>4||(this.colCountValue=e,this.fireCallback(this.colCountChangedCallback))},enumerable:!0,configurable:!0}),t}(h);i.a.metaData.addClass("selectbase",["hasComment:boolean","hasOther:boolean",{name:"choices:itemvalues",onGetValue:function(e){return s.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"choicesOrder",default:"none",choices:["none","asc","desc","random"]},{name:"choicesByUrl:restfull",className:"ChoicesRestfull",onGetValue:function(e){return e.choicesByUrl.isEmpty?null:e.choicesByUrl},onSetValue:function(e,t){e.choicesByUrl.setData(t)}},{name:"otherText",serializationProperty:"locOtherText"},{name:"otherErrorText",serializationProperty:"locOtherErrorText"},{name:"storeOthersAsComment:boolean",default:!0}],null,"question"),i.a.metaData.addClass("checkboxbase",[{name:"colCount:number",default:1,choices:[0,1,2,3,4]}],null,"selectbase")},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(10)),s=n(12),a=n(4),u=n(76);n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.setQuestion(t.question),n.creator=t.creator,n.css=t.css,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.creator=e.creator,this.css=e.css,this.setQuestion(e.question)},t.prototype.setQuestion=function(e){this.questionBase=e,this.question=e instanceof o.a?e:null;var t=this.question?this.question.value:null;this.state={visible:this.questionBase.visible,value:t,error:0,renderWidth:0,visibleIndexValue:-1,isReadOnly:this.questionBase.isReadOnly}},t.prototype.componentDidMount=function(){if(this.questionBase){var e=this;this.questionBase.react=e,this.questionBase.renderWidthChangedCallback=function(){e.state.renderWidth=e.state.renderWidth+1,e.setState(e.state)},this.questionBase.visibleIndexChangedCallback=function(){e.state.visibleIndexValue=e.questionBase.visibleIndex,e.setState(e.state)},this.questionBase.readOnlyChangedCallback=function(){e.state.isReadOnly=e.questionBase.isReadOnly,e.setState(e.state)};var t=this.refs.root;t&&this.questionBase.survey&&this.questionBase.survey.afterRenderQuestion(this.questionBase,t)}},t.prototype.componentWillUnmount=function(){this.refs.root;this.questionBase&&(this.questionBase.react=null,this.questionBase.renderWidthChangedCallback=null,this.questionBase.visibleIndexChangedCallback=null,this.questionBase.readOnlyChangedCallback=null)},t.prototype.render=function(){if(!this.questionBase||!this.creator)return null;if(!this.questionBase.visible)return null;var e=this.renderQuestion(),t=this.questionBase.hasTitle?this.renderTitle():null,n="top"==this.creator.questionTitleLocation()?t:null,r="bottom"==this.creator.questionTitleLocation()?t:null,o=this.question&&this.question.hasComment?this.renderComment():null,s=this.renderErrors(),a=this.questionBase.indent>0?this.questionBase.indent*this.css.question.indent+"px":null,u=this.questionBase.rightIndent>0?this.questionBase.rightIndent*this.css.question.indent+"px":null,l={display:"inline-block",verticalAlign:"top"};return this.questionBase.renderWidth&&(l.width=this.questionBase.renderWidth),a&&(l.marginLeft=a),u&&(l.paddingRight=u),i.createElement("div",{ref:"root",id:this.questionBase.id,className:this.css.question.root,style:l},n,s,e,o,r)},t.prototype.renderQuestion=function(){return this.questionBase.customWidget?i.createElement(u.a,{creator:this.creator,question:this.questionBase}):this.creator.createQuestionElement(this.questionBase)},t.prototype.renderTitle=function(){var e=a.a.renderLocString(this.question.locTitle);return i.createElement("h5",{className:this.css.question.title},e)},t.prototype.renderComment=function(){var e=a.a.renderLocString(this.question.locCommentText);return i.createElement("div",null,i.createElement("div",null,e),i.createElement(s.a,{question:this.question,css:this.css}))},t.prototype.renderErrors=function(){return i.createElement(c,{question:this.question,css:this.css,creator:this.creator})},t}(i.Component),c=function(e){function t(t){var n=e.call(this,t)||this;return n.setQuestion(t.question),n.creator=t.creator,n.css=t.css,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.setQuestion(e.question),this.creator=e.creator,this.css=e.css},t.prototype.setQuestion=function(e){if(this.question=e instanceof o.a?e:null,this.question){var t=this;this.question.errorsChangedCallback=function(){t.state.error=t.state.error+1,t.setState(t.state)}}this.state={error:0}},t.prototype.render=function(){if(!this.question||0==this.question.errors.length)return null;for(var e=[],t=0;t<this.question.errors.length;t++){var n=this.question.errors[t].getText(),r="error"+t;e.push(this.creator.renderError(r,n))}return i.createElement("div",{className:this.css.error.root},e)},t}(i.Component)},function(e,t,n){"use strict";var r=n(0),i=n(23);n.d(t,"a",function(){return o});var o=function(e){function t(t){return void 0===t&&(t=null),e.call(this,t)||this}return r.b(t,e),t.prototype.render=function(){this.renderCallback&&this.renderCallback()},t.prototype.mergeCss=function(e,t){this.mergeValues(e,t)},t.prototype.doAfterRenderSurvey=function(e){this.afterRenderSurvey(e)},t.prototype.onLoadSurveyFromService=function(){this.render()},t.prototype.onLoadingSurveyFromService=function(){this.render()},t}(i.a)},function(e,t,n){"use strict";var r=n(30),i=n(20);n.d(t,"b",function(){return o}),n.d(t,"c",function(){return s}),n.d(t,"a",function(){return a});var o=function(){function e(){this.opValue="equal"}return Object.defineProperty(e,"operators",{get:function(){return null!=e.operatorsValue?e.operatorsValue:(e.operatorsValue={empty:function(e,t){return!e},notempty:function(e,t){return!!e},equal:function(e,t){return e==t},notequal:function(e,t){return e!=t},contains:function(e,t){return e&&e.indexOf&&e.indexOf(t)>-1},notcontains:function(e,t){return!e||!e.indexOf||-1==e.indexOf(t)},greater:function(e,t){return e>t},less:function(e,t){return e<t},greaterorequal:function(e,t){return e>=t},lessorequal:function(e,t){return e<=t}},e.operatorsValue)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"operator",{get:function(){return this.opValue},set:function(t){t&&(t=t.toLowerCase(),e.operators[t]&&(this.opValue=t))},enumerable:!0,configurable:!0}),e.prototype.perform=function(t,n){return void 0===t&&(t=null),void 0===n&&(n=null),t||(t=this.left),n||(n=this.right),e.operators[this.operator](this.getPureValue(t),this.getPureValue(n))},e.prototype.getPureValue=function(e){if(!e||"string"!=typeof e)return e;e.length>0&&("'"==e[0]||'"'==e[0])&&(e=e.substr(1));var t=e.length;return t>0&&("'"==e[t-1]||'"'==e[t-1])&&(e=e.substr(0,t-1)),e},e}();o.operatorsValue=null;var s=function(){function e(){this.connectiveValue="and",this.children=[]}return Object.defineProperty(e.prototype,"connective",{get:function(){return this.connectiveValue},set:function(e){e&&(e=e.toLowerCase(),"&"!=e&&"&&"!=e||(e="and"),"|"!=e&&"||"!=e||(e="or"),"and"!=e&&"or"!=e||(this.connectiveValue=e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isEmpty",{get:function(){return 0==this.children.length},enumerable:!0,configurable:!0}),e.prototype.clear=function(){this.children=[],this.connective="and"},e}(),a=function(){function e(e){this.root=new s,this.expression=e,this.processValue=new i.a}return Object.defineProperty(e.prototype,"expression",{get:function(){return this.expressionValue},set:function(e){this.expression!=e&&(this.expressionValue=e,(new r.a).parse(this.expressionValue,this.root))},enumerable:!0,configurable:!0}),e.prototype.run=function(e){return this.values=e,this.runNode(this.root)},e.prototype.runNode=function(e){for(var t="and"==e.connective,n=0;n<e.children.length;n++){var r=this.runNodeCondition(e.children[n]);if(!r&&t)return!1;if(r&&!t)return!0}return t},e.prototype.runNodeCondition=function(e){return!!e&&(e.children?this.runNode(e):!!e.left&&this.runCondition(e))},e.prototype.runCondition=function(e){var t=e.left,n=this.getValueName(t);if(n){if(!this.processValue.hasValue(n,this.values))return"empty"===e.operator;t=this.processValue.getValue(n,this.values)}var r=e.right;if(n=this.getValueName(r)){if(!this.processValue.hasValue(n,this.values))return!1;r=this.processValue.getValue(n,this.values)}return e.perform(t,r)},e.prototype.getValueName=function(e){return e?"string"!=typeof e?null:e.length<3||"{"!=e[0]||"}"!=e[e.length-1]?null:e.substr(1,e.length-2):null},e}()},function(e,t,n){"use strict";n.d(t,"b",function(){return r}),n.d(t,"a",function(){return i});var r={currentType:"",getCss:function(){var e=this.currentType?this[this.currentType]:i;return e||(e=i),e}},i={root:"sv_main",header:"",body:"sv_body",footer:"sv_nav",navigationButton:"",navigation:{complete:"",prev:"",next:""},progress:"sv_progress",progressBar:"",pageTitle:"sv_p_title",row:"sv_row",question:{root:"sv_q",title:"sv_q_title",comment:"",indent:20},error:{root:"sv_q_erbox",icon:"",item:""},checkbox:{root:"sv_qcbc",item:"sv_q_checkbox",other:"sv_q_other"},comment:"",dropdown:{root:"",control:""},matrix:{root:"sv_q_matrix"},matrixdropdown:{root:"sv_q_matrix"},matrixdynamic:{root:"table",button:""},multipletext:{root:"",itemTitle:"",itemValue:""},radiogroup:{root:"sv_qcbc",item:"sv_q_radiogroup",label:"",other:"sv_q_other"},rating:{root:"sv_q_rating",item:"sv_q_rating_item"},text:"",window:{root:"sv_window",body:"sv_window_content",header:{root:"sv_window_title",title:"",button:"",buttonExpanded:"",buttonCollapsed:""}}};r.standard=i},function(e,t,n){"use strict";var r=n(0),i=n(3);n.n(i);n.d(t,"a",function(){return o});var o=function(e){function t(t){var n=e.call(this,t)||this;return n.updateStateFunction=null,n.survey=t.survey,n.css=t.css,n.state={update:0},n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.survey=e.survey,this.css=e.css},t.prototype.componentDidMount=function(){if(this.survey){var e=this;this.updateStateFunction=function(){e.state.update=e.state.update+1,e.setState(e.state)},this.survey.onPageVisibleChanged.add(this.updateStateFunction)}},t.prototype.componentWillUnmount=function(){this.survey&&this.updateStateFunction&&(this.survey.onPageVisibleChanged.remove(this.updateStateFunction),this.updateStateFunction=null)},t}(i.Component)},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(11),s=n(2),a=n(1),u=n(9);n.d(t,"a",function(){return l});var l=function(e){function t(){var t=e.call(this)||this;return t.url="",t.path="",t.valueName="",t.titleName="",t.error=null,t}return r.b(t,e),t.prototype.run=function(){if(this.url&&this.getResultCallback){this.error=null;var e=new XMLHttpRequest;e.open("GET",this.url),e.setRequestHeader("Content-Type","application/x-www-form-urlencoded");var t=this;e.onload=function(){200==e.status?t.onLoad(JSON.parse(e.response)):t.onError(e.statusText,e.responseText)},e.send()}},t.prototype.getType=function(){return"choicesByUrl"},Object.defineProperty(t.prototype,"isEmpty",{get:function(){return!(this.url||this.path||this.valueName||this.titleName)},enumerable:!0,configurable:!0}),t.prototype.setData=function(e){this.clear(),e.url&&(this.url=e.url),e.path&&(this.path=e.path),e.valueName&&(this.valueName=e.valueName),e.titleName&&(this.titleName=e.titleName)},t.prototype.clear=function(){this.url="",this.path="",this.valueName="",this.titleName=""},t.prototype.onLoad=function(e){var t=[];if((e=this.getResultAfterPath(e))&&e.length)for(var n=0;n<e.length;n++){var r=e[n];if(r){var i=this.getValue(r),s=this.getTitle(r);t.push(new o.a(i,s))}}else this.error=new u.c(a.a.getString("urlGetChoicesError"));this.getResultCallback(t)},t.prototype.onError=function(e,t){this.error=new u.c(a.a.getString("urlRequestError").format(e,t)),this.getResultCallback([])},t.prototype.getResultAfterPath=function(e){if(!e)return e;if(!this.path)return e;for(var t=this.getPathes(),n=0;n<t.length;n++)if(!(e=e[t[n]]))return null;return e},t.prototype.getPathes=function(){var e=[];return e=this.path.indexOf(";")>-1?this.path.split(";"):this.path.split(","),0==e.length&&e.push(this.path),e},t.prototype.getValue=function(e){return this.valueName?e[this.valueName]:Object.keys(e).length<1?null:e[Object.keys(e)[0]]},t.prototype.getTitle=function(e){return this.titleName?e[this.titleName]:null},t}(i.b);s.a.metaData.addClass("choicesByUrl",["url","path","valueName","titleName"],function(){return new l})},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){}return e.prototype.getFirstName=function(e){if(!e)return e;for(var t="",n=0;n<e.length;n++){var r=e[n];if("."==r||"["==r)break;t+=r}return t},e.prototype.hasValue=function(e,t){return this.getValueCore(e,t).hasValue},e.prototype.getValue=function(e,t){return this.getValueCore(e,t).value},e.prototype.getValueCore=function(e,t){var n={hasValue:!1,value:null},r=t;if(!r)return n;for(var i=!0;e&&e.length>0;){if(!i&&"["==e[0]){if(!Array.isArray(r))return n;for(var o=1,s="";o<e.length&&"]"!=e[o];)s+=e[o],o++;if(e=o<e.length?e.substr(o+1):"",(o=this.getIntValue(s))<0||o>=r.length)return n;r=r[o]}else{i||(e=e.substr(1));var a=this.getFirstName(e);if(!a)return n;if(!r[a])return n;r=r[a],e=e.substr(a.length)}i=!1}return n.value=r,n.hasValue=!0,n},e.prototype.getIntValue=function(e){return"0"==e||(0|e)>0&&e%1==0?Number(e):-1},e}()},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(10),s=n(6),a=n(11),u=n(1),l=n(13),c=n(19),h=n(7),p=n(8);n.d(t,"b",function(){return d}),n.d(t,"a",function(){return f}),n.d(t,"c",function(){return g}),n.d(t,"d",function(){return m});var d=function(e){function t(t,n){void 0===n&&(n=null);var r=e.call(this)||this;r.name=t,r.isRequired=!1,r.hasOther=!1,r.minWidth="",r.cellType="default",r.inputType="text",r.choicesOrder="none",r.colOwner=null,r.validators=new Array,r.colCountValue=-1,r.choicesValue=a.a.createArray(r),r.locTitleValue=new p.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getFullTitle(e)},r.locOptionsCaptionValue=new p.a(r),r.locPlaceHolderValue=new p.a(r),r.choicesByUrl=new c.a,n&&(r.title=n),r}return r.b(t,e),t.prototype.getType=function(){return"matrixdropdowncolumn"},Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text?this.locTitle.text:this.name},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){return this.getFullTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getFullTitle=function(e){if(e||(e=this.name),this.isRequired){var t=this.colOwner?this.colOwner.getRequiredText():"";t&&(t+=" "),e=t+e}return e},Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text},set:function(e){this.locOptionsCaption.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValue},set:function(e){a.a.setData(this.choicesValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<-1||e>4||(this.colCountValue=e)},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.colOwner?this.colOwner.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.colOwner?this.colOwner.getMarkdownHtml(e):null},t.prototype.onLocaleChanged=function(){this.locTitle.onChanged(),this.locOptionsCaption.onChanged(),a.a.NotifyArrayOnLocaleChanged(this.choices)},t}(s.b),f=function(){function e(e,t,n){this.column=e,this.row=t,this.questionValue=n.createQuestion(this.row,this.column),this.questionValue.setData(t)}return Object.defineProperty(e.prototype,"question",{get:function(){return this.questionValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.question.value},set:function(e){this.question.value=e},enumerable:!0,configurable:!0}),e}(),g=function(){function e(t,n){this.rowValues={},this.rowComments={},this.isSettingValue=!1,this.cells=[],this.data=t,this.value=n,this.idValue=e.getId(),this.buildCells()}return e.getId=function(){return"srow_"+e.idCounter++},Object.defineProperty(e.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rowName",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.rowValues},set:function(e){if(this.isSettingValue=!0,this.rowValues={},null!=e)for(var t in e)this.rowValues[t]=e[t];for(var n=0;n<this.cells.length;n++)this.cells[n].question.onSurveyValueChanged(this.getValue(this.cells[n].column.name));this.isSettingValue=!1},enumerable:!0,configurable:!0}),e.prototype.getValue=function(e){return this.rowValues[e]},e.prototype.setValue=function(e,t){this.isSettingValue||(""===t&&(t=null),null!=t?this.rowValues[e]=t:delete this.rowValues[e],this.data.onRowChanged(this,this.value))},e.prototype.getComment=function(e){return this.rowComments[e]},e.prototype.setComment=function(e,t){this.rowComments[e]=t},Object.defineProperty(e.prototype,"isEmpty",{get:function(){var e=this.value;if(s.b.isValueEmpty(e))return!0;for(var t in e)return!1;return!0},enumerable:!0,configurable:!0}),e.prototype.getLocale=function(){return this.data?this.data.getLocale():""},e.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},e.prototype.onLocaleChanged=function(){for(var e=0;e<this.cells.length;e++)this.cells[e].question.onLocaleChanged()},e.prototype.buildCells=function(){for(var e=this.data.columns,t=0;t<e.length;t++){var n=e[t];this.cells.push(this.createCell(n))}},e.prototype.createCell=function(e){return new f(e,this,this.data)},e}();g.idCounter=1;var m=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.columnsValue=[],n.isRowChanging=!1,n.generatedVisibleRows=null,n.cellTypeValue="dropdown",n.columnColCountValue=0,n.columnMinWidth="",n.horizontalScroll=!1,n.choicesValue=a.a.createArray(n),n.locOptionsCaptionValue=new p.a(n),n.overrideColumnsMethods(),n}return r.b(t,e),t.addDefaultColumns=function(e){for(var t=h.a.DefaultColums,n=0;n<t.length;n++)e.addColumn(t[n])},t.prototype.getType=function(){return"matrixdropdownbase"},Object.defineProperty(t.prototype,"columns",{get:function(){return this.columnsValue},set:function(e){this.columnsValue=e,this.overrideColumnsMethods(),this.fireCallback(this.columnsChangedCallback)},enumerable:!0,configurable:!0}),t.prototype.overrideColumnsMethods=function(){var e=this;this.columnsValue.push=function(t){var n=Array.prototype.push.call(this,t);return t.colOwner=e,null!=e.data&&e.fireCallback(e.columnsChangedCallback),n},this.columnsValue.splice=function(t,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var o=(a=Array.prototype.splice).call.apply(a,[this,t,n].concat(r));r||(r=[]);for(var s=0;s<r.length;s++)r[s].colOwner=e;return null!=e.data&&e.fireCallback(e.columnsChangedCallback),o;var a}},Object.defineProperty(t.prototype,"cellType",{get:function(){return this.cellTypeValue},set:function(e){this.cellType!=e&&(this.cellTypeValue=e,this.fireCallback(this.updateCellsCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"columnColCount",{get:function(){return this.columnColCountValue},set:function(e){e<0||e>4||(this.columnColCountValue=e,this.fireCallback(this.updateCellsCallback))},enumerable:!0,configurable:!0}),t.prototype.getRequiredText=function(){return this.survey?this.survey.requiredText:""},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locOptionsCaption.onChanged();for(var t=0;t<this.columns.length;t++)this.columns[t].onLocaleChanged();for(var n=this.visibleRows,t=0;t<n.length;t++)n[t].onLocaleChanged();this.fireCallback(this.updateCellsCallback)},t.prototype.getColumnWidth=function(e){return e.minWidth?e.minWidth:this.columnMinWidth},Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValue},set:function(e){a.a.setData(this.choicesValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text?this.locOptionsCaption.text:u.a.getString("optionsCaption")},set:function(e){this.locOptionsCaption.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),t.prototype.addColumn=function(e,t){void 0===t&&(t=null);var n=new d(e,t);return this.columnsValue.push(n),n},Object.defineProperty(t.prototype,"visibleRows",{get:function(){return this.generatedVisibleRows=this.generateRows(),this.generatedVisibleRows},enumerable:!0,configurable:!0}),t.prototype.generateRows=function(){return null},t.prototype.createNewValue=function(e){return e||{}},t.prototype.getRowValue=function(e,t,n){void 0===n&&(n=!1);var r=t[e.rowName]?t[e.rowName]:null;return!r&&n&&(r={},t[e.rowName]=r),r},t.prototype.onBeforeValueChanged=function(e){},t.prototype.onValueChanged=function(){if(!this.isRowChanging&&(this.onBeforeValueChanged(this.value),this.generatedVisibleRows&&0!=this.generatedVisibleRows.length)){this.isRowChanging=!0;for(var e=this.createNewValue(this.value),t=0;t<this.generatedVisibleRows.length;t++){var n=this.generatedVisibleRows[t];this.generatedVisibleRows[t].value=this.getRowValue(n,e)}this.isRowChanging=!1}},t.prototype.supportGoNextPageAutomatic=function(){var e=this.generatedVisibleRows;if(e||(e=this.visibleRows),!e)return!0;for(var t=0;t<e.length;t++){var n=this.generatedVisibleRows[t].cells;if(n)for(var r=0;r<n.length;r++){var i=n[r].question;if(i&&(!i.supportGoNextPageAutomatic()||!i.value))return!1}}return!0},t.prototype.hasErrors=function(t){void 0===t&&(t=!0);var n=this.hasErrorInColumns(t);return e.prototype.hasErrors.call(this,t)||n},t.prototype.hasErrorInColumns=function(e){if(!this.generatedVisibleRows)return!1;for(var t=!1,n=0;n<this.columns.length;n++)for(var r=0;r<this.generatedVisibleRows.length;r++){var i=this.generatedVisibleRows[r].cells;t=i&&i[n]&&i[n].question&&i[n].question.hasErrors(e)||t}return t},t.prototype.getFirstInputElementId=function(){var t=this.getFirstCellQuestion(!1);return t?t.inputId:e.prototype.getFirstInputElementId.call(this)},t.prototype.getFirstErrorInputElementId=function(){var t=this.getFirstCellQuestion(!0);return t?t.inputId:e.prototype.getFirstErrorInputElementId.call(this)},t.prototype.getFirstCellQuestion=function(e){if(!this.generatedVisibleRows)return null;for(var t=0;t<this.generatedVisibleRows.length;t++)for(var n=this.generatedVisibleRows[t].cells,r=0;r<this.columns.length;r++){if(!e)return n[r].question;if(n[r].question.currentErrorCount>0)return n[r].question}return null},t.prototype.createQuestion=function(e,t){var n=this.createQuestionCore(e,t);return n.name=t.name,n.isRequired=t.isRequired,n.hasOther=t.hasOther,n.readOnly=this.readOnly,n.validators=t.validators,n.setData(this.survey),t.hasOther&&n instanceof l.b&&(n.storeOthersAsComment=!1),n},t.prototype.createQuestionCore=function(e,t){var n="default"==t.cellType?this.cellType:t.cellType,r=this.getQuestionName(e,t);return"checkbox"==n?this.createCheckbox(r,t):"radiogroup"==n?this.createRadiogroup(r,t):"text"==n?this.createText(r,t):"comment"==n?this.createComment(r,t):this.createDropdown(r,t)},t.prototype.getQuestionName=function(e,t){return e.rowName+"_"+t.name},t.prototype.getColumnChoices=function(e){return e.choices&&e.choices.length>0?e.choices:this.choices},t.prototype.getColumnOptionsCaption=function(e){return e.optionsCaption?e.optionsCaption:this.optionsCaption},t.prototype.createDropdown=function(e,t){var n=this.createCellQuestion("dropdown",e);return this.setSelectBaseProperties(n,t),n.optionsCaption=this.getColumnOptionsCaption(t),n},t.prototype.createCheckbox=function(e,t){var n=this.createCellQuestion("checkbox",e);return this.setSelectBaseProperties(n,t),n.colCount=t.colCount>-1?t.colCount:this.columnColCount,n},t.prototype.createRadiogroup=function(e,t){var n=this.createCellQuestion("radiogroup",e);return this.setSelectBaseProperties(n,t),n.colCount=t.colCount>-1?t.colCount:this.columnColCount,n},t.prototype.setSelectBaseProperties=function(e,t){e.choicesOrder=t.choicesOrder,e.choices=this.getColumnChoices(t),e.choicesByUrl.setData(t.choicesByUrl),e.choicesByUrl.isEmpty||e.choicesByUrl.run()},t.prototype.createText=function(e,t){var n=this.createCellQuestion("text",e);return n.inputType=t.inputType,n.placeHolder=t.placeHolder,n},t.prototype.createComment=function(e,t){var n=this.createCellQuestion("comment",e);return n.placeHolder=t.placeHolder,n},t.prototype.createCellQuestion=function(e,t){return h.a.Instance.createQuestion(e,t)},t.prototype.deleteRowValue=function(e,t){return delete e[t.rowName],0==Object.keys(e).length?null:e},t.prototype.onRowChanged=function(e,t){var n=this.createNewValue(this.value),r=this.getRowValue(e,n,!0);for(var i in r)delete r[i];if(t){t=JSON.parse(JSON.stringify(t));for(var i in t)r[i]=t[i]}0==Object.keys(r).length&&(n=this.deleteRowValue(n,e)),this.isRowChanging=!0,this.setNewValue(n),this.isRowChanging=!1},t}(o.a);i.a.metaData.addClass("matrixdropdowncolumn",["name",{name:"title",serializationProperty:"locTitle"},{name:"choices:itemvalues",onGetValue:function(e){return a.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"optionsCaption",serializationProperty:"locOptionsCaption"},{name:"cellType",default:"default",choices:["default","dropdown","checkbox","radiogroup","text","comment"]},{name:"colCount",default:-1,choices:[-1,0,1,2,3,4]},"isRequired:boolean","hasOther:boolean","minWidth",{name:"placeHolder",serializationProperty:"locPlaceHolder"},{name:"choicesOrder",default:"none",choices:["none","asc","desc","random"]},{name:"choicesByUrl:restfull",className:"ChoicesRestfull",onGetValue:function(e){return e.choicesByUrl.isEmpty?null:e.choicesByUrl},onSetValue:function(e,t){e.choicesByUrl.setData(t)}},{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],function(){return new d("")}),i.a.metaData.addClass("matrixdropdownbase",[{name:"columns:matrixdropdowncolumns",className:"matrixdropdowncolumn"},"horizontalScroll:boolean",{name:"choices:itemvalues",onGetValue:function(e){return a.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"optionsCaption",serializationProperty:"locOptionsCaption"},{name:"cellType",default:"dropdown",choices:["dropdown","checkbox","radiogroup","text","comment"]},{name:"columnColCount",default:0,choices:[0,1,2,3,4]},"columnMinWidth"],function(){return new m("")},"question")},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(2),s=n(16);n.d(t,"a",function(){return a});var a=function(e){function t(n){var r=e.call(this)||this;return r.name=n,r.conditionRunner=null,r.visibleIf="",r.visibleValue=!0,r.startWithNewLineValue=!0,r.visibleIndexValue=-1,r.width="",r.renderWidthValue="",r.rightIndentValue=0,r.indent=0,r.localeChanged=new i.c,r.idValue=t.getQuestionId(),r.onCreating(),r}return r.b(t,e),t.getQuestionId=function(){return"sq_"+t.questionCounter++},Object.defineProperty(t.prototype,"isPanel",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!=this.visible&&(this.visibleValue=e,this.fireCallback(this.visibilityChangedCallback),this.fireCallback(this.rowVisibilityChangedCallback),this.survey&&this.survey.questionVisibilityChanged(this,this.visible))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this.visible||this.survey&&this.survey.isDesignMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isReadOnly",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleIndex",{get:function(){return this.visibleIndexValue},enumerable:!0,configurable:!0}),t.prototype.hasErrors=function(e){return void 0===e&&(e=!0),!1},Object.defineProperty(t.prototype,"currentErrorCount",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTitle",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInput",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasComment",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startWithNewLine",{get:function(){return this.startWithNewLineValue},set:function(e){this.startWithNewLine!=e&&(this.startWithNewLineValue=e,this.startWithNewLineChangedCallback&&this.startWithNewLineChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderWidth",{get:function(){return this.renderWidthValue},set:function(e){e!=this.renderWidth&&(this.renderWidthValue=e,this.fireCallback(this.renderWidthChangedCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightIndent",{get:function(){return this.rightIndentValue},set:function(e){e!=this.rightIndent&&(this.rightIndentValue=e,this.fireCallback(this.renderWidthChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.focus=function(e){void 0===e&&(e=!1)},t.prototype.setData=function(e){this.data=e,e&&e.questionAdded&&(this.surveyValue=e),this.onSetData()},Object.defineProperty(t.prototype,"survey",{get:function(){return this.surveyValue},enumerable:!0,configurable:!0}),t.prototype.fireCallback=function(e){e&&e()},t.prototype.onSetData=function(){},t.prototype.onCreating=function(){},t.prototype.runCondition=function(e){this.visibleIf&&(this.conditionRunner||(this.conditionRunner=new s.a(this.visibleIf)),this.conditionRunner.expression=this.visibleIf,this.visible=this.conditionRunner.run(e))},t.prototype.onSurveyValueChanged=function(e){},t.prototype.onSurveyLoad=function(){},t.prototype.setVisibleIndex=function(e){this.visibleIndexValue!=e&&(this.visibleIndexValue=e,this.fireCallback(this.visibleIndexChangedCallback))},t.prototype.supportGoNextPageAutomatic=function(){return!1},t.prototype.clearUnusedValues=function(){},t.prototype.onLocaleChanged=function(){this.localeChanged.fire(this,this.getLocale())},t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},t}(i.b);a.questionCounter=100,o.a.metaData.addClass("questionbase",["!name",{name:"visible:boolean",default:!0},"visibleIf:expression",{name:"width"},{name:"startWithNewLine:boolean",default:!0},{name:"indent:number",default:0,choices:[0,1,2,3]}])},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(32),a=n(24),u=n(20),l=n(31),c=n(1),h=n(9),p=n(34),d=n(8);n.d(t,"a",function(){return f});var f=function(e){function t(t){void 0===t&&(t=null);var n=e.call(this)||this;n.surveyId=null,n.surveyPostId=null,n.clientId=null,n.cookieName=null,n.sendResultOnPageNext=!1,n.commentPrefix="-Comment",n.focusFirstQuestionAutomatic=!0,n.showNavigationButtons=!0,n.showTitle=!0,n.showPageTitles=!0,n.showCompletedPage=!0,n.requiredText="*",n.questionStartIndex="",n.showProgressBar="off",n.storeOthersAsComment=!0,n.goNextPageAutomatic=!1,n.pages=new Array,n.triggers=new Array,n.clearInvisibleValues=!1,n.currentPageValue=null,n.valuesHash={},n.variablesHash={},n.showPageNumbersValue=!1,n.showQuestionNumbersValue="on",n.questionTitleLocationValue="top",n.localeValue="",n.isCompleted=!1,n.isLoading=!1,n.processedTextValues={},n.isValidatingOnServerValue=!1,n.modeValue="edit",n.isDesignModeValue=!1,n.onComplete=new o.c,n.onPartialSend=new o.c,n.onCurrentPageChanged=new o.c,n.onValueChanged=new o.c,n.onVisibleChanged=new o.c,n.onPageVisibleChanged=new o.c,n.onQuestionAdded=new o.c,n.onQuestionRemoved=new o.c,n.onPanelAdded=new o.c,n.onPanelRemoved=new o.c,n.onValidateQuestion=new o.c,n.onProcessHtml=new o.c,n.onTextMarkdown=new o.c,n.onSendResult=new o.c,n.onGetResult=new o.c,n.onUploadFile=new o.c,n.onAfterRenderSurvey=new o.c,n.onAfterRenderPage=new o.c,n.onAfterRenderQuestion=new o.c,n.onAfterRenderPanel=new o.c,n.jsonErrors=null,n.isLoadingFromJsonValue=!1;var r=n;return n.locTitleValue=new d.a(n,!0),n.locTitleValue.onRenderedHtmlCallback=function(e){return r.processedTitle},n.locCompletedHtmlValue=new d.a(n),n.locPagePrevTextValue=new d.a(n),n.locPageNextTextValue=new d.a(n),n.locCompleteTextValue=new d.a(n),n.locQuestionTitleTemplateValue=new d.a(n,!0),n.textPreProcessor=new a.a,n.textPreProcessor.onHasValue=function(e){return r.hasProcessedTextValue(e)},n.textPreProcessor.onProcess=function(e){return r.getProcessedTextValue(e)},n.pages.push=function(e){return e.data=r,Array.prototype.push.call(this,e)},n.triggers.push=function(e){return e.setOwner(r),Array.prototype.push.call(this,e)},n.updateProcessedTextValues(),n.onBeforeCreating(),t&&(n.setJsonObject(t),n.surveyId&&n.loadSurveyFromService(n.surveyId)),n.onCreating(),n}return r.b(t,e),t.prototype.getType=function(){return"survey"},Object.defineProperty(t.prototype,"locale",{get:function(){return this.localeValue},set:function(e){this.localeValue=e,c.a.currentLocale=e;for(var t=0;t<this.pages.length;t++)this.pages[t].onLocaleChanged()},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.locale},t.prototype.getMarkdownHtml=function(e){var t={text:e,html:null};return this.onTextMarkdown.fire(this,t),t.html},t.prototype.getLocString=function(e){return c.a.getString(e)},Object.defineProperty(t.prototype,"emptySurveyText",{get:function(){return this.getLocString("emptySurvey")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completedHtml",{get:function(){return this.locCompletedHtml.text},set:function(e){this.locCompletedHtml.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCompletedHtml",{get:function(){return this.locCompletedHtmlValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pagePrevText",{get:function(){return this.locPagePrevText.text?this.locPagePrevText.text:this.getLocString("pagePrevText")},set:function(e){this.locPagePrevText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPagePrevText",{get:function(){return this.locPagePrevTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pageNextText",{get:function(){return this.locPageNextText.text?this.locPageNextText.text:this.getLocString("pageNextText")},set:function(e){this.locPageNextText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPageNextText",{get:function(){return this.locPageNextTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completeText",{get:function(){return this.locCompleteText.text?this.locCompleteText.text:this.getLocString("completeText")},set:function(e){this.locCompleteText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCompleteText",{get:function(){return this.locCompleteTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questionTitleTemplate",{get:function(){return this.locQuestionTitleTemplate.text},set:function(e){this.locQuestionTitleTemplate.text=e},enumerable:!0,configurable:!0}),t.prototype.getQuestionTitleTemplate=function(){return this.locQuestionTitleTemplate.textOrHtml},Object.defineProperty(t.prototype,"locQuestionTitleTemplate",{get:function(){return this.locQuestionTitleTemplateValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"showPageNumbers",{get:function(){return this.showPageNumbersValue},set:function(e){e!==this.showPageNumbers&&(this.showPageNumbersValue=e,this.updateVisibleIndexes())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"showQuestionNumbers",{get:function(){return this.showQuestionNumbersValue},set:function(e){e!==this.showQuestionNumbers&&(this.showQuestionNumbersValue=e,this.updateVisibleIndexes())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedTitle",{get:function(){return this.processText(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questionTitleLocation",{get:function(){return this.questionTitleLocationValue},set:function(e){e!==this.questionTitleLocationValue&&(this.questionTitleLocationValue=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this.modeValue},set:function(e){e!=this.mode&&("edit"!=e&&"display"!=e||(this.modeValue=e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"data",{get:function(){var e={};for(var t in this.valuesHash)e[t]=this.valuesHash[t];return e},set:function(e){if(this.valuesHash={},e)for(var t in e)this._setDataValue(e,t),this.checkTriggers(t,e[t],!1),this.processedTextValues[t.toLowerCase()]||(this.processedTextValues[t.toLowerCase()]="value");this.notifyAllQuestionsOnValueChanged(),this.runConditions()},enumerable:!0,configurable:!0}),t.prototype._setDataValue=function(e,t){this.valuesHash[t]=e[t]},Object.defineProperty(t.prototype,"comments",{get:function(){var e={};for(var t in this.valuesHash)t.indexOf(this.commentPrefix)>0&&(e[t]=this.valuesHash[t]);return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visiblePages",{get:function(){if(this.isDesignMode)return this.pages;for(var e=new Array,t=0;t<this.pages.length;t++)this.pages[t].isVisible&&e.push(this.pages[t]);return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isEmpty",{get:function(){return 0==this.pages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"PageCount",{get:function(){return this.pages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visiblePageCount",{get:function(){return this.visiblePages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentPage",{get:function(){var e=this.visiblePages;return null!=this.currentPageValue&&e.indexOf(this.currentPageValue)<0&&(this.currentPage=null),null==this.currentPageValue&&e.length>0&&(this.currentPage=e[0]),this.currentPageValue},set:function(e){var t=this.visiblePages;if(!(null!=e&&t.indexOf(e)<0)&&e!=this.currentPageValue){var n=this.currentPageValue;this.currentPageValue=e,this.updateCustomWidgets(e),this.currentPageChanged(e,n)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentPageNo",{get:function(){return this.visiblePages.indexOf(this.currentPage)},set:function(e){this.visiblePages;e<0||e>=this.visiblePages.length||(this.currentPage=this.visiblePages[e])},enumerable:!0,configurable:!0}),t.prototype.focusFirstQuestion=function(){this.currentPageValue&&(this.currentPageValue.scrollToTop(),this.currentPageValue.focusFirstQuestion())},Object.defineProperty(t.prototype,"state",{get:function(){return this.isLoading?"loading":this.isCompleted?"completed":this.currentPage?"running":"empty"},enumerable:!0,configurable:!0}),t.prototype.clear=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!0),e&&(this.data=null,this.variablesHash={}),this.isCompleted=!1,t&&this.visiblePageCount>0&&(this.currentPage=this.visiblePages[0])},t.prototype.mergeValues=function(e,t){if(t&&e)for(var n in e){var r=e[n];r&&"object"==typeof r?(t[n]||(t[n]={}),this.mergeValues(r,t[n])):t[n]=r}},t.prototype.updateCustomWidgets=function(e){if(e)for(var t=0;t<e.questions.length;t++)e.questions[t].customWidget=p.a.Instance.getCustomWidget(e.questions[t])},t.prototype.currentPageChanged=function(e,t){this.onCurrentPageChanged.fire(this,{oldCurrentPage:t,newCurrentPage:e})},t.prototype.getProgress=function(){if(null==this.currentPage)return 0;var e=this.visiblePages.indexOf(this.currentPage)+1;return Math.ceil(100*e/this.visiblePageCount)},Object.defineProperty(t.prototype,"isNavigationButtonsShowing",{get:function(){if(this.isDesignMode)return!1;var e=this.currentPage;return!!e&&("show"==e.navigationButtonsVisibility||"hide"!=e.navigationButtonsVisibility&&this.showNavigationButtons)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isEditMode",{get:function(){return"edit"==this.mode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDisplayMode",{get:function(){return"display"==this.mode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDesignMode",{get:function(){return this.isDesignModeValue},enumerable:!0,configurable:!0}),t.prototype.setDesignMode=function(e){this.isDesignModeValue=e},Object.defineProperty(t.prototype,"hasCookie",{get:function(){if(!this.cookieName)return!1;var e=document.cookie;return e&&e.indexOf(this.cookieName+"=true")>-1},enumerable:!0,configurable:!0}),t.prototype.setCookie=function(){this.cookieName&&(document.cookie=this.cookieName+"=true; expires=Fri, 31 Dec 9999 0:0:0 GMT")},t.prototype.deleteCookie=function(){this.cookieName&&(document.cookie=this.cookieName+"=;")},t.prototype.nextPage=function(){return!this.isLastPage&&((!this.isEditMode||!this.isCurrentPageHasErrors)&&(!this.doServerValidation()&&(this.doNextPage(),!0)))},Object.defineProperty(t.prototype,"isCurrentPageHasErrors",{get:function(){return null==this.currentPage||this.currentPage.hasErrors(!0,!0)},enumerable:!0,configurable:!0}),t.prototype.prevPage=function(){if(this.isFirstPage)return!1;var e=this.visiblePages,t=e.indexOf(this.currentPage);this.currentPage=e[t-1]},t.prototype.completeLastPage=function(){return(!this.isEditMode||!this.isCurrentPageHasErrors)&&(!this.doServerValidation()&&(this.doComplete(),!0))},Object.defineProperty(t.prototype,"isFirstPage",{get:function(){return null==this.currentPage||0==this.visiblePages.indexOf(this.currentPage)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLastPage",{get:function(){if(null==this.currentPage)return!0;var e=this.visiblePages;return e.indexOf(this.currentPage)==e.length-1},enumerable:!0,configurable:!0}),t.prototype.doComplete=function(){this.clearUnusedValues(),this.setCookie(),this.setCompleted(),this.onComplete.fire(this,null),this.surveyPostId&&this.sendResult()},Object.defineProperty(t.prototype,"isValidatingOnServer",{get:function(){return this.isValidatingOnServerValue},enumerable:!0,configurable:!0}),t.prototype.setIsValidatingOnServer=function(e){e!=this.isValidatingOnServer&&(this.isValidatingOnServerValue=e,this.onIsValidatingOnServerChanged())},t.prototype.onIsValidatingOnServerChanged=function(){},t.prototype.doServerValidation=function(){if(!this.onServerValidateQuestions)return!1;for(var e=this,t={data:{},errors:{},survey:this,complete:function(){e.completeServerValidation(t)}},n=0;n<this.currentPage.questions.length;n++){var r=this.currentPage.questions[n];if(r.visible){var i=this.getValue(r.name);o.b.isValueEmpty(i)||(t.data[r.name]=i)}}return this.setIsValidatingOnServer(!0),this.onServerValidateQuestions(this,t),!0},t.prototype.completeServerValidation=function(e){if(this.setIsValidatingOnServer(!1),e||e.survey){var t=e.survey,n=!1;if(e.errors)for(var r in e.errors){var i=t.getQuestionByName(r);i&&i.errors&&(n=!0,i.addError(new h.c(e.errors[r])))}n||(t.isLastPage?t.doComplete():t.doNextPage())}},t.prototype.doNextPage=function(){this.checkOnPageTriggers(),this.sendResultOnPageNext&&this.sendResult(this.surveyPostId,this.clientId,!0);var e=this.visiblePages,t=e.indexOf(this.currentPage);this.currentPage=e[t+1]},t.prototype.setCompleted=function(){this.isCompleted=!0},Object.defineProperty(t.prototype,"processedCompletedHtml",{get:function(){return this.completedHtml?this.processHtml(this.completedHtml):"<h3>"+this.getLocString("completingSurvey")+"</h3>"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedLoadingHtml",{get:function(){return"<h3>"+this.getLocString("loadingSurvey")+"</h3>"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"progressText",{get:function(){if(null==this.currentPage)return"";var e=this.visiblePages,t=e.indexOf(this.currentPage)+1;return this.getLocString("progressText").format(t,e.length)},enumerable:!0,configurable:!0}),t.prototype.afterRenderSurvey=function(e){this.onAfterRenderSurvey.fire(this,{survey:this,htmlElement:e})},t.prototype.afterRenderPage=function(e){this.onAfterRenderPage.isEmpty||this.onAfterRenderPage.fire(this,{page:this.currentPage,htmlElement:e})},t.prototype.afterRenderQuestion=function(e,t){this.onAfterRenderQuestion.fire(this,{question:e,htmlElement:t})},t.prototype.afterRenderPanel=function(e,t){this.onAfterRenderPanel.fire(this,{panel:e,htmlElement:t})},t.prototype.uploadFile=function(e,t,n,r){var i=!0;return this.onUploadFile.fire(this,{name:e,file:t,accept:i}),!!i&&(!n&&this.surveyPostId&&this.uploadFileCore(e,t,r),!0)},t.prototype.uploadFileCore=function(e,t,n){var r=this;n&&n("uploading"),(new l.a).sendFile(this.surveyPostId,t,function(t,i){n&&n(t?"success":"error"),t&&r.setValue(e,i)})},t.prototype.getPage=function(e){return this.pages[e]},t.prototype.addPage=function(e){null!=e&&(this.pages.push(e),this.updateVisibleIndexes())},t.prototype.addNewPage=function(e){var t=this.createNewPage(e);return this.addPage(t),t},t.prototype.removePage=function(e){var t=this.pages.indexOf(e);t<0||(this.pages.splice(t,1),this.currentPageValue==e&&(this.currentPage=this.pages.length>0?this.pages[0]:null),this.updateVisibleIndexes())},t.prototype.getQuestionByName=function(e,t){void 0===t&&(t=!1);var n=this.getAllQuestions();t&&(e=e.toLowerCase());for(var r=0;r<n.length;r++){var i=n[r].name;if(t&&(i=i.toLowerCase()),i==e)return n[r]}return null},t.prototype.getQuestionsByNames=function(e,t){void 0===t&&(t=!1);var n=[];if(!e)return n;for(var r=0;r<e.length;r++)if(e[r]){var i=this.getQuestionByName(e[r],t);i&&n.push(i)}return n},t.prototype.getPageByElement=function(e){for(var t=0;t<this.pages.length;t++){var n=this.pages[t];if(n.containsElement(e))return n}return null},t.prototype.getPageByQuestion=function(e){return this.getPageByElement(e)},t.prototype.getPageByName=function(e){for(var t=0;t<this.pages.length;t++)if(this.pages[t].name==e)return this.pages[t];return null},t.prototype.getPagesByNames=function(e){var t=[];if(!e)return t;for(var n=0;n<e.length;n++)if(e[n]){var r=this.getPageByName(e[n]);r&&t.push(r)}return t},t.prototype.getAllQuestions=function(e){void 0===e&&(e=!1);for(var t=new Array,n=0;n<this.pages.length;n++)this.pages[n].addQuestionsToList(t,e);return t},t.prototype.createNewPage=function(e){return new s.a(e)},t.prototype.notifyQuestionOnValueChanged=function(e,t){for(var n=this.getAllQuestions(),r=null,i=0;i<n.length;i++)n[i].name==e&&(r=n[i],this.doSurveyValueChanged(r,t));this.onValueChanged.fire(this,{name:e,question:r,value:t})},t.prototype.notifyAllQuestionsOnValueChanged=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)this.doSurveyValueChanged(e[t],this.getValue(e[t].name))},t.prototype.doSurveyValueChanged=function(e,t){e.onSurveyValueChanged(t)},t.prototype.checkOnPageTriggers=function(){for(var e=this.getCurrentPageQuestions(),t=0;t<e.length;t++){var n=e[t],r=this.getValue(n.name);this.checkTriggers(n.name,r,!0)}},t.prototype.getCurrentPageQuestions=function(){var e=[],t=this.currentPage;if(!t)return e;for(var n=0;n<t.questions.length;n++){var r=t.questions[n];r.visible&&r.name&&e.push(r)}return e},t.prototype.checkTriggers=function(e,t,n){for(var r=0;r<this.triggers.length;r++){var i=this.triggers[r];i.name==e&&i.isOnNextPage==n&&i.check(t)}},t.prototype.doElementsOnLoad=function(){for(var e=0;e<this.pages.length;e++)this.pages[e].onSurveyLoad()},t.prototype.runConditions=function(){for(var e=this.pages,t=0;t<e.length;t++)e[t].runCondition(this.valuesHash)},t.prototype.sendResult=function(e,t,n){if(void 0===e&&(e=null),void 0===t&&(t=null),void 0===n&&(n=!1),this.isEditMode&&(n&&this.onPartialSend&&this.onPartialSend.fire(this,null),!e&&this.surveyPostId&&(e=this.surveyPostId),e&&(t&&(this.clientId=t),!n||this.clientId))){var r=this;(new l.a).sendResult(e,this.data,function(e,t){r.onSendResult.fire(r,{success:e,response:t})},this.clientId,n)}},t.prototype.getResult=function(e,t){var n=this;(new l.a).getResult(e,t,function(e,t,r,i){n.onGetResult.fire(n,{success:e,data:t,dataList:r,response:i})})},t.prototype.loadSurveyFromService=function(e){void 0===e&&(e=null),e&&(this.surveyId=e);var t=this;this.isLoading=!0,this.onLoadingSurveyFromService(),(new l.a).loadSurvey(this.surveyId,function(e,n,r){t.isLoading=!1,e&&n&&(t.setJsonObject(n),t.notifyAllQuestionsOnValueChanged(),t.onLoadSurveyFromService())})},t.prototype.onLoadingSurveyFromService=function(){},t.prototype.onLoadSurveyFromService=function(){},t.prototype.checkPageVisibility=function(e,t){var n=this.getPageByQuestion(e);if(n){var r=n.isVisible;(r!=n.getIsPageVisible(e)||t)&&this.pageVisibilityChanged(n,r)}},t.prototype.updateVisibleIndexes=function(){if(this.updatePageVisibleIndexes(this.showPageNumbers),"onPage"==this.showQuestionNumbers)for(var e=this.visiblePages,t=0;t<e.length;t++)this.updateQuestionVisibleIndexes(e[t].questions,!0);else this.updateQuestionVisibleIndexes(this.getAllQuestions(!1),"on"==this.showQuestionNumbers)},t.prototype.updatePageVisibleIndexes=function(e){for(var t=0,n=0;n<this.pages.length;n++)this.pages[n].visibleIndex=this.pages[n].visible?t++:-1,this.pages[n].num=e&&this.pages[n].visible?this.pages[n].visibleIndex+1:-1},t.prototype.updateQuestionVisibleIndexes=function(e,t){for(var n=0,r=0;r<e.length;r++)e[r].setVisibleIndex(t&&e[r].visible&&e[r].hasTitle?n++:-1)},Object.defineProperty(t.prototype,"isLoadingFromJson",{get:function(){return this.isLoadingFromJsonValue},enumerable:!0,configurable:!0}),t.prototype.setJsonObject=function(e){if(e){this.jsonErrors=null,this.isLoadingFromJsonValue=!0;var t=new i.a;t.toObject(e,this),t.errors.length>0&&(this.jsonErrors=t.errors),this.isLoadingFromJsonValue=!1,this.updateProcessedTextValues(),this.hasCookie&&this.doComplete(),this.doElementsOnLoad(),this.runConditions(),this.updateVisibleIndexes()}},t.prototype.onBeforeCreating=function(){},t.prototype.onCreating=function(){},t.prototype.updateProcessedTextValues=function(){this.processedTextValues={};var e=this;this.processedTextValues.pageno=function(t){return null!=e.currentPage?e.visiblePages.indexOf(e.currentPage)+1:0},this.processedTextValues.pagecount=function(t){return e.visiblePageCount};for(var t=this.getAllQuestions(),n=0;n<t.length;n++)this.addQuestionToProcessedTextValues(t[n])},t.prototype.addQuestionToProcessedTextValues=function(e){this.processedTextValues[e.name.toLowerCase()]="question"},t.prototype.hasProcessedTextValue=function(e){var t=(new u.a).getFirstName(e);return this.processedTextValues[t.toLowerCase()]},t.prototype.getProcessedTextValue=function(e){var t=(new u.a).getFirstName(e),n=this.processedTextValues[t.toLowerCase()];if(!n)return null;if("variable"==n)return this.getVariable(e.toLowerCase());if("question"==n){var r=this.getQuestionByName(t,!0);return r?(e=r.name+e.substr(t.length),(new u.a).getValue(e,this.valuesHash)):null}return"value"==n?(new u.a).getValue(e,this.valuesHash):n(e)},t.prototype.clearUnusedValues=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)e[t].clearUnusedValues();this.clearInvisibleValues&&this.clearInvisibleQuestionValues()},t.prototype.clearInvisibleQuestionValues=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)e[t].visible||this.clearValue(e[t].name)},t.prototype.getVariable=function(e){return e?this.variablesHash[e]:null},t.prototype.setVariable=function(e,t){e&&(this.variablesHash[e]=t,this.processedTextValues[e.toLowerCase()]="variable")},t.prototype.getUnbindValue=function(e){return e&&e instanceof Object?JSON.parse(JSON.stringify(e)):e},t.prototype.getValue=function(e){if(!e||0==e.length)return null;var t=this.valuesHash[e];return this.getUnbindValue(t)},t.prototype.setValue=function(e,t){this.isValueEqual(e,t)||(""===t||null===t?delete this.valuesHash[e]:(t=this.getUnbindValue(t),this.valuesHash[e]=t,this.processedTextValues[e.toLowerCase()]="value"),this.notifyQuestionOnValueChanged(e,t),this.checkTriggers(e,t,!1),this.runConditions(),this.tryGoNextPageAutomatic(e))},t.prototype.isValueEqual=function(e,t){""==t&&(t=null);var n=this.getValue(e);return null===t||null===n?t===n:this.isTwoValueEquals(t,n)},t.prototype.tryGoNextPageAutomatic=function(e){if(this.goNextPageAutomatic&&this.currentPage){var t=this.getQuestionByName(e);if(!t||t.visible&&t.supportGoNextPageAutomatic()){for(var n=this.getCurrentPageQuestions(),r=0;r<n.length;r++){var i=this.getValue(n[r].name);if(n[r].hasInput&&o.b.isValueEmpty(i))return}this.currentPage.hasErrors(!0,!1)||(this.isLastPage?this.doComplete():this.nextPage())}}},t.prototype.getComment=function(e){var t=this.data[e+this.commentPrefix];return null==t&&(t=""),t},t.prototype.setComment=function(e,t){var n=e+this.commentPrefix;""===t||null===t?delete this.valuesHash[n]:(this.valuesHash[n]=t,this.tryGoNextPageAutomatic(e));var r=this.getQuestionByName(e);r&&this.onValueChanged.fire(this,{name:n,question:r,value:t})},t.prototype.clearValue=function(e){this.setValue(e,null),this.setComment(e,null)},t.prototype.questionVisibilityChanged=function(e,t){this.updateVisibleIndexes(),this.onVisibleChanged.fire(this,{question:e,name:e.name,visible:t}),this.checkPageVisibility(e,!t)},t.prototype.pageVisibilityChanged=function(e,t){this.updateVisibleIndexes(),this.onPageVisibleChanged.fire(this,{page:e,visible:t})},t.prototype.questionAdded=function(e,t,n,r){this.updateVisibleIndexes(),this.addQuestionToProcessedTextValues(e),this.onQuestionAdded.fire(this,{question:e,name:e.name,index:t,parentPanel:n,rootPanel:r})},t.prototype.questionRemoved=function(e){this.updateVisibleIndexes(),this.onQuestionRemoved.fire(this,{question:e,name:e.name})},t.prototype.panelAdded=function(e,t,n,r){this.updateVisibleIndexes(),this.onPanelAdded.fire(this,{panel:e,name:e.name,index:t,parentPanel:n,rootPanel:r})},t.prototype.panelRemoved=function(e){this.updateVisibleIndexes(),this.onPanelRemoved.fire(this,{panel:e,name:e.name})},t.prototype.validateQuestion=function(e){if(this.onValidateQuestion.isEmpty)return null;var t={name:e,value:this.getValue(e),error:null};return this.onValidateQuestion.fire(this,t),t.error?new h.c(t.error):null},t.prototype.processHtml=function(e){var t={html:e};return this.onProcessHtml.fire(this,t),this.processText(t.html)},t.prototype.processText=function(e){return this.textPreProcessor.process(e)},t.prototype.getObjects=function(e,t){var n=[];return Array.prototype.push.apply(n,this.getPagesByNames(e)),Array.prototype.push.apply(n,this.getQuestionsByNames(t)),n},t.prototype.setTriggerValue=function(e,t,n){e&&(n?this.setVariable(e,t):this.setValue(e,t))},t}(o.b);i.a.metaData.addClass("survey",[{name:"locale",choices:function(){return c.a.getLocales()}},{name:"title",serializationProperty:"locTitle"},{name:"focusFirstQuestionAutomatic:boolean",default:!0},{name:"completedHtml:html",serializationProperty:"locCompletedHtml"},{name:"pages",className:"page",visible:!1},{name:"questions",baseClassName:"question",visible:!1,onGetValue:function(e){return null},onSetValue:function(e,t,n){var r=e.addNewPage("");n.toObject({questions:t},r)}},{name:"triggers:triggers",baseClassName:"surveytrigger",classNamePart:"trigger"},"surveyId","surveyPostId","cookieName","sendResultOnPageNext:boolean",{name:"showNavigationButtons:boolean",default:!0},{name:"showTitle:boolean",default:!0},{name:"showPageTitles:boolean",default:!0},{name:"showCompletedPage:boolean",default:!0},"showPageNumbers:boolean",{name:"showQuestionNumbers",default:"on",choices:["on","onPage","off"]},{name:"questionTitleLocation",default:"top",choices:["top","bottom"]},{name:"showProgressBar",default:"off",choices:["off","top","bottom"]},{name:"mode",default:"edit",choices:["edit","display"]},{name:"storeOthersAsComment:boolean",default:!0},"goNextPageAutomatic:boolean","clearInvisibleValues:boolean",{name:"pagePrevText",serializationProperty:"locPagePrevText"},{name:"pageNextText",serializationProperty:"locPageNextText"},{name:"completeText",serializationProperty:"locCompleteText"},{name:"requiredText",default:"*"},"questionStartIndex",{name:"questionTitleTemplate",serializationProperty:"locQuestionTitleTemplate"}])},function(e,t,n){"use strict";n.d(t,"a",function(){return i});var r=function(){function e(){}return e}(),i=function(){function e(){}return e.prototype.process=function(e){if(!e)return e;if(!this.onProcess)return e;for(var t=this.getItems(e),n=t.length-1;n>=0;n--){var r=t[n],i=this.getName(e.substring(r.start+1,r.end));if(this.canProcessName(i)&&(!this.onHasValue||this.onHasValue(i))){var o=this.onProcess(i);null==o&&(o=""),e=e.substr(0,r.start)+o+e.substr(r.end+1)}}return e},e.prototype.getItems=function(e){for(var t=[],n=e.length,i=-1,o="",s=0;s<n;s++)if(o=e[s],"{"==o&&(i=s),"}"==o){if(i>-1){var a=new r;a.start=i,a.end=s,t.push(a)}i=-1}return t},e.prototype.getName=function(e){if(e)return e.trim()},e.prototype.canProcessName=function(e){if(!e)return!1;for(var t=0;t<e.length;t++){var n=e[t];if(" "==n||"-"==n||"&"==n)return!1}return!0},e}()},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(9),s=n(1),a=n(2);n.d(t,"h",function(){return u}),n.d(t,"f",function(){return l}),n.d(t,"a",function(){return c}),n.d(t,"d",function(){return h}),n.d(t,"g",function(){return p}),n.d(t,"b",function(){return d}),n.d(t,"e",function(){return f}),n.d(t,"c",function(){return g});var u=function(){function e(e,t){void 0===t&&(t=null),this.value=e,this.error=t}return e}(),l=function(e){function t(){var t=e.call(this)||this;return t.text="",t}return r.b(t,e),t.prototype.getErrorText=function(e){return this.text?this.text:this.getDefaultErrorText(e)},t.prototype.getDefaultErrorText=function(e){return""},t.prototype.validate=function(e,t){return void 0===t&&(t=null),null},t}(i.b),c=function(){function e(){}return e.prototype.run=function(e){for(var t=0;t<e.validators.length;t++){var n=e.validators[t].validate(e.value,e.getValidatorTitle());if(null!=n){if(n.error)return n.error;n.value&&(e.value=n.value)}}return null},e}(),h=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;return r.minValue=t,r.maxValue=n,r}return r.b(t,e),t.prototype.getType=function(){return"numericvalidator"},t.prototype.validate=function(e,t){if(void 0===t&&(t=null),!e||!this.isNumber(e))return new u(null,new o.b);var n=new u(parseFloat(e));return this.minValue&&this.minValue>n.value?(n.error=new o.c(this.getErrorText(t)),n):this.maxValue&&this.maxValue<n.value?(n.error=new o.c(this.getErrorText(t)),n):"number"==typeof e?null:n},t.prototype.getDefaultErrorText=function(e){var t=e||"value";return this.minValue&&this.maxValue?s.a.getString("numericMinMax").format(t,this.minValue,this.maxValue):this.minValue?s.a.getString("numericMin").format(t,this.minValue):s.a.getString("numericMax").format(t,this.maxValue)},t.prototype.isNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},t}(l),p=function(e){function t(t,n){void 0===t&&(t=0),void 0===n&&(n=0);var r=e.call(this)||this;return r.minLength=t,r.maxLength=n,r}return r.b(t,e),t.prototype.getType=function(){return"textvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),this.minLength>0&&e.length<this.minLength?new u(null,new o.c(this.getErrorText(t))):this.maxLength>0&&e.length>this.maxLength?new u(null,new o.c(this.getErrorText(t))):null},t.prototype.getDefaultErrorText=function(e){return this.minLength>0&&this.maxLength>0?s.a.getString("textMinMaxLength").format(this.minLength,this.maxLength):this.minLength>0?s.a.getString("textMinLength").format(this.minLength):s.a.getString("textMaxLength").format(this.maxLength)},t}(l),d=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;return r.minCount=t,r.maxCount=n,r}return r.b(t,e),t.prototype.getType=function(){return"answercountvalidator"},t.prototype.validate=function(e,t){if(void 0===t&&(t=null),null==e||e.constructor!=Array)return null;var n=e.length;return this.minCount&&n<this.minCount?new u(null,new o.c(this.getErrorText(s.a.getString("minSelectError").format(this.minCount)))):this.maxCount&&n>this.maxCount?new u(null,new o.c(this.getErrorText(s.a.getString("maxSelectError").format(this.maxCount)))):null},t.prototype.getDefaultErrorText=function(e){return e},t}(l),f=function(e){function t(t){void 0===t&&(t=null);var n=e.call(this)||this;return n.regex=t,n}return r.b(t,e),t.prototype.getType=function(){return"regexvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),this.regex&&e?new RegExp(this.regex).test(e)?null:new u(e,new o.c(this.getErrorText(t))):null},t}(l),g=function(e){function t(){var t=e.call(this)||this;return t.re=/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i,t}return r.b(t,e),t.prototype.getType=function(){return"emailvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),e?this.re.test(e)?null:new u(e,new o.c(this.getErrorText(t))):null},t.prototype.getDefaultErrorText=function(e){return s.a.getString("invalidEmail")},t}(l);a.a.metaData.addClass("surveyvalidator",["text"]),a.a.metaData.addClass("numericvalidator",["minValue:number","maxValue:number"],function(){return new h},"surveyvalidator"),a.a.metaData.addClass("textvalidator",["minLength:number","maxLength:number"],function(){return new p},"surveyvalidator"),a.a.metaData.addClass("answercountvalidator",["minCount:number","maxCount:number"],function(){return new d},"surveyvalidator"),a.a.metaData.addClass("regexvalidator",["regex"],function(){return new f},"surveyvalidator"),a.a.metaData.addClass("emailvalidator",[],function(){return new g},"surveyvalidator")},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(15)),s=n(29),a=n(27),u=n(5),l=n(17),c=n(28),h=n(6),p=n(4);n.d(t,"a",function(){return d});var d=function(e){function t(t){var n=e.call(this,t)||this;return n.isCurrentPageChanged=!1,n.updateSurvey(t),n}return r.b(t,e),Object.defineProperty(t,"cssType",{get:function(){return l.b.currentType},set:function(e){l.b.currentType=e},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(e){this.updateSurvey(e)},t.prototype.componentDidUpdate=function(){this.isCurrentPageChanged&&(this.isCurrentPageChanged=!1,this.survey.focusFirstQuestionAutomatic&&this.survey.focusFirstQuestion())},t.prototype.componentDidMount=function(){var e=this.refs.root;e&&this.survey&&this.survey.doAfterRenderSurvey(e)},t.prototype.render=function(){return"completed"==this.survey.state?this.renderCompleted():"loading"==this.survey.state?this.renderLoading():this.renderSurvey()},Object.defineProperty(t.prototype,"css",{get:function(){return l.b.getCss()},set:function(e){this.survey.mergeCss(e,this.css)},enumerable:!0,configurable:!0}),t.prototype.renderCompleted=function(){if(!this.survey.showCompletedPage)return null;var e={__html:this.survey.processedCompletedHtml};return i.createElement("div",{dangerouslySetInnerHTML:e})},t.prototype.renderLoading=function(){var e={__html:this.survey.processedLoadingHtml};return i.createElement("div",{dangerouslySetInnerHTML:e})},t.prototype.renderSurvey=function(){var e=this.survey.title&&this.survey.showTitle?this.renderTitle():null,t=this.survey.currentPage?this.renderPage():null,n="top"==this.survey.showProgressBar?this.renderProgress(!0):null,r="bottom"==this.survey.showProgressBar?this.renderProgress(!1):null,o=t&&this.survey.showNavigationButtons?this.renderNavigation():null;return t||(t=this.renderEmptySurvey()),i.createElement("div",{ref:"root",className:this.css.root},e,i.createElement("div",{id:h.e,className:this.css.body},n,t,r),o)},t.prototype.renderTitle=function(){var e=p.a.renderLocString(this.survey.locTitle);return i.createElement("div",{className:this.css.header},i.createElement("h3",null,e))},t.prototype.renderPage=function(){return i.createElement(s.a,{survey:this.survey,page:this.survey.currentPage,css:this.css,creator:this})},t.prototype.renderProgress=function(e){return i.createElement(c.a,{survey:this.survey,css:this.css,isTop:e})},t.prototype.renderNavigation=function(){return i.createElement(a.a,{survey:this.survey,css:this.css})},t.prototype.renderEmptySurvey=function(){return i.createElement("span",null,this.survey.emptySurveyText)},t.prototype.updateSurvey=function(e){e?e.model?this.survey=e.model:e.json&&(this.survey=new o.a(e.json)):this.survey=new o.a,e&&(e.clientId&&(this.survey.clientId=e.clientId),e.data&&(this.survey.data=e.data),e.css&&this.survey.mergeCss(e.css,this.css));this.survey.currentPage;this.state={pageIndexChange:0,isCompleted:!1,modelChanged:0},this.setSurveyEvents(e)},t.prototype.setSurveyEvents=function(e){var t=this;this.survey.renderCallback=function(){t.state.modelChanged=t.state.modelChanged+1,t.setState(t.state)},this.survey.onComplete.add(function(e){t.state.isCompleted=!0,t.setState(t.state)}),this.survey.onPartialSend.add(function(e){t.setState(t.state)}),this.survey.onCurrentPageChanged.add(function(n,r){t.isCurrentPageChanged=!0,t.state.pageIndexChange=t.state.pageIndexChange+1,t.setState(t.state),e&&e.onCurrentPageChanged&&e.onCurrentPageChanged(n,r)}),this.survey.onVisibleChanged.add(function(e,t){if(t.question&&t.question.react){var n=t.question.react.state;n.visible=t.question.visible,t.question.react.setState(n)}}),this.survey.onValueChanged.add(function(e,t){if(t.question&&t.question.react){var n=t.question.react.state;n.value=t.value,t.question.react.setState(n)}}),e&&(this.survey.onValueChanged.add(function(t,n){e.data&&(e.data[n.name]=n.value),e.onValueChanged&&e.onValueChanged(t,n)}),e.onComplete&&this.survey.onComplete.add(function(t){e.onComplete(t)}),e.onPartialSend&&this.survey.onPartialSend.add(function(t){e.onPartialSend(t)}),this.survey.onPageVisibleChanged.add(function(t,n){e.onPageVisibleChanged&&e.onPageVisibleChanged(t,n)}),e.onServerValidateQuestions&&(this.survey.onServerValidateQuestions=e.onServerValidateQuestions),e.onQuestionAdded&&this.survey.onQuestionAdded.add(function(t,n){e.onQuestionAdded(t,n)}),e.onQuestionRemoved&&this.survey.onQuestionRemoved.add(function(t,n){e.onQuestionRemoved(t,n)}),e.onValidateQuestion&&this.survey.onValidateQuestion.add(function(t,n){e.onValidateQuestion(t,n)}),e.onSendResult&&this.survey.onSendResult.add(function(t,n){e.onSendResult(t,n)}),e.onGetResult&&this.survey.onGetResult.add(function(t,n){e.onGetResult(t,n)}),e.onProcessHtml&&this.survey.onProcessHtml.add(function(t,n){e.onProcessHtml(t,n)}),e.onAfterRenderSurvey&&this.survey.onAfterRenderSurvey.add(function(t,n){e.onAfterRenderSurvey(t,n)}),e.onAfterRenderPage&&this.survey.onAfterRenderPage.add(function(t,n){e.onAfterRenderPage(t,n)}),e.onAfterRenderQuestion&&this.survey.onAfterRenderQuestion.add(function(t,n){e.onAfterRenderQuestion(t,n)}),e.onTextMarkdown&&this.survey.onTextMarkdown.add(function(t,n){e.onTextMarkdown(t,n)}))},t.prototype.createQuestionElement=function(e){var t=this.css[e.getType()];return u.a.Instance.createQuestion(e.getType(),{question:e,css:t,rootCss:this.css,isDisplayMode:e.isReadOnly,creator:this})},t.prototype.renderError=function(e,t){return i.createElement("div",{key:e,className:this.css.error.item},t)},t.prototype.questionTitleLocation=function(){return this.survey.questionTitleLocation},t}(i.Component)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(18));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.handlePrevClick=n.handlePrevClick.bind(n),n.handleNextClick=n.handleNextClick.bind(n),n.handleCompleteClick=n.handleCompleteClick.bind(n),n}return r.b(t,e),t.prototype.handlePrevClick=function(e){this.survey.prevPage()},t.prototype.handleNextClick=function(e){this.survey.nextPage()},t.prototype.handleCompleteClick=function(e){this.survey.completeLastPage()},t.prototype.render=function(){if(!this.survey||!this.survey.isNavigationButtonsShowing)return null;var e=this.survey.isFirstPage?null:this.renderButton(this.handlePrevClick,this.survey.pagePrevText,this.css.navigation.prev),t=this.survey.isLastPage?null:this.renderButton(this.handleNextClick,this.survey.pageNextText,this.css.navigation.next),n=this.survey.isLastPage&&this.survey.isEditMode?this.renderButton(this.handleCompleteClick,this.survey.completeText,this.css.navigation.complete):null;return i.createElement("div",{className:this.css.footer},e,t,n)},t.prototype.renderButton=function(e,t,n){var r={marginRight:"5px"},o=this.css.navigationButton+(n?" "+n:"");return i.createElement("input",{className:o,style:r,type:"button",onClick:e,value:t})},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(18));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.isTop=t.isTop,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.isTop=t.isTop},Object.defineProperty(t.prototype,"progress",{get:function(){return this.survey.getProgress()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"progressText",{get:function(){return this.survey.progressText},enumerable:!0,configurable:!0}),t.prototype.render=function(){var e=this.isTop?{width:"60%"}:{width:"60%",marginTop:"10px"},t={width:this.progress+"%"};return i.createElement("div",{className:this.css.progress,style:e},i.createElement("div",{style:t,className:this.css.progressBar,role:"progressbar","aria-valuemin":"0","aria-valuemax":"100"},i.createElement("span",null,this.progressText)))},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(14)),s=n(4);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return l});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.page=t.page,n.survey=t.survey,n.creator=t.creator,n.css=t.css,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.page=e.page,this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.componentDidMount=function(){var e=this.refs.root;e&&this.survey&&this.survey.afterRenderPage(e)},t.prototype.render=function(){if(null==this.page||null==this.survey||null==this.creator)return null;for(var e=this.renderTitle(),t=[],n=this.page.rows,r=0;r<n.length;r++)t.push(this.createRow(n[r],r));return i.createElement("div",{ref:"root"},e,t)},t.prototype.createRow=function(e,t){var n="row"+(t+1);return i.createElement(l,{key:n,row:e,survey:this.survey,creator:this.creator,css:this.css})},t.prototype.renderTitle=function(){if(!this.page.title||!this.survey.showPageTitles)return null;var e=s.a.renderLocString(this.page.locTitle);return i.createElement("h4",{className:this.css.pageTitle},e)},t}(i.Component),u=function(e){function t(t){var n=e.call(this,t)||this;return n.panel=t.panel,n.survey=t.survey,n.creator=t.creator,n.css=t.css,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.panel=e.panel,this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.componentDidMount=function(){var e=this.refs.root;e&&this.survey&&this.survey.afterRenderPage(e)},t.prototype.render=function(){if(null==this.panel||null==this.survey||null==this.creator)return null;for(var e=this.renderTitle(),t=[],n=this.panel.rows,r=0;r<n.length;r++)t.push(this.createRow(n[r],r));var o={marginLeft:this.panel.innerIndent*this.css.question.indent+"px"};return i.createElement("div",{ref:"root"},e,i.createElement("div",{style:o},t))},t.prototype.createRow=function(e,t){var n="row"+(t+1);return i.createElement(l,{key:n,row:e,survey:this.survey,creator:this.creator,css:this.css})},t.prototype.renderTitle=function(){if(!this.panel.title)return null;var e=s.a.renderLocString(this.panel.locTitle);return i.createElement("h4",{className:this.css.pageTitle},e)},t}(i.Component),l=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.setProperties(e)},t.prototype.setProperties=function(e){if(this.row=e.row,this.row){var t=this;this.row.visibilityChangedCallback=function(){t.setState({visible:t.row.visible})}}this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.render=function(){if(null==this.row||null==this.survey||null==this.creator)return null;var e=null;if(this.row.visible){e=[];for(var t=0;t<this.row.elements.length;t++){var n=this.row.elements[t];e.push(this.createQuestion(n))}}var r=this.row.visible?{}:{display:"none"};return i.createElement("div",{className:this.css.row,style:r},e)},t.prototype.createQuestion=function(e){return e.isPanel?i.createElement(u,{key:e.name,panel:e,creator:this.creator,survey:this.survey,css:this.css}):i.createElement(o.a,{key:e.name,question:e,creator:this.creator,css:this.css})},t}(i.Component)},function(e,t,n){"use strict";var r=n(16);n.d(t,"a",function(){return i});var i=function(){function e(){}return e.prototype.parse=function(e,t){return this.text=e,this.root=t,this.root.clear(),this.at=0,this.length=this.text.length,this.parseText()},e.prototype.toString=function(e){return this.root=e,this.nodeToString(e)},e.prototype.toStringCore=function(e){return e?e.children?this.nodeToString(e):e.left?this.conditionToString(e):"":""},e.prototype.nodeToString=function(e){if(e.isEmpty)return"";for(var t="",n=0;n<e.children.length;n++){var r=this.toStringCore(e.children[n]);r&&(t&&(t+=" "+e.connective+" "),t+=r)}return e!=this.root&&e.children.length>1&&(t="("+t+")"),t},e.prototype.conditionToString=function(e){if(!e.right||!e.operator)return"";var t=e.left;t&&!this.isNumeric(t)&&(t="'"+t+"'");var n=t+" "+this.operationToString(e.operator);if(this.isNoRightOperation(e.operator))return n;var r=e.right;return r&&!this.isNumeric(r)&&(r="'"+r+"'"),n+" "+r},e.prototype.operationToString=function(e){return"equal"==e?"=":"notequal"==e?"!=":"greater"==e?">":"less"==e?"<":"greaterorequal"==e?">=":"lessorequal"==e?"<=":e},e.prototype.isNumeric=function(e){var t=parseFloat(e);return!isNaN(t)&&isFinite(t)},e.prototype.parseText=function(){return this.node=this.root,this.expressionNodes=[],this.expressionNodes.push(this.node),this.readConditions()&&this.at>=this.length},e.prototype.readConditions=function(){var e=this.readCondition();if(!e)return e;var t=this.readConnective();return!t||(this.addConnective(t),this.readConditions())},e.prototype.readCondition=function(){var e=this.readExpression();if(e<0)return!1;if(1==e)return!0;var t=this.readString();if(!t)return!1;var n=this.readOperator();if(!n)return!1;var i=new r.b;if(i.left=t,i.operator=n,!this.isNoRightOperation(n)){var o=this.readString();if(!o)return!1;i.right=o}return this.addCondition(i),!0},e.prototype.readExpression=function(){if(this.skip(),this.at>=this.length||"("!=this.ch)return 0;this.at++,this.pushExpression();var e=this.readConditions();return e?(this.skip(),e=")"==this.ch,this.at++,this.popExpression(),1):-1},Object.defineProperty(e.prototype,"ch",{get:function(){return this.text.charAt(this.at)},enumerable:!0,configurable:!0}),e.prototype.skip=function(){for(;this.at<this.length&&this.isSpace(this.ch);)this.at++},e.prototype.isSpace=function(e){return" "==e||"\n"==e||"\t"==e||"\r"==e},e.prototype.isQuotes=function(e){return"'"==e||'"'==e},e.prototype.isOperatorChar=function(e){return">"==e||"<"==e||"="==e||"!"==e},e.prototype.isBrackets=function(e){return"("==e||")"==e},e.prototype.readString=function(){if(this.skip(),this.at>=this.length)return null;var e=this.at,t=this.isQuotes(this.ch);t&&this.at++;for(var n=this.isOperatorChar(this.ch);this.at<this.length&&(t||!this.isSpace(this.ch));){if(this.isQuotes(this.ch)){t&&this.at++;break}if(!t){if(n!=this.isOperatorChar(this.ch))break;if(this.isBrackets(this.ch))break}this.at++}if(this.at<=e)return null;var r=this.text.substr(e,this.at-e);if(r&&r.length>1&&this.isQuotes(r[0])){var i=r.length-1;this.isQuotes(r[r.length-1])&&i--,r=r.substr(1,i)}return r},e.prototype.isNoRightOperation=function(e){return"empty"==e||"notempty"==e},e.prototype.readOperator=function(){var e=this.readString();return e?(e=e.toLowerCase(),">"==e&&(e="greater"),"<"==e&&(e="less"),">="!=e&&"=>"!=e||(e="greaterorequal"),"<="!=e&&"=<"!=e||(e="lessorequal"),"="!=e&&"=="!=e||(e="equal"),"<>"!=e&&"!="!=e||(e="notequal"),"contain"==e&&(e="contains"),"notcontain"==e&&(e="notcontains"),e):null},e.prototype.readConnective=function(){var e=this.readString();return e?(e=e.toLowerCase(),"&"!=e&&"&&"!=e||(e="and"),"|"!=e&&"||"!=e||(e="or"),"and"!=e&&"or"!=e&&(e=null),e):null},e.prototype.pushExpression=function(){var e=new r.c;this.expressionNodes.push(e),this.node=e},e.prototype.popExpression=function(){var e=this.expressionNodes.pop();this.node=this.expressionNodes[this.expressionNodes.length-1],this.node.children.push(e)},e.prototype.addCondition=function(e){this.node.children.push(e)},e.prototype.addConnective=function(e){if(this.node.children.length<2)this.node.connective=e;else if(this.node.connective!=e){var t=this.node.connective,n=this.node.children;this.node.clear(),this.node.connective=e;var i=new r.c;i.connective=t,i.children=n,this.node.children.push(i);var o=new r.c;this.node.children.push(o),this.node=o}},e}()},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){}return e.prototype.loadSurvey=function(t,n){var r=new XMLHttpRequest;r.open("GET",e.serviceUrl+"/getSurvey?surveyId="+t),r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.onload=function(){var e=JSON.parse(r.response);n(200==r.status,e,r.response)},r.send()},e.prototype.sendResult=function(t,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=!1);var s=new XMLHttpRequest;s.open("POST",e.serviceUrl+"/post/"),s.setRequestHeader("Content-Type","application/json; charset=utf-8");var a={postId:t,surveyResult:JSON.stringify(n)};i&&(a.clientId=i),o&&(a.isPartialCompleted=!0);var u=JSON.stringify(a);s.onload=s.onerror=function(){r&&r(200==s.status,s.response)},s.send(u)},e.prototype.sendFile=function(t,n,r){var i=new XMLHttpRequest;i.onload=i.onerror=function(){r&&r(200==i.status,JSON.parse(i.response))},i.open("POST",e.serviceUrl+"/upload/",!0);var o=new FormData;o.append("file",n),o.append("postId",t),i.send(o)},e.prototype.getResult=function(t,n,r){var i=new XMLHttpRequest,o="resultId="+t+"&name="+n;i.open("GET",e.serviceUrl+"/getResult?"+o),i.setRequestHeader("Content-Type","application/x-www-form-urlencoded");i.onload=function(){var e=null,t=null;if(200==i.status){e=JSON.parse(i.response),t=[];for(var n in e.QuestionResult){var o={name:n,value:e.QuestionResult[n]};t.push(o)}}r(200==i.status,e,t,i.response)},i.send()},e.prototype.isCompleted=function(t,n,r){var i=new XMLHttpRequest,o="resultId="+t+"&clientId="+n;i.open("GET",e.serviceUrl+"/isCompleted?"+o),i.setRequestHeader("Content-Type","application/x-www-form-urlencoded");i.onload=function(){var e=null;200==i.status&&(e=JSON.parse(i.response)),r(200==i.status,e,i.response)},i.send()},e}();r.serviceUrl="https://dxsurveyapi.azurewebsites.net/api/Survey"},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(33);n.d(t,"a",function(){return a});var a=function(e){function t(t){void 0===t&&(t="");var n=e.call(this,t)||this;return n.name=t,n.numValue=-1,n.navigationButtonsVisibility="inherit",n}return r.b(t,e),t.prototype.getType=function(){return"page"},Object.defineProperty(t.prototype,"num",{get:function(){return this.numValue},set:function(e){this.numValue!=e&&(this.numValue=e,this.onNumChanged(e))},enumerable:!0,configurable:!0}),t.prototype.getRendredTitle=function(t){return t=e.prototype.getRendredTitle.call(this,t),this.num>0&&(t=this.num+". "+t),t},t.prototype.focusFirstQuestion=function(){for(var e=0;e<this.questions.length;e++){var t=this.questions[e];if(t.visible&&t.hasInput){this.questions[e].focus();break}}},t.prototype.focusFirstErrorQuestion=function(){for(var e=0;e<this.questions.length;e++)if(this.questions[e].visible&&0!=this.questions[e].currentErrorCount){this.questions[e].focus(!0);break}},t.prototype.scrollToTop=function(){o.a.ScrollElementToTop(o.e)},t.prototype.onNumChanged=function(e){},t.prototype.onVisibleChanged=function(){e.prototype.onVisibleChanged.call(this),null!=this.data&&this.data.pageVisibilityChanged(this,this.visible)},t}(s.a);i.a.metaData.addClass("page",[{name:"navigationButtonsVisibility",default:"inherit",choices:["iherit","show","hide"]}],function(){return new a},"panel")},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(16),a=n(7),u=n(8);n.d(t,"c",function(){return l}),n.d(t,"a",function(){return c}),n.d(t,"b",function(){return h});var l=function(){function e(e){this.panel=e,this.elements=[],this.visibleValue=e.data&&e.data.isDesignMode}return Object.defineProperty(e.prototype,"questions",{get:function(){return this.elements},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!=this.visible&&(this.visibleValue=e,this.onVisibleChanged())},enumerable:!0,configurable:!0}),e.prototype.updateVisible=function(){this.visible=this.calcVisible(),this.setWidth()},e.prototype.addElement=function(e){this.elements.push(e),this.updateVisible()},e.prototype.onVisibleChanged=function(){this.visibilityChangedCallback&&this.visibilityChangedCallback()},e.prototype.setWidth=function(){var e=this.getVisibleCount();if(0!=e)for(var t=0,n=0;n<this.elements.length;n++)if(this.elements[n].isVisible){var r=this.elements[n];r.renderWidth=r.width?r.width:Math.floor(100/e)+"%",r.rightIndent=t<e-1?1:0,t++}},e.prototype.getVisibleCount=function(){for(var e=0,t=0;t<this.elements.length;t++)this.elements[t].isVisible&&e++;return e},e.prototype.calcVisible=function(){return this.getVisibleCount()>0},e}(),c=function(e){function t(n){void 0===n&&(n="");var r=e.call(this)||this;r.name=n,r.dataValue=null,r.rowValues=null,r.conditionRunner=null,r.elementsValue=new Array,r.isQuestionsReady=!1,r.questionsValue=new Array,r.parent=null,r.visibleIf="",r.visibleIndex=-1,r.visibleValue=!0,r.idValue=t.getPanelId(),r.locTitleValue=new u.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getRendredTitle(e)},r.elementsValue.push=function(e){return i.doOnPushElement(this,e)},r.elementsValue.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return i.doSpliceElements.apply(i,[this,e,t].concat(n))},r}return r.b(t,e),t.getPanelId=function(){return"sp_"+t.panelCounter++},Object.defineProperty(t.prototype,"data",{get:function(){return this.dataValue},set:function(e){if(this.dataValue!==e){this.dataValue=e;for(var t=0;t<this.elements.length;t++)this.elements[t].setData(e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},Object.defineProperty(t.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isPanel",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questions",{get:function(){if(!this.isQuestionsReady){this.questionsValue=[];for(var e=0;e<this.elements.length;e++){var t=this.elements[e];if(t.isPanel)for(var n=t.questions,r=0;r<n.length;r++)this.questionsValue.push(n[r]);else this.questionsValue.push(t)}this.isQuestionsReady=!0}return this.questionsValue},enumerable:!0,configurable:!0}),t.prototype.markQuestionListDirty=function(){this.isQuestionsReady=!1,this.parent&&this.parent.markQuestionListDirty()},Object.defineProperty(t.prototype,"elements",{get:function(){return this.elementsValue},enumerable:!0,configurable:!0}),t.prototype.containsElement=function(e){for(var t=0;t<this.elements.length;t++){var n=this.elements[t];if(n==e)return!0;if(n.isPanel&&n.containsElement(e))return!0}return!1},t.prototype.hasErrors=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!1);var n=!1,r=null,i=[];this.addQuestionsToList(i,!0);for(var o=0;o<i.length;o++){var s=i[o];s.isReadOnly||s.hasErrors(e)&&(t&&null==r&&(r=s),n=!0)}return r&&r.focus(!0),n},t.prototype.addQuestionsToList=function(e,t){if(void 0===t&&(t=!1),!t||this.visible)for(var n=0;n<this.elements.length;n++){var r=this.elements[n];t&&!r.visible||(r.isPanel?r.addQuestionsToList(e,t):e.push(r))}},Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowValues||(this.rowValues=this.buildRows()),this.rowValues},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isActive",{get:function(){return!this.data||this.data.currentPage==this.root},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){for(var e=this;e.parent;)e=e.parent;return e},enumerable:!0,configurable:!0}),t.prototype.createRow=function(){return new l(this)},t.prototype.onSurveyLoad=function(){for(var e=0;e<this.elements.length;e++)this.elements[e].onSurveyLoad();this.rowsChangedCallback&&this.rowsChangedCallback()},Object.defineProperty(t.prototype,"isLoadingFromJson",{get:function(){return this.data&&this.data.isLoadingFromJson},enumerable:!0,configurable:!0}),t.prototype.onRowsChanged=function(){this.rowValues=null,this.rowsChangedCallback&&!this.isLoadingFromJson&&this.rowsChangedCallback()},Object.defineProperty(t.prototype,"isDesignMode",{get:function(){return this.data&&this.data.isDesignMode},enumerable:!0,configurable:!0}),t.prototype.doOnPushElement=function(e,t){var n=Array.prototype.push.call(e,t);return this.markQuestionListDirty(),this.onAddElement(t,e.length),this.onRowsChanged(),n},t.prototype.doSpliceElements=function(e,t,n){for(var r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];t||(t=0),n||(n=0);for(var o=[],s=0;s<n;s++)s+t>=e.length||o.push(e[s+t]);var a=(u=Array.prototype.splice).call.apply(u,[e,t,n].concat(r));this.markQuestionListDirty(),r||(r=[]);for(var s=0;s<o.length;s++)this.onRemoveElement(o[s]);for(var s=0;s<r.length;s++)this.onAddElement(r[s],t+s);return this.onRowsChanged(),a;var u},t.prototype.onAddElement=function(e,t){if(e.isPanel){var n=e;n.data=this.data,n.parent=this,this.data&&this.data.panelAdded(n,t,this,this.root)}else if(this.data){var r=e;r.setData(this.data),this.data.questionAdded(r,t,this,this.root)}var i=this;e.rowVisibilityChangedCallback=function(){i.onElementVisibilityChanged(e)},e.startWithNewLineChangedCallback=function(){i.onElementStartWithNewLineChanged(e)}},t.prototype.onRemoveElement=function(e){e.isPanel?this.data&&this.data.panelRemoved(e):this.data&&this.data.questionRemoved(e)},t.prototype.onElementVisibilityChanged=function(e){this.rowValues&&this.updateRowsVisibility(e),this.parent&&this.parent.onElementVisibilityChanged(this)},t.prototype.onElementStartWithNewLineChanged=function(e){this.onRowsChanged()},t.prototype.updateRowsVisibility=function(e){for(var t=0;t<this.rowValues.length;t++){var n=this.rowValues[t];if(n.elements.indexOf(e)>-1){n.updateVisible();break}}},t.prototype.buildRows=function(){for(var e=new Array,t=0;t<this.elements.length;t++){var n=this.elements[t],r=0==t||n.startWithNewLine,i=r?this.createRow():e[e.length-1];r&&e.push(i),i.addElement(n)}for(var t=0;t<e.length;t++)e[t].updateVisible();return e},Object.defineProperty(t.prototype,"processedTitle",{get:function(){return this.getRendredTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getRendredTitle=function(e){return!e&&this.isPanel&&this.isDesignMode?"["+this.name+"]":null!=this.data?this.data.processText(e):e},Object.defineProperty(t.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!==this.visible&&(this.visibleValue=e,this.onVisibleChanged())},enumerable:!0,configurable:!0}),t.prototype.onVisibleChanged=function(){},Object.defineProperty(t.prototype,"isVisible",{get:function(){return this.data&&this.data.isDesignMode||this.getIsPageVisible(null)},enumerable:!0,configurable:!0}),t.prototype.getIsPageVisible=function(e){if(!this.visible)return!1;for(var t=0;t<this.questions.length;t++)if(this.questions[t]!=e&&this.questions[t].visible)return!0;return!1},t.prototype.addElement=function(e,t){void 0===t&&(t=-1),null!=e&&(t<0||t>=this.elements.length?this.elements.push(e):this.elements.splice(t,0,e))},t.prototype.addQuestion=function(e,t){void 0===t&&(t=-1),this.addElement(e,t)},t.prototype.addPanel=function(e,t){void 0===t&&(t=-1),this.addElement(e,t)},t.prototype.addNewQuestion=function(e,t){var n=a.a.Instance.createQuestion(e,t);return this.addQuestion(n),n},t.prototype.addNewPanel=function(e){var t=this.createNewPanel(e);return this.addPanel(t),t},t.prototype.createNewPanel=function(e){return new h(e)},t.prototype.removeElement=function(e){var t=this.elements.indexOf(e);if(t<0){for(var n=0;n<this.elements.length;n++){var r=this.elements[n];if(r.isPanel&&r.removeElement(e))return!0}return!1}return this.elements.splice(t,1),!0},t.prototype.removeQuestion=function(e){this.removeElement(e)},t.prototype.runCondition=function(e){for(var t=0;t<this.elements.length;t++)this.elements[t].runCondition(e);this.visibleIf&&(this.conditionRunner||(this.conditionRunner=new s.a(this.visibleIf)),this.conditionRunner.expression=this.visibleIf,this.visible=this.conditionRunner.run(e))},t.prototype.onLocaleChanged=function(){for(var e=0;e<this.elements.length;e++)this.elements[e].onLocaleChanged();this.locTitle.onChanged()},t}(o.b);c.panelCounter=100;var h=function(e){function t(t){void 0===t&&(t="");var n=e.call(this,t)||this;return n.name=t,n.innerIndentValue=0,n.startWithNewLineValue=!0,n}return r.b(t,e),t.prototype.getType=function(){return"panel"},t.prototype.setData=function(e){this.data=e},Object.defineProperty(t.prototype,"isPanel",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"innerIndent",{get:function(){return this.innerIndentValue},set:function(e){e!=this.innerIndentValue&&(this.innerIndentValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderWidth",{get:function(){return this.renderWidthValue},set:function(e){e!=this.renderWidth&&(this.renderWidthValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startWithNewLine",{get:function(){return this.startWithNewLineValue},set:function(e){this.startWithNewLine!=e&&(this.startWithNewLineValue=e,this.startWithNewLineChangedCallback&&this.startWithNewLineChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightIndent",{get:function(){return this.rightIndentValue},set:function(e){e!=this.rightIndent&&(this.rightIndentValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),t.prototype.onVisibleChanged=function(){this.rowVisibilityChangedCallback&&this.rowVisibilityChangedCallback()},t}(c);i.a.metaData.addClass("panel",["name",{name:"elements",alternativeName:"questions",baseClassName:"question",visible:!1},{name:"visible:boolean",default:!0},"visibleIf:expression",{name:"title:text",serializationProperty:"locTitle"},{name:"innerIndent:number",default:0,choices:[0,1,2,3]}],function(){return new h})},function(e,t,n){"use strict";var r=n(6);n.d(t,"b",function(){return i}),n.d(t,"a",function(){return o});var i=function(){function e(e,t){this.name=e,this.widgetJson=t,this.htmlTemplate=t.htmlTemplate?t.htmlTemplate:""}return e.prototype.afterRender=function(e,t){this.widgetJson.afterRender&&this.widgetJson.afterRender(e,t)},e.prototype.willUnmount=function(e,t){this.widgetJson.willUnmount&&this.widgetJson.willUnmount(e,t)},e.prototype.isFit=function(e){return!!this.widgetJson.isFit&&this.widgetJson.isFit(e)},e}(),o=function(){function e(){this.widgetsValues=[],this.onCustomWidgetAdded=new r.c}return Object.defineProperty(e.prototype,"widgets",{get:function(){return this.widgetsValues},enumerable:!0,configurable:!0}),e.prototype.addCustomWidget=function(e){var t=e.name;t||(t="widget_"+this.widgets.length+1);var n=new i(t,e);this.widgetsValues.push(n),this.onCustomWidgetAdded.fire(n,null)},e.prototype.clear=function(){this.widgetsValues=[]},e.prototype.getCustomWidget=function(e){for(var t=0;t<this.widgetsValues.length;t++)if(this.widgetsValues[t].isFit(e))return this.widgetsValues[t];return null},e}();o.Instance=new o},function(e,t,n){"use strict";var r=n(17);n.d(t,"a",function(){return i});var i={root:"",header:"panel-heading",body:"panel-body",footer:"panel-footer",navigationButton:"",navigation:{complete:"",prev:"",next:""},progress:"progress center-block",progressBar:"progress-bar",pageTitle:"",row:"",question:{root:"",title:"",comment:"form-control",indent:20},error:{root:"alert alert-danger",icon:"glyphicon glyphicon-exclamation-sign",item:""},checkbox:{root:"form-inline",item:"checkbox",other:""},comment:"form-control",dropdown:{root:"",control:"form-control"},matrix:{root:"table"},matrixdropdown:{root:"table"},matrixdynamic:{root:"table",button:"button"},multipletext:{root:"table",itemTitle:"",itemValue:"form-control"},radiogroup:{root:"form-inline",item:"radio",label:"",other:""},rating:{root:"btn-group",item:"btn btn-default"},text:"form-control",window:{root:"modal-content",body:"modal-body",header:{root:"modal-header panel-title",title:"pull-left",button:"glyphicon pull-right",buttonExpanded:"glyphicon pull-right glyphicon-chevron-up",buttonCollapsed:"glyphicon pull-right glyphicon-chevron-down"}}};r.b.bootstrap=i},function(e,t,n){"use strict";n(51),n(52),n(53),n(54),n(55),n(56),n(57),n(58),n(59),n(60),n(61),n(62),n(63)},function(e,t,n){"use strict";var r=n(50),i=(n.n(r),n(25));n.d(t,"b",function(){return i.b}),n.d(t,"c",function(){return i.c}),n.d(t,"d",function(){return i.d}),n.d(t,"e",function(){return i.e}),n.d(t,"f",function(){return i.f}),n.d(t,"g",function(){return i.g}),n.d(t,"h",function(){return i.h}),n.d(t,"i",function(){return i.a});var o=n(6);n.d(t,"j",function(){return o.b}),n.d(t,"k",function(){return o.c}),n.d(t,"l",function(){return o.d});var s=n(11);n.d(t,"m",function(){return s.a});var a=n(8);n.d(t,"n",function(){return a.a});var u=n(19);n.d(t,"o",function(){return u.a});var l=n(16);n.d(t,"p",function(){return l.b}),n.d(t,"q",function(){return l.c}),n.d(t,"r",function(){return l.a});var c=n(30);n.d(t,"s",function(){return c.a});var h=n(20);n.d(t,"t",function(){return h.a});var p=n(9);n.d(t,"u",function(){return p.c}),n.d(t,"v",function(){return p.d}),n.d(t,"w",function(){return p.b});var d=n(2);n.d(t,"x",function(){return d.b}),n.d(t,"y",function(){return d.c}),n.d(t,"z",function(){return d.d}),n.d(t,"A",function(){return d.e}),n.d(t,"B",function(){return d.f}),n.d(t,"C",function(){return d.g}),n.d(t,"D",function(){return d.a}),n.d(t,"E",function(){return d.h}),n.d(t,"F",function(){return d.i}),n.d(t,"G",function(){return d.j});var f=n(21);n.d(t,"H",function(){return f.a}),n.d(t,"I",function(){return f.b}),n.d(t,"J",function(){return f.c}),n.d(t,"K",function(){return f.d});var g=n(70);n.d(t,"L",function(){return g.a}),n.d(t,"M",function(){return g.b});var m=n(71);n.d(t,"N",function(){return m.a}),n.d(t,"O",function(){return m.b});var y=n(69);n.d(t,"P",function(){return y.a}),n.d(t,"Q",function(){return y.b});var v=n(72);n.d(t,"R",function(){return v.a}),n.d(t,"S",function(){return v.b});var b=n(33);n.d(t,"T",function(){return b.b}),n.d(t,"U",function(){return b.a}),n.d(t,"V",function(){return b.c});var C=n(32);n.d(t,"W",function(){return C.a});var w=n(10);n.d(t,"X",function(){return w.a});var x=n(22);n.d(t,"Y",function(){return x.a});var V=n(13);n.d(t,"Z",function(){return V.a}),n.d(t,"_0",function(){return V.b});var P=n(64);n.d(t,"_1",function(){return P.a});var T=n(65);n.d(t,"_2",function(){return T.a});var O=n(66);n.d(t,"_3",function(){return O.a});var q=n(7);n.d(t,"_4",function(){return q.a}),n.d(t,"_5",function(){return q.b});var R=n(67);n.d(t,"_6",function(){return R.a});var S=n(68);n.d(t,"_7",function(){return S.a});var E=n(73);n.d(t,"_8",function(){return E.a});var k=n(74);n.d(t,"_9",function(){return k.a});var N=n(75);n.d(t,"_10",function(){return N.a});var j=n(23);n.d(t,"_11",function(){return j.a});var I=n(78);n.d(t,"_12",function(){return I.a}),n.d(t,"_13",function(){return I.b}),n.d(t,"_14",function(){return I.c}),n.d(t,"_15",function(){return I.d}),n.d(t,"_16",function(){return I.e});var M=n(77);n.d(t,"_17",function(){return M.a});var L=n(24);n.d(t,"_18",function(){return L.a});var D=n(31);n.d(t,"_19",function(){return D.a});var A=n(1);n.d(t,"_20",function(){return A.a}),n.d(t,"_21",function(){return A.b});var Q=n(34);n.d(t,"_22",function(){return Q.b}),n.d(t,"_23",function(){return Q.a}),n.d(t,"a",function(){return B});var B;B="0.12.11"},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(26));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.handleOnExpanded=n.handleOnExpanded.bind(n),n}return r.b(t,e),t.prototype.handleOnExpanded=function(e){this.state.expanded=!this.state.expanded,this.setState(this.state)},t.prototype.render=function(){if(this.state.hidden)return null;var e=this.renderHeader(),t=this.state.expanded?this.renderBody():null,n={position:"fixed",bottom:"3px",right:"10px"};return i.createElement("div",{className:this.css.window.root,style:n},e,t)},t.prototype.renderHeader=function(){var e={width:"100%"},t={paddingRight:"10px"},n=this.state.expanded?this.css.window.header.buttonCollapsed:this.css.window.header.buttonExpanded;return n="glyphicon pull-right "+n,i.createElement("div",{className:this.css.window.header.root},i.createElement("a",{href:"#",onClick:this.handleOnExpanded,style:e},i.createElement("span",{className:this.css.window.header.title,style:t},this.title),i.createElement("span",{className:n,"aria-hidden":"true"})))},t.prototype.renderBody=function(){return i.createElement("div",{className:this.css.window.body},this.renderSurvey())},t.prototype.updateSurvey=function(t){e.prototype.updateSurvey.call(this,t),this.title=t.title?t.title:this.survey.title;var n=!!t.expanded&&t.expanded;this.state={expanded:n,hidden:!1};var r=this;this.survey.onComplete.add(function(e){r.state.hidden=!0,r.setState(r.state)})},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t){var n=e.call(this,t)||this;n.state={choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){return this.question?i.createElement("div",{className:this.css.root},this.getItems()):null},t.prototype.getItems=function(){for(var e=[],t=0;t<this.question.visibleChoices.length;t++){var n=this.question.visibleChoices[t],r="item"+t;e.push(this.renderItem(r,n,0==t))}return e},Object.defineProperty(t.prototype,"textStyle",{get:function(){return null},enumerable:!0,configurable:!0}),t.prototype.renderItem=function(e,t,n){return i.createElement(l,{key:e,question:this.question,css:this.css,rootCss:this.rootCss,isDisplayMode:this.isDisplayMode,item:t,textStyle:this.textStyle,isFirst:n})},t}(o.b),l=function(e){function t(t){var n=e.call(this,t)||this;return n.item=t.item,n.question=t.question,n.textStyle=t.textStyle,n.isFirst=t.isFirst,n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),t.prototype.shouldComponentUpdate=function(){return!this.question.customWidget||!!this.question.customWidget.widgetJson.render},t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.item=t.item,this.textStyle=t.textStyle,this.question=t.question,this.isFirst=t.isFirst},t.prototype.handleOnChange=function(e){var t=this.question.value;t||(t=[]);var n=t.indexOf(this.item.value);e.target.checked?n<0&&t.push(this.item.value):n>-1&&t.splice(n,1),this.question.value=t,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.item||!this.question)return null;var e=this.question.colCount>0?100/this.question.colCount+"%":"",t=0==this.question.colCount?"5px":"0px",n={marginRight:t};e&&(n.width=e);var r=this.question.value&&this.question.value.indexOf(this.item.value)>-1||!1,i=this.item.value===this.question.otherItem.value&&r?this.renderOther():null;return this.renderCheckbox(r,n,i)},Object.defineProperty(t.prototype,"inputStyle",{get:function(){return{marginRight:"3px"}},enumerable:!0,configurable:!0}),t.prototype.renderCheckbox=function(e,t,n){var r=this.isFirst?this.question.inputId:null,o=this.renderLocString(this.item.locText);return i.createElement("div",{className:this.css.item,style:t},i.createElement("label",{className:this.css.item},i.createElement("input",{type:"checkbox",id:r,style:this.inputStyle,disabled:this.isDisplayMode,checked:e,onChange:this.handleOnChange}),o),n)},t.prototype.renderOther=function(){return i.createElement("div",{className:this.css.other},i.createElement(s.a,{question:this.question,css:this.rootCss,isDisplayMode:this.isDisplayMode}))},t}(o.a);a.a.Instance.registerQuestion("checkbox",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5),u=n(79);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;n.state={value:n.question.value,choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state.value=this.question.value},t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.question)return null;var e=this.question.value===this.question.otherItem.value?this.renderOther():null,t=this.renderSelect();return i.createElement("div",{className:this.css.root},t,e)},t.prototype.renderSelect=function(){if(this.isDisplayMode)return i.createElement("div",{id:this.question.inputId,className:this.css.control},this.question.value);for(var e=[],t=0;t<this.question.visibleChoices.length;t++){var r=this.question.visibleChoices[t],o="item"+t,s=i.createElement("option",{key:o,value:r.value},r.text);e.push(s)}var a=null;return(u.a.msie||u.a.firefox&&n.i(u.b)(u.a.version,"51")<0)&&(a=this.handleOnChange),i.createElement("select",{id:this.question.inputId,className:this.css.control,value:this.state.value,onChange:a,onInput:this.handleOnChange},i.createElement("option",{value:""},this.question.optionsCaption),e)},t.prototype.renderOther=function(){var e={marginTop:"3px"};return i.createElement("div",{style:e},i.createElement(s.a,{question:this.question,css:this.rootCss,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("dropdown",function(e){return i.createElement(l,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={fileLoaded:0},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.handleOnChange=function(e){var t=e.target||e.srcElement;window.FileReader&&(!t||!t.files||t.files.length<1||(this.question.loadFile(t.files[0]),this.setState({fileLoaded:this.state.fileLoaded+1})))},t.prototype.render=function(){if(!this.question)return null;var e=this.renderImage(),t=null;return this.isDisplayMode||(t=i.createElement("input",{id:this.question.inputId,type:"file",onChange:this.handleOnChange})),i.createElement("div",null,t,e)},t.prototype.renderImage=function(){return this.question.previewValue?i.createElement("div",null," ",i.createElement("img",{src:this.question.previewValue,height:this.question.imageHeight,width:this.question.imageWidth})):null},t}(o.b);s.a.Instance.registerQuestion("file",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question||!this.question.html)return null;var e={__html:this.question.processedHtml};return i.createElement("div",{dangerouslySetInnerHTML:e})},t}(o.b);s.a.Instance.registerQuestion("html",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u});var a=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.hasRows?i.createElement("th",null):null,t=[],n=0;n<this.question.columns.length;n++){var r=this.question.columns[n],o="column"+n,s=this.renderLocString(r.locText);t.push(i.createElement("th",{key:o},s))}for(var a=[],l=this.question.visibleRows,n=0;n<l.length;n++){var c=l[n],o="row"+n;a.push(i.createElement(u,{key:o,question:this.question,css:this.css,rootCss:this.rootCss,isDisplayMode:this.isDisplayMode,row:c,isFirst:0==n}))}return i.createElement("table",{className:this.css.root},i.createElement("thead",null,i.createElement("tr",null,e,t)),i.createElement("tbody",null,a))},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.question=t.question,n.row=t.row,n.isFirst=t.isFirst,n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.row.value=e.target.value,this.setState({value:this.row.value})},t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.question=t.question,this.row=t.row,this.isFirst=t.isFirst},t.prototype.render=function(){if(!this.row)return null;var e=null;if(this.question.hasRows){var t=this.renderLocString(this.row.locText);e=i.createElement("td",null,t)}for(var n=[],r=0;r<this.question.columns.length;r++){var o=this.question.columns[r],s="value"+r,a=this.row.value==o.value,u=this.isFirst&&0==r?this.question.inputId:null,l=i.createElement("td",{key:s},i.createElement("input",{id:u,type:"radio",name:this.row.fullName,value:o.value,disabled:this.isDisplayMode,checked:a,onChange:this.handleOnChange}));n.push(l)}return i.createElement("tr",null,e,n)},t}(o.a);s.a.Instance.registerQuestion("matrix",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(14),a=n(5);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=[],t=0;t<this.question.columns.length;t++){var n=this.question.columns[t],r="column"+t,o=this.question.getColumnWidth(n),s=o?{minWidth:o}:{},a=this.renderLocString(n.locTitle);e.push(i.createElement("th",{key:r,style:s},a))}for(var u=[],c=this.question.visibleRows,t=0;t<c.length;t++){var h=c[t];u.push(i.createElement(l,{row:h,css:this.css,rootCss:this.rootCss,isDisplayMode:this.isDisplayMode,creator:this.creator}))}var p=this.question.horizontalScroll?{overflowX:"scroll"}:{};return i.createElement("div",{style:p},i.createElement("table",{className:this.css.root},i.createElement("thead",null,i.createElement("tr",null,i.createElement("th",null),e)),i.createElement("tbody",null,u)))},t}(o.b),l=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){this.row=e.row,this.creator=e.creator},t.prototype.render=function(){if(!this.row)return null;for(var e=[],t=0;t<this.row.cells.length;t++){var n=this.row.cells[t],r=i.createElement(s.b,{question:n.question,css:this.rootCss,creator:this.creator}),o=this.renderSelect(n);e.push(i.createElement("td",{key:"row"+t},r,o))}var a=this.renderLocString(this.row.locText);return i.createElement("tr",null,i.createElement("td",null,a),e)},t.prototype.renderSelect=function(e){return this.creator.createQuestionElement(e.question)},t}(o.a);a.a.Instance.registerQuestion("matrixdropdown",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(14),a=n(5);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){var t=this;this.state={rowCounter:0},this.question.rowCountChangedCallback=function(){t.state.rowCounter=t.state.rowCounter+1,t.setState(t.state)},this.handleOnRowAddClick=this.handleOnRowAddClick.bind(this)},t.prototype.handleOnRowAddClick=function(e){this.question.addRow()},t.prototype.render=function(){if(!this.question)return null;for(var e=[],t=0;t<this.question.columns.length;t++){var n=this.question.columns[t],r="column"+t,o=this.question.getColumnWidth(n),s=o?{minWidth:o}:{},a=this.renderLocString(n.locTitle);e.push(i.createElement("th",{key:r,style:s},a))}for(var u=[],c=this.question.visibleRows,t=0;t<c.length;t++){var h=c[t];u.push(i.createElement(l,{row:h,question:this.question,index:t,css:this.css,rootCss:this.rootCss,isDisplayMode:this.isDisplayMode,creator:this.creator}))}var p=this.question.horizontalScroll?{overflowX:"scroll"}:{},d=this.isDisplayMode?null:i.createElement("th",null);return i.createElement("div",null,i.createElement("div",{style:p},i.createElement("table",{className:this.css.root},i.createElement("thead",null,i.createElement("tr",null,e,d)),i.createElement("tbody",null,u))),this.renderAddRowButton())},t.prototype.renderAddRowButton=function(){return this.isDisplayMode||!this.question.canAddRow?null:i.createElement("input",{className:this.css.button,type:"button",onClick:this.handleOnRowAddClick,value:this.question.addRowText})},t}(o.b),l=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){this.row=e.row,this.question=e.question,this.index=e.index,this.creator=e.creator,this.handleOnRowRemoveClick=this.handleOnRowRemoveClick.bind(this)},t.prototype.handleOnRowRemoveClick=function(e){this.question.removeRow(this.index)},t.prototype.render=function(){if(!this.row)return null;for(var e=[],t=0;t<this.row.cells.length;t++){var n=this.row.cells[t],r=i.createElement(s.b,{question:n.question,css:this.rootCss,creator:this.creator}),o=this.renderQuestion(n);e.push(i.createElement("td",{key:"row"+t},r,o))}if(!this.isDisplayMode&&this.question.canRemoveRow){var a=this.renderButton();e.push(i.createElement("td",{key:"row"+this.row.cells.length+1},a))}return i.createElement("tr",null,e)},t.prototype.renderQuestion=function(e){return this.creator.createQuestionElement(e.question)},t.prototype.renderButton=function(){return i.createElement("input",{className:this.css.button,type:"button",onClick:this.handleOnRowRemoveClick,value:this.question.removeRowText})},t}(o.a);a.a.Instance.registerQuestion("matrixdynamic",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u});var a=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.getRows(),t=[],n=0;n<e.length;n++)t.push(this.renderRow("item"+n,e[n]));return i.createElement("table",{className:this.css.root},i.createElement("tbody",null,t))},t.prototype.renderRow=function(e,t){for(var n=[],r=0;r<t.length;r++){var o=t[r],s=this.renderLocString(o.locTitle);n.push(i.createElement("td",{key:"label"+r},i.createElement("span",{className:this.css.itemTitle},s))),n.push(i.createElement("td",{key:"value"+r},this.renderItem(o,0==r)))}return i.createElement("tr",{key:e},n)},t.prototype.renderItem=function(e,t){var n=t?this.question.inputId:null;return i.createElement(u,{item:e,css:this.css,isDisplayMode:this.isDisplayMode,inputId:n})},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.item=t.item,n.inputId=t.inputId,n.state={value:n.item.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.item.value=e.target.value,this.setState({value:this.item.value})},t.prototype.componentWillReceiveProps=function(e){this.item=e.item,this.css=e.css},t.prototype.render=function(){if(!this.item)return null;var e={float:"left"};return this.isDisplayMode?i.createElement("div",{id:this.inputId,className:this.css.itemValue,style:e},this.item.value):i.createElement("input",{id:this.inputId,className:this.css.itemValue,type:this.item.inputType,style:e,value:this.state.value,placeholder:this.item.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange})},Object.defineProperty(t.prototype,"mainClassName",{get:function(){return""},enumerable:!0,configurable:!0}),t}(o.a);s.a.Instance.registerQuestion("multipletext",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;n.state={choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.handleOnChange=this.handleOnChange.bind(this)},t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value})},t.prototype.render=function(){return this.question?i.createElement("div",{className:this.css.root},this.getItems()):null},t.prototype.getItems=function(){for(var e=[],t=0;t<this.question.visibleChoices.length;t++){var n=this.question.visibleChoices[t],r="item"+t;e.push(this.renderItem(r,n,0==t))}return e},Object.defineProperty(t.prototype,"textStyle",{get:function(){return{marginLeft:"3px"}},enumerable:!0,configurable:!0}),t.prototype.renderItem=function(e,t,n){var r=this.question.colCount>0?100/this.question.colCount+"%":"",i=0==this.question.colCount?"5px":"0px",o={marginRight:i};r&&(o.width=r);var s=this.question.value==t.value,a=s&&t.value===this.question.otherItem.value?this.renderOther():null;return this.renderRadio(e,t,s,o,a,n)},t.prototype.renderRadio=function(e,t,n,r,o,s){var a=s?this.question.inputId:null,u=this.renderLocString(t.locText,this.textStyle);return i.createElement("div",{key:e,className:this.css.item,style:r},i.createElement("label",{className:this.css.label},i.createElement("input",{id:a,type:"radio",name:this.question.name+"_"+this.questionBase.id,checked:n,value:t.value,disabled:this.isDisplayMode,onChange:this.handleOnChange}),u),o)},t.prototype.renderOther=function(){return i.createElement("div",{className:this.css.other},i.createElement(s.a,{question:this.question,css:this.rootCss,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("radiogroup",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.question)return null;for(var e=[],t=this.question.minRateDescription?this.renderLocString(this.question.locMinRateDescription):null,n=this.question.maxRateDescription?this.renderLocString(this.question.locMaxRateDescription):null,r=0;r<this.question.visibleRateValues.length;r++){var o=0==r?t:null,s=r==this.question.visibleRateValues.length-1?n:null;e.push(this.renderItem("value"+r,this.question.visibleRateValues[r],o,s))}var a=this.question.hasOther?this.renderOther():null;return i.createElement("div",{className:this.css.root},e,a)},t.prototype.renderItem=function(e,t,n,r){var o=this.question.value==t.value,s=this.css.item;o&&(s+=" active");var a=this.renderLocString(t.locText);return i.createElement("label",{key:e,className:s},i.createElement("input",{type:"radio",style:{display:"none"},name:this.question.name,value:t.value,disabled:this.isDisplayMode,checked:this.question.value==t.value,onChange:this.handleOnChange}),n,a,r)},t.prototype.renderOther=function(){return i.createElement("div",{className:this.css.other},i.createElement(s.a,{question:this.question,css:this.rootCss,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("rating",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={value:n.question.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state={value:this.question.value||""}},t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.question.value=e.target.value,this.setState({value:this.question.value||""})},t.prototype.render=function(){return this.question?this.isDisplayMode?i.createElement("div",{id:this.question.inputId,className:this.css},this.question.value):i.createElement("input",{id:this.question.inputId,className:this.css,type:this.question.inputType,value:this.state.value,size:this.question.size,placeholder:this.question.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange}):null},t}(o.b);s.a.Instance.registerQuestion("text",function(e){return i.createElement(a,e)})},function(e,t){},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Předchozí",pageNextText:"Další",completeText:"Hotovo",otherItemText:"Jiná odpověď (napište)",progressText:"Strana {0} z {1}",emptySurvey:"Průzkumu neobsahuje žádné otázky.",completingSurvey:"Děkujeme za vyplnění průzkumu!",loadingSurvey:"Probíhá načítání průzkumu...",optionsCaption:"Vyber...",requiredError:"Odpovězte prosím na otázku.",requiredInAllRowsError:"Odpovězte prosím na všechny otázky.",numericError:"V tomto poli lze zadat pouze čísla.",textMinLength:"Zadejte prosím alespoň {0} znaků.",textMaxLength:"Zadejte prosím méně než {0} znaků.",textMinMaxLength:"Zadejte prosím více než {0} a méně než {1} znaků.",minRowCountError:"Vyplňte prosím alespoň {0} řádků.",minSelectError:"Vyberte prosím alespoň {0} varianty.",maxSelectError:"Nevybírejte prosím více než {0} variant.",numericMinMax:"Odpověď '{0}' by mělo být větší nebo rovno {1} a menší nebo rovno {2}",numericMin:"Odpověď '{0}' by mělo být větší nebo rovno {1}",numericMax:"Odpověď '{0}' by mělo být menší nebo rovno {1}",invalidEmail:"Zadejte prosím platnou e-mailovou adresu.",urlRequestError:"Požadavek vrátil chybu '{0}'. {1}",urlGetChoicesError:"Požadavek nevrátil data nebo cesta je neplatná",exceedMaxSize:"Velikost souboru by neměla být větší než {0}.",otherRequiredError:"Zadejte prosím jinou hodnotu.",uploadingFile:"Váš soubor se nahrává. Zkuste to prosím za několik sekund.",addRow:"Přidat řádek",removeRow:"Odstranit"};r.a.locales.cz=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Tilbage",pageNextText:"Videre",completeText:"Færdig",progressText:"Side {0} af {1}",emptySurvey:"Der er ingen synlige spørgsmål.",completingSurvey:"Mange tak for din besvarelse!",loadingSurvey:"Spørgeskemaet hentes fra serveren...",otherItemText:"Valgfrit svar...",optionsCaption:"Vælg...",requiredError:"Besvar venligst spørgsmålet.",numericError:"Angiv et tal.",textMinLength:"Angiv mindst {0} tegn.",minSelectError:"Vælg venligst mindst {0} svarmulighed(er).",maxSelectError:"Vælg venligst færre {0} svarmuligheder(er).",numericMinMax:"'{0}' skal være lig med eller større end {1} og lig med eller mindre end {2}",numericMin:"'{0}' skal være lig med eller større end {1}",numericMax:"'{0}' skal være lig med eller mindre end {1}",invalidEmail:"Angiv venligst en gyldig e-mail adresse.",exceedMaxSize:"Filstørrelsen må ikke overstige {0}.",otherRequiredError:"Angiv en værdi for dit valgfrie svar."};r.a.locales.da=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Vorige",pageNextText:"Volgende",completeText:"Afsluiten",otherItemText:"Andere",progressText:"Pagina {0} van {1}",emptySurvey:"Er is geen zichtbare pagina of vraag in deze vragenlijst",completingSurvey:"Bedankt om deze vragenlijst in te vullen",loadingSurvey:"De vragenlijst is aan het laden...",optionsCaption:"Kies...",requiredError:"Gelieve een antwoord in te vullen",numericError:"Het antwoord moet een getal zijn",textMinLength:"Gelieve minsten {0} karakters in te vullen.",minSelectError:"Gelieve minimum {0} antwoorden te selecteren.",maxSelectError:"Gelieve niet meer dan {0} antwoorden te selecteren.",numericMinMax:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1} en kleiner of gelijk aan {2}",numericMin:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1}",numericMax:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1}",invalidEmail:"Gelieve een geldig e-mailadres in te vullen.",exceedMaxSize:"De grootte van het bestand mag niet groter zijn dan {0}.",otherRequiredError:"Gelieve het veld 'Andere' in te vullen"};r.a.locales.nl=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Edellinen",pageNextText:"Seuraava",completeText:"Valmis",otherItemText:"Muu (kuvaile)",progressText:"Sivu {0}/{1}",emptySurvey:"Tässä kyselyssä ei ole yhtäkään näkyvillä olevaa sivua tai kysymystä.",completingSurvey:"Kiitos kyselyyn vastaamisesta!",loadingSurvey:"Kyselyä ladataan palvelimelta...",optionsCaption:"Valitse...",requiredError:"Vastaa kysymykseen, kiitos.",numericError:"Arvon tulee olla numeerinen.",textMinLength:"Ole hyvä ja syötä vähintään {0} merkkiä.",minSelectError:"Ole hyvä ja valitse vähintään {0} vaihtoehtoa.",maxSelectError:"Ole hyvä ja valitse enintään {0} vaihtoehtoa.",numericMinMax:"'{0}' täytyy olla enemmän tai yhtä suuri kuin {1} ja vähemmän tai yhtä suuri kuin {2}",numericMin:"'{0}' täytyy olla enemmän tai yhtä suuri kuin {1}",numericMax:"'{0}' täytyy olla vähemmän tai yhtä suuri kuin {1}",invalidEmail:"Syötä validi sähköpostiosoite.",otherRequiredError:'Ole hyvä ja syötä "Muu (kuvaile)"'};r.a.locales.fi=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Précédent",pageNextText:"Suivant",completeText:"Terminer",otherItemText:"Autre (préciser)",progressText:"Page {0} sur {1}",emptySurvey:"Il n'y a ni page visible ni question visible dans ce questionnaire",completingSurvey:"Merci d'avoir répondu au questionnaire!",loadingSurvey:"Le questionnaire est en cours de chargement...",optionsCaption:"Choisissez...",requiredError:"La réponse à cette question est obligatoire.",requiredInAllRowsError:"Toutes les lignes sont obligatoires",numericError:"La réponse doit être un nombre.",textMinLength:"Merci d'entrer au moins {0} symboles.",minSelectError:"Merci de sélectionner au moins {0}réponses.",maxSelectError:"Merci de sélectionner au plus {0}réponses.",numericMinMax:"Votre réponse '{0}' doit êtresupérieure ou égale à {1} et inférieure ouégale à {2}",numericMin:"Votre réponse '{0}' doit êtresupérieure ou égale à {1}",numericMax:"Votre réponse '{0}' doit êtreinférieure ou égale à {1}",invalidEmail:"Merci d'entrer une adresse mail valide.",exceedMaxSize:"La taille du fichier ne doit pas excéder {0}.",otherRequiredError:"Merci de préciser le champ 'Autre'."};r.a.locales.fr=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Zurück",pageNextText:"Weiter",completeText:"Fertig",progressText:"Seite {0} von {1}",emptySurvey:"Es gibt keine sichtbare Frage.",completingSurvey:"Vielen Dank für das Ausfüllen des Fragebogens!",loadingSurvey:"Der Fragebogen wird vom Server geladen...",otherItemText:"Benutzerdefinierte Antwort...",optionsCaption:"Wählen...",requiredError:"Bitte antworten Sie auf die Frage.",numericError:"Der Wert sollte eine Zahl sein.",textMinLength:"Bitte geben Sie mindestens {0} Symbole.",minSelectError:"Bitte wählen Sie mindestens {0} Varianten.",maxSelectError:"Bitte wählen Sie nicht mehr als {0} Varianten.",numericMinMax:"'{0}' sollte gleich oder größer sein als {1} und gleich oder kleiner als {2}",numericMin:"'{0}' sollte gleich oder größer sein als {1}",numericMax:"'{0}' sollte gleich oder kleiner als {1}",invalidEmail:"Bitte geben Sie eine gültige Email-Adresse ein.",exceedMaxSize:"Die Dateigröße soll nicht mehr als {0}.",otherRequiredError:"Bitte geben Sie einen Wert für Ihre benutzerdefinierte Antwort ein."};r.a.locales.de=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Προηγούμενο",pageNextText:"Επόμενο",completeText:"Ολοκλήρωση",otherItemText:"Άλλο (παρακαλώ διευκρινίστε)",progressText:"Σελίδα {0} από {1}",emptySurvey:"Δεν υπάρχει καμία ορατή σελίδα ή ορατή ερώτηση σε αυτό το ερωτηματολόγιο.",completingSurvey:"Ευχαριστούμε για την συμπλήρωση αυτου του ερωτηματολογίου!",loadingSurvey:"Το ερωτηματολόγιο φορτώνεται απο το διακομιστή...",optionsCaption:"Επιλέξτε...",requiredError:"Παρακαλώ απαντήστε στην ερώτηση.",requiredInAllRowsError:"Παρακαλώ απαντήστε στις ερωτήσεις σε όλες τις γραμμές.",numericError:"Η τιμή πρέπει να είναι αριθμιτική.",textMinLength:"Παρακαλώ συμπληρώστε τουλάχιστον {0} σύμβολα.",minRowCountError:"Παρακαλώ συμπληρώστε τουλάχιστον {0} γραμμές.",minSelectError:"Παρακαλώ επιλέξτε τουλάχιστον {0} παραλλαγές.",maxSelectError:"Παρακαλώ επιλέξτε όχι παραπάνω απο {0} παραλλαγές.",numericMinMax:"Το '{0}' θα πρέπει να είναι ίσο ή μεγαλύτερο απο το {1} και ίσο ή μικρότερο απο το {2}",numericMin:"Το '{0}' πρέπει να είναι μεγαλύτερο ή ισο με το {1}",numericMax:"Το '{0}' πρέπει να είναι μικρότερο ή ίσο απο το {1}",invalidEmail:"Παρακαλώ δώστε μια αποδεκτή διεύθυνση e-mail.",urlRequestError:"Η αίτηση επέστρεψε σφάλμα '{0}'. {1}",urlGetChoicesError:"Η αίτηση επέστρεψε κενά δεδομένα ή η ιδότητα 'μονοπάτι/path' είναι εσφαλέμένη",exceedMaxSize:"Το μέγεθος δεν μπορεί να υπερβένει τα {0}.",otherRequiredError:"Παρακαλώ συμπληρώστε την τιμή για το πεδίο 'άλλο'.",uploadingFile:"Το αρχείο σας ανεβαίνει. Παρακαλώ περιμένετε καποια δευτερόλεπτα και δοκιμάστε ξανά.",addRow:"Προσθήκη γραμμής",removeRow:"Αφαίρεση"};r.a.locales.gr=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Wstecz",pageNextText:"Dalej",completeText:"Gotowe",otherItemText:"Inna odpowiedź (wpisz)",progressText:"Strona {0} z {1}",emptySurvey:"Nie ma widocznych pytań.",completingSurvey:"Dziękujemy za wypełnienie ankiety!",loadingSurvey:"Trwa wczytywanie ankiety...",optionsCaption:"Wybierz...",requiredError:"Proszę odpowiedzieć na to pytanie.",requiredInAllRowsError:"Proszę odpowiedzieć na wszystkie pytania.",numericError:"W tym polu można wpisać tylko liczby.",textMinLength:"Proszę wpisać co najmniej {0} znaków.",textMaxLength:"Proszę wpisać mniej niż {0} znaków.",textMinMaxLength:"Proszę wpisać więcej niż {0} i mniej niż {1} znaków.",minRowCountError:"Proszę uzupełnić przynajmniej {0} wierszy.",minSelectError:"Proszę wybrać co najmniej {0} pozycji.",maxSelectError:"Proszę wybrać nie więcej niż {0} pozycji.",numericMinMax:"Odpowiedź '{0}' powinna być większa lub równa {1} oraz mniejsza lub równa {2}",numericMin:"Odpowiedź '{0}' powinna być większa lub równa {1}",numericMax:"Odpowiedź '{0}' powinna być mniejsza lub równa {1}",invalidEmail:"Proszę podać prawidłowy adres email.",urlRequestError:"Żądanie zwróciło błąd '{0}'. {1}",urlGetChoicesError:"Żądanie nie zwróciło danych albo ścieżka jest nieprawidłowa",exceedMaxSize:"Rozmiar przesłanego pliku nie może przekraczać {0}.",otherRequiredError:"Proszę podać inną odpowiedź.",uploadingFile:"Trwa przenoszenie Twojego pliku, proszę spróbować ponownie za kilka sekund.",addRow:"Dodaj wiersz",removeRow:"Usuń"};r.a.locales.pl=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Precedent",pageNextText:"Următor",completeText:"Finalizare",otherItemText:"Altul(precizaţi)",progressText:"Pagina {0} din {1}",emptySurvey:"Nu sunt întrebări pentru acest chestionar",completingSurvey:"Vă mulţumim pentru timpul acordat!",loadingSurvey:"Chestionarul se încarcă...",optionsCaption:"Alegeţi...",requiredError:"Răspunsul la această întrebare este obligatoriu.",requiredInAllRowsError:"Toate răspunsurile sunt obligatorii",numericError:"Răspunsul trebuie să fie numeric.",textMinLength:"Trebuie să introduci minim {0} caractere.",minSelectError:"Trebuie să selectezi minim {0} opţiuni.",maxSelectError:"Trebuie să selectezi maxim {0} opţiuni.",numericMinMax:"Răspunsul '{0}' trebuie să fie mai mare sau egal ca {1} şî mai mic sau egal cu {2}",numericMin:"Răspunsul '{0}' trebuie să fie mai mare sau egal ca {1}",numericMax:"Răspunsul '{0}' trebuie să fie mai mic sau egal ca {1}",invalidEmail:"Trebuie să introduceţi o adresa de email validă.",exceedMaxSize:"Dimensiunea fişierului nu trebuie să depăşească {0}.",otherRequiredError:"Trebuie să completezi câmpul 'Altul'."};r.a.locales.ro=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Назад",pageNextText:"Далее",completeText:"Готово",progressText:"Страница {0} из {1}",emptySurvey:"Нет ни одного вопроса.",completingSurvey:"Благодарим Вас за заполнение анкеты!",loadingSurvey:"Загрузка с сервера...",otherItemText:"Другое (пожалуйста, опишите)",optionsCaption:"Выбрать...",requiredError:"Пожалуйста, ответьте на вопрос.",numericError:"Ответ должен быть числом.",textMinLength:"Пожалуйста, введите хотя бы {0} символов.",minSelectError:"Пожалуйста, выберите хотя бы {0} вариантов.",maxSelectError:"Пожалуйста, выберите не более {0} вариантов.",numericMinMax:"'{0}' должно быть равным или больше, чем {1}, и равным или меньше, чем {2}",numericMin:"'{0}' должно быть равным или больше, чем {1}",numericMax:"'{0}' должно быть равным или меньше, чем {1}",invalidEmail:"Пожалуйста, введите действительный адрес электронной почты.",otherRequiredError:'Пожалуйста, введите данные в поле "Другое"'};r.a.locales.ru=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Anterior",pageNextText:"Siguiente",completeText:"Completo",otherItemText:"Otro (describa)",progressText:"Pagina {0} de {1}",emptySurvey:"No hay pagina visible o pregunta en la encuesta.",completingSurvey:"Gracias por completar la encuesta!",loadingSurvey:"La encuesta se esta cargando...",optionsCaption:"Seleccione...",requiredError:"Por favor conteste la pregunta.",requiredInAllRowsError:"Por favor conteste las preguntas en cada hilera.",numericError:"La estimacion debe ser numerica.",textMinLength:"Por favor entre por lo menos {0} symbolos.",textMaxLength:"Por favor entre menos de {0} symbolos.",textMinMaxLength:"Por favor entre mas de {0} y menos de {1} symbolos.",minRowCountError:"Por favor llene por lo menos {0} hileras.",minSelectError:"Por favor seleccione por lo menos {0} variantes.",maxSelectError:"Por favor seleccione no mas de {0} variantes.",numericMinMax:"El '{0}' debe de ser igual o mas de {1} y igual o menos de {2}",numericMin:"El '{0}' debe ser igual o mas de {1}",numericMax:"El '{0}' debe ser igual o menos de {1}",invalidEmail:"Por favor agrege un correo electonico valido.",urlRequestError:"La solicitud regreso error '{0}'. {1}",urlGetChoicesError:"La solicitud regreso vacio de data o la propiedad 'trayectoria' no es correcta",exceedMaxSize:"El tamaño der archivo no debe de exceder {0}.",otherRequiredError:"Por favor agrege la otra estimacion.",uploadingFile:"Su archivo se esta subiendo. Por favor espere unos segundos y intente de nuevo.",addRow:"Agrege hilera",removeRow:"Retire",choices_firstItem:"primer articulo",choices_secondItem:"segundo articulo",choices_thirdItem:"tercer articulo",matrix_column:"Columna",matrix_row:"Hilera"};r.a.locales.es=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Föregående",pageNextText:"Nästa",completeText:"Färdig",otherItemText:"Annat (beskriv)",progressText:"Sida {0} av {1}",emptySurvey:"Det finns ingen synlig sida eller fråga i enkäten.",completingSurvey:"Tack för att du genomfört enkäten!!",loadingSurvey:"Enkäten laddas...",optionsCaption:"Välj...",requiredError:"Var vänlig besvara frågan.",requiredInAllRowsError:"Var vänlig besvara frågorna på alla rader.",numericError:"Värdet ska vara numeriskt.",textMinLength:"Var vänlig ange minst {0} tecken.",minRowCountError:"Var vänlig fyll i minst {0} rader.",minSelectError:"Var vänlig välj åtminstone {0} varianter.",maxSelectError:"Var vänlig välj inte fler än {0} varianter.",numericMinMax:"'{0}' ska vara lika med eller mer än {1} samt lika med eller mindre än {2}",numericMin:"'{0}' ska vara lika med eller mer än {1}",numericMax:"'{0}' ska vara lika med eller mindre än {1}",invalidEmail:"Var vänlig ange en korrekt e-postadress.",urlRequestError:"Förfrågan returnerade felet '{0}'. {1}",urlGetChoicesError:"Antingen returnerade förfrågan ingen data eller så är egenskapen 'path' inte korrekt",exceedMaxSize:"Filstorleken får ej överstiga {0}.",otherRequiredError:"Var vänlig ange det andra värdet.",uploadingFile:"Din fil laddas upp. Var vänlig vänta några sekunder och försök sedan igen.",addRow:"Lägg till rad",removeRow:"Ta bort"};r.a.locales.sv=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Geri",pageNextText:"İleri",completeText:"Anketi Tamamla",otherItemText:"Diğer (açıklayınız)",progressText:"Sayfa {0} / {1}",emptySurvey:"Ankette görüntülenecek sayfa ya da soru mevcut değil.",completingSurvey:"Anketimizi tamamladığınız için teşekkür ederiz.",loadingSurvey:"Anket sunucudan yükleniyor ...",optionsCaption:"Seçiniz ...",requiredError:"Lütfen soruya cevap veriniz",numericError:"Girilen değer numerik olmalıdır",textMinLength:"En az {0} sembol giriniz.",minRowCountError:"Lütfen en az {0} satırı doldurun.",minSelectError:"Lütfen en az {0} seçeneği seçiniz.",maxSelectError:"Lütfen {0} adetten fazla seçmeyiniz.",numericMinMax:"The '{0}' should be equal or more than {1} and equal or less than {2}",numericMin:"'{0}' değeri {1} değerine eşit veya büyük olmalıdır",numericMax:"'{0}' değeri {1} değerine eşit ya da küçük olmalıdır.",invalidEmail:"Lütfen geçerli bir eposta adresi giriniz.",urlRequestError:"Talebi şu hatayı döndü '{0}'. {1}",urlGetChoicesError:"Talep herhangi bir veri dönmedi ya da 'path' özelliği hatalı.",exceedMaxSize:"Dosya boyutu {0} değerini geçemez.",otherRequiredError:"Lütfen diğer değerleri giriniz.",uploadingFile:"Dosyanız yükleniyor. LÜtfen birkaç saniye bekleyin ve tekrar deneyin.",addRow:"Satır Ekle",removeRow:"Kaldır"};r.a.locales.tr=i},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(13);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n}return r.b(t,e),t.prototype.getHasOther=function(e){return!(!e||!Array.isArray(e))&&e.indexOf(this.otherItem.value)>=0},t.prototype.valueFromData=function(t){return t?Array.isArray(t)?e.prototype.valueFromData.call(this,t):[t]:t},t.prototype.valueFromDataCore=function(e){for(var t=0;t<e.length;t++){if(e[t]==this.otherItem.value)return e;if(this.hasUnknownValue(e[t])){this.comment=e[t];var n=e.slice();return n[t]=this.otherItem.value,n}}return e},t.prototype.valueToDataCore=function(e){if(!e||!e.length)return e;for(var t=0;t<e.length;t++)if(e[t]==this.otherItem.value&&this.getComment()){var n=e.slice();return n[t]=this.getComment(),n}return e},t.prototype.getType=function(){return"checkbox"},t}(s.a);i.a.metaData.addClass("checkbox",[],function(){return new a("")},"checkboxbase"),o.a.Instance.registerQuestion("checkbox",function(e){var t=new a(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(10),o=n(2),s=n(7),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rows=4,n.cols=50,n.locPlaceHolderValue=new a.a(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"comment"},t.prototype.isEmpty=function(){return e.prototype.isEmpty.call(this)||""===this.value},t}(i.a);o.a.metaData.addClass("comment",[{name:"cols:number",default:50},{name:"rows:number",default:4},{name:"placeHolder",serializationProperty:"locPlaceHolder"}],function(){return new u("")},"question"),s.a.Instance.registerQuestion("comment",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(13),a=n(1),u=n(8);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.locOptionsCaptionValue=new u.a(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text?this.locOptionsCaption.text:a.a.getString("optionsCaption")},set:function(e){this.locOptionsCaption.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"dropdown"},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locOptionsCaption.onChanged()},t.prototype.supportGoNextPageAutomatic=function(){return!0},t}(s.b);i.a.metaData.addClass("dropdown",[{name:"optionsCaption",serializationProperty:"locOptionsCaption"}],function(){return new l("")},"selectbase"),o.a.Instance.registerQuestion("dropdown",function(e){var t=new l(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(10),o=n(2),s=n(7),a=n(9),u=n(1);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.showPreviewValue=!1,n.isUploading=!1,n}return r.b(t,e),t.prototype.getType=function(){return"file"},Object.defineProperty(t.prototype,"showPreview",{get:function(){return this.showPreviewValue},set:function(e){this.showPreviewValue=e},enumerable:!0,configurable:!0}),t.prototype.loadFile=function(e){var t=this;this.survey&&!this.survey.uploadFile(this.name,e,this.storeDataAsText,function(e){t.isUploading="uploading"==e})||this.setFileValue(e)},t.prototype.setFileValue=function(e){if(FileReader&&(this.showPreview||this.storeDataAsText)&&!this.checkFileForErrors(e)){var t=new FileReader,n=this;t.onload=function(r){n.showPreview&&(n.previewValue=n.isFileImage(e)?t.result:null,n.fireCallback(n.previewValueLoadedCallback)),n.storeDataAsText&&(n.value=t.result)},t.readAsDataURL(e)}},t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.isUploading&&this.errors.push(new a.c(u.a.getString("uploadingFile")))},t.prototype.checkFileForErrors=function(e){var t=this.errors?this.errors.length:0;return this.errors=[],this.maxSize>0&&e.size>this.maxSize&&this.errors.push(new a.d(this.maxSize)),(t!=this.errors.length||this.errors.length>0)&&this.fireCallback(this.errorsChangedCallback),this.errors.length>0},t.prototype.isFileImage=function(e){if(e&&e.type){return 0==e.type.toLowerCase().indexOf("image")}},t}(i.a);o.a.metaData.addClass("file",["showPreview:boolean","imageHeight","imageWidth","storeDataAsText:boolean","maxSize:number"],function(){return new l("")},"question"),s.a.Instance.registerQuestion("file",function(e){return new l(e)})},function(e,t,n){"use strict";var r=n(0),i=n(22),o=n(2),s=n(7),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.locHtmlValue=new a.a(n),n}return r.b(t,e),t.prototype.getType=function(){return"html"},Object.defineProperty(t.prototype,"html",{get:function(){return this.locHtml.text},set:function(e){this.locHtml.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locHtml",{get:function(){return this.locHtmlValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedHtml",{get:function(){return this.survey?this.survey.processHtml(this.html):this.html},enumerable:!0,configurable:!0}),t}(i.a);o.a.metaData.addClass("html",[{name:"html:html",serializationProperty:"locHtml"}],function(){return new u("")},"questionbase"),s.a.Instance.registerQuestion("html",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(11),s=n(10),a=n(2),u=n(1),l=n(9),c=n(7);n.d(t,"a",function(){return h}),n.d(t,"b",function(){return p});var h=function(e){function t(t,n,r,i){var o=e.call(this)||this;return o.fullName=n,o.item=t,o.data=r,o.rowValue=i,o}return r.b(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return this.item.value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"text",{get:function(){return this.item.text},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locText",{get:function(){return this.item.locText},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){return this.rowValue},set:function(e){this.rowValue=e,this.data&&this.data.onMatrixRowChanged(this),this.onValueChanged()},enumerable:!0,configurable:!0}),t.prototype.onValueChanged=function(){},t}(i.b),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.isRowChanging=!1,n.isAllRowRequired=!1,n.columnsValue=o.a.createArray(n),n.rowsValue=o.a.createArray(n),n}return r.b(t,e),t.prototype.getType=function(){return"matrix"},Object.defineProperty(t.prototype,"hasRows",{get:function(){return this.rowsValue.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"columns",{get:function(){return this.columnsValue},set:function(e){o.a.setData(this.columnsValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowsValue},set:function(e){o.a.setData(this.rowsValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleRows",{get:function(){var e=new Array,t=this.value;t||(t={});for(var n=0;n<this.rows.length;n++)this.rows[n].value&&e.push(this.createMatrixRow(this.rows[n],this.name+"_"+this.rows[n].value.toString(),t[this.rows[n].value]));return 0==e.length&&e.push(this.createMatrixRow(new o.a(null),this.name,t)),this.generatedVisibleRows=e,e},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),o.a.NotifyArrayOnLocaleChanged(this.columns),o.a.NotifyArrayOnLocaleChanged(this.rows)},t.prototype.supportGoNextPageAutomatic=function(){return this.hasValuesInAllRows()},t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.hasErrorInRows()&&this.errors.push(new l.c(u.a.getString("requiredInAllRowsError")))},t.prototype.hasErrorInRows=function(){return!!this.isAllRowRequired&&!this.hasValuesInAllRows()},t.prototype.hasValuesInAllRows=function(){var e=this.generatedVisibleRows;if(e||(e=this.visibleRows),!e)return!0;for(var t=0;t<e.length;t++){if(!e[t].value)return!1}return!0},t.prototype.createMatrixRow=function(e,t,n){return new h(e,t,this,n)},t.prototype.onValueChanged=function(){if(!this.isRowChanging&&this.generatedVisibleRows&&0!=this.generatedVisibleRows.length){this.isRowChanging=!0;var e=this.value;if(e||(e={}),0==this.rows.length)this.generatedVisibleRows[0].value=e;else for(var t=0;t<this.generatedVisibleRows.length;t++){var n=this.generatedVisibleRows[t],r=e[n.name]?e[n.name]:null;this.generatedVisibleRows[t].value=r}this.isRowChanging=!1}},t.prototype.onMatrixRowChanged=function(e){if(!this.isRowChanging){if(this.isRowChanging=!0,this.hasRows){var t=this.value;t||(t={}),t[e.name]=e.value,this.setNewValue(t)}else this.setNewValue(e.value);this.isRowChanging=!1}},t}(s.a);a.a.metaData.addClass("matrix",[{name:"columns:itemvalues",onGetValue:function(e){return o.a.getData(e.columns)},onSetValue:function(e,t){e.columns=t}},{name:"rows:itemvalues",onGetValue:function(e){return o.a.getData(e.rows)},onSetValue:function(e,t){e.rows=t}},"isAllRowRequired:boolean"],function(){return new p("")},"question"),c.a.Instance.registerQuestion("matrix",function(e){var t=new p(e);return t.rows=c.a.DefaultRows,t.columns=c.a.DefaultColums,t})},function(e,t,n){"use strict";var r=n(0),i=n(21),o=n(2),s=n(11),a=n(7);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t,n,r,i){var o=e.call(this,r,i)||this;return o.name=t,o.item=n,o}return r.b(t,e),Object.defineProperty(t.prototype,"rowName",{get:function(){return this.name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"text",{get:function(){return this.item.text},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locText",{get:function(){return this.item.locText},enumerable:!0,configurable:!0}),t}(i.c),l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rowsValue=s.a.createArray(n),n}return r.b(t,e),t.prototype.getType=function(){return"matrixdropdown"},Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowsValue},set:function(e){s.a.setData(this.rowsValue,e)},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),s.a.NotifyArrayOnLocaleChanged(this.rowsValue)},t.prototype.generateRows=function(){var e=new Array;if(!this.rows||0===this.rows.length)return e;var t=this.value;t||(t={});for(var n=0;n<this.rows.length;n++)this.rows[n].value&&e.push(this.createMatrixRow(this.rows[n],t[this.rows[n].value]));return e},t.prototype.createMatrixRow=function(e,t){return new u(e.value,e,this,t)},t}(i.d);o.a.metaData.addClass("matrixdropdown",[{name:"rows:itemvalues",onGetValue:function(e){return s.a.getData(e.rows)},onSetValue:function(e,t){e.rows=t}}],function(){return new l("")},"matrixdropdownbase"),a.a.Instance.registerQuestion("matrixdropdown",function(e){var t=new l(e);return t.choices=[1,2,3,4,5],t.rows=a.a.DefaultColums,i.d.addDefaultColumns(t),t})},function(e,t,n){"use strict";var r=n(0),i=n(21),o=n(2),s=n(7),a=n(1),u=n(9),l=n(8);n.d(t,"a",function(){return c}),n.d(t,"b",function(){return h});var c=function(e){function t(t,n,r){var i=e.call(this,n,r)||this;return i.index=t,i}return r.b(t,e),Object.defineProperty(t.prototype,"rowName",{get:function(){return"row"+this.index},enumerable:!0,configurable:!0}),t}(i.c),h=function(e){function t(n){var r=e.call(this,n)||this;return r.name=n,r.rowCounter=0,r.rowCountValue=2,r.minRowCountValue=0,r.maxRowCountValue=t.MaxRowCount,r.locAddRowTextValue=new l.a(r),r.locRemoveRowTextValue=new l.a(r),r}return r.b(t,e),t.prototype.getType=function(){return"matrixdynamic"},Object.defineProperty(t.prototype,"rowCount",{get:function(){return this.rowCountValue},set:function(e){if(!(e<0||e>t.MaxRowCount)){if(this.rowCountValue=e,this.value&&this.value.length>e){var n=this.value;n.splice(e),this.value=n}this.fireCallback(this.rowCountChangedCallback)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minRowCount",{get:function(){return this.minRowCountValue},set:function(e){e<0&&(e=0),e==this.minRowCount||e>this.maxRowCount||(this.minRowCountValue=e,this.rowCount<e&&(this.rowCount=e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxRowCount",{get:function(){return this.maxRowCountValue},set:function(e){e<=0||(e>t.MaxRowCount&&(e=t.MaxRowCount),e==this.maxRowCount||e<this.minRowCount||(this.maxRowCountValue=e,this.rowCount>e&&(this.rowCount=e)))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canAddRow",{get:function(){return this.rowCount<this.maxRowCount},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canRemoveRow",{get:function(){return this.rowCount>this.minRowCount},enumerable:!0,configurable:!0}),t.prototype.addRow=function(){this.canAddRow&&(this.generatedVisibleRows&&this.generatedVisibleRows.push(this.createMatrixRow(null)),this.rowCount++)},t.prototype.removeRow=function(e){if(this.canRemoveRow&&!(e<0||e>=this.rowCount)){if(this.generatedVisibleRows&&e<this.generatedVisibleRows.length&&this.generatedVisibleRows.splice(e,1),this.value){var t=this.createNewValue(this.value);t.splice(e,1),t=this.deleteRowValue(t,null),this.value=t}this.rowCount--}},Object.defineProperty(t.prototype,"addRowText",{get:function(){return this.locAddRowText.text?this.locAddRowText.text:a.a.getString("addRow")},set:function(e){this.locAddRowText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locAddRowText",{get:function(){return this.locAddRowTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"removeRowText",{get:function(){return this.locRemoveRowText.text?this.locRemoveRowText.text:a.a.getString("removeRow")},set:function(e){this.locRemoveRowText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locRemoveRowText",{get:function(){return this.locRemoveRowTextValue},enumerable:!0,configurable:!0}),t.prototype.supportGoNextPageAutomatic=function(){return!1},Object.defineProperty(t.prototype,"cachedVisibleRows",{get:function(){return this.generatedVisibleRows&&this.generatedVisibleRows.length==this.rowCount?this.generatedVisibleRows:this.visibleRows},enumerable:!0,configurable:!0}),t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.hasErrorInRows()&&t.push(new u.c(a.a.getString("minRowCountError").format(this.minRowCount)))},t.prototype.hasErrorInRows=function(){if(this.minRowCount<=0||!this.generatedVisibleRows)return!1;for(var e=0,t=0;t<this.generatedVisibleRows.length;t++){this.generatedVisibleRows[t].isEmpty||e++}return e<this.minRowCount},t.prototype.generateRows=function(){var e=new Array;if(0===this.rowCount)return e;for(var t=this.createNewValue(this.value),n=0;n<this.rowCount;n++)e.push(this.createMatrixRow(this.getRowValueByIndex(t,n)));return e},t.prototype.createMatrixRow=function(e){return new c(this.rowCounter++,this,e)},t.prototype.onBeforeValueChanged=function(e){var t=e&&Array.isArray(e)?e.length:0;t<=this.rowCount||(this.rowCountValue=t,this.generatedVisibleRows&&(this.generatedVisibleRows=this.visibleRows))},t.prototype.createNewValue=function(e){var t=e;t||(t=[]);t.length>this.rowCount&&t.splice(this.rowCount-1);for(var n=t.length;n<this.rowCount;n++)t.push({});return t},t.prototype.deleteRowValue=function(e,t){for(var n=!0,r=0;r<e.length;r++)if(Object.keys(e[r]).length>0){n=!1;break}return n?null:e},t.prototype.getRowValueByIndex=function(e,t){return t>=0&&t<e.length?e[t]:null},t.prototype.getRowValue=function(e,t,n){return void 0===n&&(n=!1),this.getRowValueByIndex(t,this.generatedVisibleRows.indexOf(e))},t}(i.d);h.MaxRowCount=100,o.a.metaData.addClass("matrixdynamic",[{name:"rowCount:number",default:2},{name:"minRowCount:number",default:0},{name:"maxRowCount:number",default:h.MaxRowCount},{name:"addRowText",serializationProperty:"locAddRowText"},{name:"removeRowText",serializationProperty:"locRemoveRowText"}],function(){return new h("")},"matrixdropdownbase"),s.a.Instance.registerQuestion("matrixdynamic",function(e){var t=new h(e);return t.choices=[1,2,3,4,5],i.d.addDefaultColumns(t),t})},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(25),s=n(10),a=n(2),u=n(7),l=n(9),c=n(8);n.d(t,"a",function(){return h}),n.d(t,"b",function(){return p});var h=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;r.name=t,r.isRequired=!1,r.inputType="text",r.validators=new Array,r.locTitleValue=new c.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getFullTitle(e)},r.title=n,r.locPlaceHolderValue=new c.a(r),r}return r.b(t,e),t.prototype.getType=function(){return"multipletextitem"},t.prototype.setData=function(e){this.data=e},Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text?this.locTitle.text:this.name},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){return this.getFullTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getFullTitle=function(e){return e||(e=this.name),this.isRequired&&this.data&&(e=this.data.getIsRequiredText()+" "+e),e},Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){this.locTitle.onChanged()},Object.defineProperty(t.prototype,"value",{get:function(){return this.data?this.data.getMultipleTextValue(this.name):null},set:function(e){null!=this.data&&this.data.setMultipleTextValue(this.name,e)},enumerable:!0,configurable:!0}),t.prototype.onValueChanged=function(e){},t.prototype.getValidatorTitle=function(){return this.title},t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},t}(i.b),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.colCountValue=1,n.itemSize=25,n.itemsValues=new Array,n.isMultipleItemValueChanging=!1,n.setItemsOverriddenMethods(),n}return r.b(t,e),t.prototype.getType=function(){return"multipletext"},Object.defineProperty(t.prototype,"items",{get:function(){return this.itemsValues},set:function(e){this.itemsValues=e,this.setItemsOverriddenMethods(),this.fireCallback(this.colCountChangedCallback)},enumerable:!0,configurable:!0}),t.prototype.addItem=function(e,t){void 0===t&&(t=null);var n=this.createTextItem(e,t);return this.items.push(n),n},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this);for(var t=0;t<this.items.length;t++)this.items[t].onLocaleChanged()},t.prototype.setItemsOverriddenMethods=function(){var e=this;this.itemsValues.push=function(t){t.setData(e);var n=Array.prototype.push.call(this,t);return e.fireCallback(e.colCountChangedCallback),n},this.itemsValues.splice=function(t,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];t||(t=0),n||(n=0);var o=(a=Array.prototype.splice).call.apply(a,[e.itemsValues,t,n].concat(r));r||(r=[]);for(var s=0;s<r.length;s++)r[s].setData(e);return e.fireCallback(e.colCountChangedCallback),o;var a}},t.prototype.supportGoNextPageAutomatic=function(){for(var e=0;e<this.items.length;e++)if(!this.items[e].value)return!1;return!0},Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<1||e>4||(this.colCountValue=e,this.fireCallback(this.colCountChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.getRows=function(){for(var e=this.colCount,t=this.items,n=[],r=0,i=0;i<t.length;i++)0==r&&n.push([]),n[n.length-1].push(t[i]),++r>=e&&(r=0);return n},t.prototype.onValueChanged=function(){e.prototype.onValueChanged.call(this),this.onItemValueChanged()},t.prototype.createTextItem=function(e,t){return new h(e,t)},t.prototype.onItemValueChanged=function(){if(!this.isMultipleItemValueChanging)for(var e=0;e<this.items.length;e++){var t=null;this.value&&this.items[e].name in this.value&&(t=this.value[this.items[e].name]),this.items[e].onValueChanged(t)}},t.prototype.runValidators=function(){var t=e.prototype.runValidators.call(this);if(null!=t)return t;for(var n=0;n<this.items.length;n++)if(null!=(t=(new o.a).run(this.items[n])))return t;return null},t.prototype.hasErrors=function(t){void 0===t&&(t=!0);var n=e.prototype.hasErrors.call(this,t);return n||(n=this.hasErrorInItems(t)),n},t.prototype.hasErrorInItems=function(e){for(var t=0;t<this.items.length;t++){var n=this.items[t];if(n.isRequired&&!n.value)return this.errors.push(new l.a),e&&this.fireCallback(this.errorsChangedCallback),!0}return!1},t.prototype.getMultipleTextValue=function(e){return this.value?this.value[e]:null},t.prototype.setMultipleTextValue=function(e,t){this.isMultipleItemValueChanging=!0;var n=this.value;n||(n={}),n[e]=t,this.setNewValue(n),this.isMultipleItemValueChanging=!1},t.prototype.getIsRequiredText=function(){return this.survey?this.survey.requiredText:""},t}(s.a);a.a.metaData.addClass("multipletextitem",["name","isRequired:boolean",{name:"placeHolder",serializationProperty:"locPlaceHolder"},{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"title",serializationProperty:"locTitle"},{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],function(){return new h("")}),a.a.metaData.addClass("multipletext",[{name:"!items:textitems",className:"multipletextitem"},{name:"itemSize:number",default:25},{name:"colCount:number",default:1,choices:[1,2,3,4]}],function(){return new p("")},"question"),u.a.Instance.registerQuestion("multipletext",function(e){var t=new p(e);return t.addItem("text1"),t.addItem("text2"),t})},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(13);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n}return r.b(t,e),t.prototype.getType=function(){return"radiogroup"},t.prototype.supportGoNextPageAutomatic=function(){return!0},t}(s.a);i.a.metaData.addClass("radiogroup",[],function(){return new a("")},"checkboxbase"),o.a.Instance.registerQuestion("radiogroup",function(e){var t=new a(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(11),o=n(10),s=n(2),a=n(7),u=n(8);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rates=i.a.createArray(n),n.locMinRateDescriptionValue=new u.a(n,!0),n.locMaxRateDescriptionValue=new u.a(n,!0),n.locMinRateDescriptionValue.onRenderedHtmlCallback=function(e){return e?e+" ":e},n.locMaxRateDescriptionValue.onRenderedHtmlCallback=function(e){return e?" "+e:e},n}return r.b(t,e),Object.defineProperty(t.prototype,"rateValues",{get:function(){return this.rates},set:function(e){i.a.setData(this.rates,e),this.fireCallback(this.rateValuesChangedCallback)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleRateValues",{get:function(){return this.rateValues.length>0?this.rateValues:t.defaultRateValues},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"rating"},t.prototype.supportGoNextPageAutomatic=function(){return!0},t.prototype.supportComment=function(){return!0},t.prototype.supportOther=function(){return!0},Object.defineProperty(t.prototype,"minRateDescription",{get:function(){return this.locMinRateDescription.text},set:function(e){this.locMinRateDescription.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locMinRateDescription",{get:function(){return this.locMinRateDescriptionValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxRateDescription",{get:function(){return this.locMaxRateDescription.text},set:function(e){this.locMaxRateDescription.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locMaxRateDescription",{get:function(){return this.locMaxRateDescriptionValue},enumerable:!0,configurable:!0}),t}(o.a);l.defaultRateValues=[],i.a.setData(l.defaultRateValues,[1,2,3,4,5]),s.a.metaData.addClass("rating",["hasComment:boolean",{name:"rateValues:itemvalues",onGetValue:function(e){return i.a.getData(e.rateValues)},onSetValue:function(e,t){e.rateValues=t}},{name:"minRateDescription",alternativeName:"mininumRateDescription",serializationProperty:"locMinRateDescription"},{name:"maxRateDescription",alternativeName:"maximumRateDescription",serializationProperty:"locMaxRateDescription"}],function(){return new l("")},"question"),a.a.Instance.registerQuestion("rating",function(e){return new l(e)})},function(e,t,n){"use strict";var r=n(0),i=n(7),o=n(2),s=n(10),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.size=25,n.inputType="text",n.locPlaceHolderValue=new a.a(n),n}return r.b(t,e),t.prototype.getType=function(){return"text"},t.prototype.isEmpty=function(){return e.prototype.isEmpty.call(this)||""===this.value},t.prototype.supportGoNextPageAutomatic=function(){return!0},Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.setNewValue=function(t){t=this.correctValueType(t),e.prototype.setNewValue.call(this,t)},t.prototype.correctValueType=function(e){return e&&("number"==this.inputType||"range"==this.inputType)?this.isNumber(e)?parseFloat(e):"":e},t.prototype.isNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},t}(s.a);o.a.metaData.addClass("text",[{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"size:number",default:25},{name:"placeHolder",serializationProperty:"locPlaceHolder"}],function(){return new u("")},"question"),i.a.Instance.registerQuestion("text",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.localeChangedHandler=function(e){return e.customWidget.widgetJson.isNeedRender=!0},n}return r.b(t,e),t.prototype.componentDidMount=function(){if(this.questionBase){var e=this.refs.root;this.questionBase.customWidget&&(e=this.refs.widget)&&(this.questionBase.customWidget.afterRender(this.questionBase,e),this.questionBase.customWidget.widgetJson.isNeedRender=!1),this.questionBase.localeChanged.add(this.localeChangedHandler)}},t.prototype.componentWillUnmount=function(){var e=this.refs.root;this.questionBase.customWidget&&(e=this.refs.widget)&&this.questionBase.customWidget.willUnmount(this.questionBase,e),this.questionBase.localeChanged.remove(this.localeChangedHandler)},t.prototype.render=function(){if(!this.questionBase||!this.creator)return null;if(!this.questionBase.visible)return null;var e=this.questionBase.customWidget;if(e.widgetJson.isDefaultRender)return i.createElement("div",{ref:"widget"},this.creator.createQuestionElement(this.questionBase));var t=null;if(e.widgetJson.render)t=e.widgetJson.render(this.questionBase);else if(e.htmlTemplate){var n={__html:e.htmlTemplate};return i.createElement("div",{ref:"widget",dangerouslySetInnerHTML:n})}return i.createElement("div",{ref:"widget"},t)},t}(o.b)},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(23);n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this)||this;return n.surveyValue=n.createSurvey(t),n.surveyValue.showTitle=!1,n.windowElement=document.createElement("div"),n}return r.b(t,e),t.prototype.getType=function(){return"window"},Object.defineProperty(t.prototype,"survey",{get:function(){return this.surveyValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isShowing",{get:function(){return this.isShowingValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isExpanded",{get:function(){return this.isExpandedValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.titleValue?this.titleValue:this.survey.title},set:function(e){this.titleValue=e},enumerable:!0,configurable:!0}),t.prototype.expand=function(){this.expandcollapse(!0)},t.prototype.collapse=function(){this.expandcollapse(!1)},t.prototype.createSurvey=function(e){return new o.a(e)},t.prototype.expandcollapse=function(e){this.isExpandedValue=e},t}(i.b);s.surveyElementName="windowSurveyJS"},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(2);n.d(t,"e",function(){return s}),n.d(t,"a",function(){return a}),n.d(t,"d",function(){return u}),n.d(t,"b",function(){return l}),n.d(t,"c",function(){return c});var s=function(e){function t(){var t=e.call(this)||this;return t.opValue="equal",t}return r.b(t,e),Object.defineProperty(t,"operators",{get:function(){return null!=t.operatorsValue?t.operatorsValue:(t.operatorsValue={empty:function(e,t){return!e},notempty:function(e,t){return!!e},equal:function(e,t){return e==t},notequal:function(e,t){return e!=t},contains:function(e,t){return e&&e.indexOf&&e.indexOf(t)>-1},notcontains:function(e,t){return!e||!e.indexOf||-1==e.indexOf(t)},greater:function(e,t){return e>t},less:function(e,t){return e<t},greaterorequal:function(e,t){return e>=t},lessorequal:function(e,t){return e<=t}},t.operatorsValue)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"operator",{get:function(){return this.opValue},set:function(e){e&&(e=e.toLowerCase(),t.operators[e]&&(this.opValue=e))},enumerable:!0,configurable:!0}),t.prototype.check=function(e){t.operators[this.operator](e,this.value)?this.onSuccess():this.onFailure()},t.prototype.onSuccess=function(){},t.prototype.onFailure=function(){},t}(i.b);s.operatorsValue=null;var a=function(e){function t(){var t=e.call(this)||this;return t.owner=null,t}return r.b(t,e),t.prototype.setOwner=function(e){this.owner=e},Object.defineProperty(t.prototype,"isOnNextPage",{get:function(){return!1},enumerable:!0,configurable:!0}),t}(s),u=function(e){function t(){var t=e.call(this)||this;return t.pages=[],t.questions=[],t}return r.b(t,e),t.prototype.getType=function(){return"visibletrigger"},t.prototype.onSuccess=function(){this.onTrigger(this.onItemSuccess)},t.prototype.onFailure=function(){this.onTrigger(this.onItemFailure)},t.prototype.onTrigger=function(e){if(this.owner)for(var t=this.owner.getObjects(this.pages,this.questions),n=0;n<t.length;n++)e(t[n])},t.prototype.onItemSuccess=function(e){e.visible=!0},t.prototype.onItemFailure=function(e){e.visible=!1},t}(a),l=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getType=function(){return"completetrigger"},Object.defineProperty(t.prototype,"isOnNextPage",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.onSuccess=function(){this.owner&&this.owner.doComplete()},t}(a),c=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getType=function(){return"setvaluetrigger"},t.prototype.onSuccess=function(){this.setToName&&this.owner&&this.owner.setTriggerValue(this.setToName,this.setValue,this.isVariable)},t}(a);o.a.metaData.addClass("trigger",["operator","!value"]),o.a.metaData.addClass("surveytrigger",["!name"],null,"trigger"),o.a.metaData.addClass("visibletrigger",["pages","questions"],function(){return new u},"surveytrigger"),o.a.metaData.addClass("completetrigger",[],function(){return new l},"surveytrigger"),o.a.metaData.addClass("setvaluetrigger",["!setToName","setValue","isVariable:boolean"],function(){return new c},"surveytrigger")},function(e,t,n){"use strict";function r(e,t){var n,r,i=/(\.0+)+$/,o=e.replace(i,"").split("."),s=t.replace(i,"").split("."),a=Math.min(o.length,s.length);for(n=0;n<a;n++)if(r=parseInt(o[n],10)-parseInt(s[n],10))return r;return o.length-s.length}n.d(t,"a",function(){return c}),n.d(t,"b",function(){return r});var i=/(webkit)[ \/]([\w.]+)/,o=/(msie) (\d{1,2}\.\d)/,s=/(trident).*rv:(\d{1,2}\.\d)/,a=/(edge)\/((\d+)?[\w\.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))/,l=function(e){e=e.toLowerCase();var t={},n=o.exec(e)||s.exec(e)||a.exec(e)||e.indexOf("compatible")<0&&u.exec(e)||i.exec(e)||[],r=n[1],l=n[2];return"trident"===r||"edge"===r?r="msie":"mozilla"===r&&(r="firefox"),r&&(t[r]=!0,t.version=l),t},c=l(navigator.userAgent)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(37);n.d(t,"Version",function(){return r.a}),n.d(t,"AnswerCountValidator",function(){return r.b}),n.d(t,"EmailValidator",function(){return r.c}),n.d(t,"NumericValidator",function(){return r.d}),n.d(t,"RegexValidator",function(){return r.e}),n.d(t,"SurveyValidator",function(){return r.f}),n.d(t,"TextValidator",function(){return r.g}),n.d(t,"ValidatorResult",function(){return r.h}),n.d(t,"ValidatorRunner",function(){return r.i}),n.d(t,"Base",function(){return r.j}),n.d(t,"Event",function(){return r.k}),n.d(t,"SurveyError",function(){return r.l}),n.d(t,"ItemValue",function(){return r.m}),n.d(t,"LocalizableString",function(){return r.n}),n.d(t,"ChoicesRestfull",function(){return r.o}),n.d(t,"Condition",function(){return r.p}),n.d(t,"ConditionNode",function(){return r.q}),n.d(t,"ConditionRunner",function(){return r.r}),n.d(t,"ConditionsParser",function(){return r.s}),n.d(t,"ProcessValue",function(){return r.t}),n.d(t,"CustomError",function(){return r.u}),n.d(t,"ExceedSizeError",function(){return r.v}),n.d(t,"RequreNumericError",function(){return r.w}),n.d(t,"JsonError",function(){return r.x}),n.d(t,"JsonIncorrectTypeError",function(){return r.y}),n.d(t,"JsonMetadata",function(){return r.z}),n.d(t,"JsonMetadataClass",function(){return r.A}),n.d(t,"JsonMissingTypeError",function(){return r.B}),n.d(t,"JsonMissingTypeErrorBase",function(){return r.C}),n.d(t,"JsonObject",function(){return r.D}),n.d(t,"JsonObjectProperty",function(){return r.E}),n.d(t,"JsonRequiredPropertyError",function(){return r.F}),n.d(t,"JsonUnknownPropertyError",function(){return r.G}),n.d(t,"MatrixDropdownCell",function(){return r.H}),n.d(t,"MatrixDropdownColumn",function(){return r.I}),n.d(t,"MatrixDropdownRowModelBase",function(){return r.J}),n.d(t,"QuestionMatrixDropdownModelBase",function(){return r.K}),n.d(t,"MatrixDropdownRowModel",function(){return r.L}),n.d(t,"QuestionMatrixDropdownModel",function(){return r.M}),n.d(t,"MatrixDynamicRowModel",function(){return r.N}),n.d(t,"QuestionMatrixDynamicModel",function(){return r.O}),n.d(t,"MatrixRowModel",function(){return r.P}),n.d(t,"QuestionMatrixModel",function(){return r.Q}),n.d(t,"MultipleTextItemModel",function(){return r.R}),n.d(t,"QuestionMultipleTextModel",function(){return r.S}),n.d(t,"PanelModel",function(){return r.T}),n.d(t,"PanelModelBase",function(){return r.U}),n.d(t,"QuestionRowModel",function(){return r.V}),n.d(t,"PageModel",function(){return r.W}),n.d(t,"Question",function(){return r.X}),n.d(t,"QuestionBase",function(){return r.Y}),n.d(t,"QuestionCheckboxBase",function(){return r.Z}),n.d(t,"QuestionSelectBase",function(){return r._0}),n.d(t,"QuestionCheckboxModel",function(){return r._1}),n.d(t,"QuestionCommentModel",function(){return r._2}),n.d(t,"QuestionDropdownModel",function(){return r._3}),n.d(t,"ElementFactory",function(){return r._5}),n.d(t,"QuestionFileModel",function(){return r._6}),n.d(t,"QuestionHtmlModel",function(){return r._7}),n.d(t,"QuestionRadiogroupModel",function(){return r._8}),n.d(t,"QuestionRatingModel",function(){return r._9}),n.d(t,"QuestionTextModel",function(){return r._10}),n.d(t,"SurveyModel",function(){return r._11}),n.d(t,"SurveyTrigger",function(){return r._12}),n.d(t,"SurveyTriggerComplete",function(){return r._13}),n.d(t,"SurveyTriggerSetValue",function(){return r._14}),n.d(t,"SurveyTriggerVisible",function(){return r._15}),n.d(t,"Trigger",function(){return r._16}),n.d(t,"SurveyWindowModel",function(){return r._17}),n.d(t,"TextPreProcessor",function(){return r._18}),n.d(t,"dxSurveyService",function(){return r._19}),n.d(t,"surveyLocalization",function(){return r._20}),n.d(t,"surveyStrings",function(){return r._21}),n.d(t,"QuestionCustomWidget",function(){return r._22}),n.d(t,"CustomWidgetCollection",function(){return r._23});var i=(n(36),n(0));n.d(t,"__assign",function(){return i.a}),n.d(t,"__extends",function(){return i.b}),n.d(t,"__decorate",function(){return i.c});var o=n(17);n.d(t,"defaultStandardCss",function(){return o.a});var s=n(35);n.d(t,"defaultBootstrapCss",function(){return s.a});var a=n(26);n.d(t,"Survey",function(){return a.a});var u=n(15);n.d(t,"ReactSurveyModel",function(){return u.a}),n.d(t,"Model",function(){return u.a});var l=n(18);n.d(t,"SurveyNavigationBase",function(){return l.a});var c=n(27);n.d(t,"SurveyNavigation",function(){return c.a});var h=n(29);n.d(t,"SurveyPage",function(){return h.a}),n.d(t,"SurveyRow",function(){return h.b});var p=n(14);n.d(t,"SurveyQuestion",function(){return p.a}),n.d(t,"SurveyQuestionErrors",function(){return p.b});var d=n(4);n.d(t,"SurveyElementBase",function(){return d.a}),n.d(t,"SurveyQuestionElementBase",function(){return d.b});var f=n(12);n.d(t,"SurveyQuestionCommentItem",function(){return f.a}),n.d(t,"SurveyQuestionComment",function(){return f.b});var g=n(39);n.d(t,"SurveyQuestionCheckbox",function(){return g.a}),n.d(t,"SurveyQuestionCheckboxItem",function(){return g.b});var m=n(40);n.d(t,"SurveyQuestionDropdown",function(){return m.a});var y=n(44);n.d(t,"SurveyQuestionMatrixDropdown",function(){return y.a}),n.d(t,"SurveyQuestionMatrixDropdownRow",function(){return y.b});var v=n(43);n.d(t,"SurveyQuestionMatrix",function(){return v.a}),n.d(t,"SurveyQuestionMatrixRow",function(){return v.b});var b=n(42);n.d(t,"SurveyQuestionHtml",function(){return b.a});var C=n(41);n.d(t,"SurveyQuestionFile",function(){return C.a});var w=n(46);n.d(t,"SurveyQuestionMultipleText",function(){return w.a}),n.d(t,"SurveyQuestionMultipleTextItem",function(){return w.b});var x=n(47);n.d(t,"SurveyQuestionRadiogroup",function(){return x.a});var V=n(49);n.d(t,"SurveyQuestionText",function(){return V.a});var P=n(45);n.d(t,"SurveyQuestionMatrixDynamic",function(){return P.a}),n.d(t,"SurveyQuestionMatrixDynamicRow",function(){return P.b});var T=n(28);n.d(t,"SurveyProgress",function(){return T.a});var O=n(48);n.d(t,"SurveyQuestionRating",function(){return O.a});var q=n(38);n.d(t,"SurveyWindow",function(){return q.a});var R=n(5);n.d(t,"ReactQuestionFactory",function(){return R.a}),n.d(t,"QuestionFactory",function(){return R.a})}])}); |
examples/forms-material-ui/src/models/tweet.js | lore/lore-forms | import React from 'react';
import fields from '../fields/tweet';
export default {
attributes: {
text: {
type: 'text'
},
userId: {
type: 'model',
model: 'user'
}
},
forms: {
create: fields,
update: fields
},
dialogs: {
create: fields,
update: fields
},
properties: {
/**
* Override the idAttribute if the primary key in the resource is named
* anything other than 'id'. Doing so will allow the other methods to
* behave as expected, such as composing the expected url for CRUD
* operations and being able to retrieve the primary key by 'model.id'
*/
// idAttribute: 'id'
/**
* Override the initialize method if you need to save data for use
* in other functions. This is especially useful if you have a nested
* URL for an API endpoint, like /authors/:userId/books. In that case,
* you can save the author here and refer to it when creating the URL
* in the url() or urlRoot() method.
*/
// initialize: function(attributes, options) {
// return;
// },
/**
* Override the urlRoot if your API endpoint does not match the default
* conventions. For example, given a model named 'bookAuthor', and assuming
* an apiRoot of 'http://localhost:1337' with pluralize set to true, the
* endpoint for creating a model is assumed to be 'http://localhost:1337/bookAuthors'
* If this model is on a different server (such as http://localhost:3001) or the
* endpoint is named something different (such as book_authors or books/:id/authors)
* you will need to set that here; urlRoot can be either a string or a function
*/
// urlRoot: function() {
// return 'https://api.example.com/endpoint'
// },
/**
* Override the url method if you need complete control over the final URL
* endpoint. This is especially useful when you have an endpoint like /user
* or /profile that returns a single resource with information about the current
* user and an id is not required. You'll also need to override this method if
* the route doesn't use the primary key of the resource.
*/
// url: function() {
// return 'https://api.example.com/unconventional/endpoint/123'
// },
/**
* Override the parse method if you need to modify data before using
* it in the application, such as converting timestamps or adding
* properties to absorb breaking API changes.
*/
// parse: function(resp, options) {
// return resp;
// },
/**
* Override the sync method if you need to modify data before sending
* it to the server.
*
* If you override this method the library will make no AJAX requests
* for this model, so you'll need to make sure you implement the AJAX
* call yourself or make a call to sync.apply(this, arguments).
*
* Use of 'sync' refers to sync method provided by the 'lore-models'
* package, i.e. import { sync } from 'lore-models';
*/
// sync: function() {
// return sync.apply(this, arguments);
// }
}
};
|
assets/grocery_crud/js/jquery-1.11.1.js | idzer0lis/SimpleUserManagement | /*!
* jQuery JavaScript Library v1.11.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:42Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowclip^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;" +
"padding:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
}
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
packages/material-ui-icons/src/PhonePausedTwoTone.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M6.54 5h-1.5c.09 1.32.34 2.58.75 3.79l1.2-1.21c-.24-.83-.39-1.7-.45-2.58zm8.66 13.21c1.21.41 2.48.67 3.8.76v-1.5c-.88-.07-1.75-.22-2.6-.45l-1.2 1.19z" opacity=".3" /><path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.1-.03-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM5.03 5h1.5c.07.88.22 1.75.45 2.58l-1.2 1.21c-.4-1.21-.66-2.47-.75-3.79zM19 18.97c-1.32-.09-2.6-.35-3.8-.76l1.2-1.2c.85.24 1.72.39 2.6.45v1.51zM15 3h2v7h-2zm4 0h2v7h-2z" /></React.Fragment>
, 'PhonePausedTwoTone');
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/UnknownExtInclusion.js | maletor/create-react-app | /**
* 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.
*/
import React from 'react';
import aFileWithExtUnknown from './assets/aFileWithExt.unknown';
const text = aFileWithExtUnknown.includes('base64')
? atob(aFileWithExtUnknown.split('base64,')[1]).trim()
: aFileWithExtUnknown;
export default () => (
<a id="feature-unknown-ext-inclusion" href={text}>
aFileWithExtUnknown
</a>
);
|
ajax/libs/yui/3.4.1pr1/yui/yui.js | blairvanderhoof/cdnjs | /**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and
* the core utilities for the library.
* @module yui
* @submodule yui-base
*/
if (typeof YUI != 'undefined') {
YUI._YUI = YUI;
}
/**
The YUI global namespace object. If YUI is already defined, the
existing YUI object will not be overwritten so that defined
namespaces are preserved. It is the constructor for the object
the end user interacts with. As indicated below, each instance
has full custom event support, but only if the event system
is available. This is a self-instantiable factory function. You
can invoke it directly like this:
YUI().use('*', function(Y) {
// ready
});
But it also works like this:
var Y = YUI();
@class YUI
@constructor
@global
@uses EventTarget
@param o* {Object} 0..n optional configuration objects. these values
are store in Y.config. See <a href="config.html">Config</a> for the list of supported
properties.
*/
/*global YUI*/
/*global YUI_config*/
var YUI = function() {
var i = 0,
Y = this,
args = arguments,
l = args.length,
instanceOf = function(o, type) {
return (o && o.hasOwnProperty && (o instanceof type));
},
gconf = (typeof YUI_config !== 'undefined') && YUI_config;
if (!(instanceOf(Y, YUI))) {
Y = new YUI();
} else {
// set up the core environment
Y._init();
/**
YUI.GlobalConfig is a master configuration that might span
multiple contexts in a non-browser environment. It is applied
first to all instances in all contexts.
@property GlobalConfig
@type {Object}
@global
@static
@example
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (YUI.GlobalConfig) {
Y.applyConfig(YUI.GlobalConfig);
}
/**
YUI_config is a page-level config. It is applied to all
instances created on the page. This is applied after
YUI.GlobalConfig, and before the instance level configuration
objects.
@global
@property YUI_config
@type {Object}
@example
//Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (gconf) {
Y.applyConfig(gconf);
}
// bind the specified additional modules for this instance
if (!l) {
Y._setup();
}
}
if (l) {
// Each instance can accept one or more configuration objects.
// These are applied after YUI.GlobalConfig and YUI_Config,
// overriding values set in those config files if there is a '
// matching property.
for (; i < l; i++) {
Y.applyConfig(args[i]);
}
Y._setup();
}
Y.instanceOf = instanceOf;
return Y;
};
(function() {
var proto, prop,
VERSION = '@VERSION@',
PERIOD = '.',
BASE = 'http://yui.yahooapis.com/',
DOC_LABEL = 'yui3-js-enabled',
NOOP = function() {},
SLICE = Array.prototype.slice,
APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo
'io.xdrResponse': 1, // can call. this should
'SWF.eventHandler': 1 }, // be done at build time
hasWin = (typeof window != 'undefined'),
win = (hasWin) ? window : null,
doc = (hasWin) ? win.document : null,
docEl = doc && doc.documentElement,
docClass = docEl && docEl.className,
instances = {},
time = new Date().getTime(),
add = function(el, type, fn, capture) {
if (el && el.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (el && el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
remove = function(el, type, fn, capture) {
if (el && el.removeEventListener) {
// this can throw an uncaught exception in FF
try {
el.removeEventListener(type, fn, capture);
} catch (ex) {}
} else if (el && el.detachEvent) {
el.detachEvent('on' + type, fn);
}
},
handleLoad = function() {
YUI.Env.windowLoaded = true;
YUI.Env.DOMReady = true;
if (hasWin) {
remove(window, 'load', handleLoad);
}
},
getLoader = function(Y, o) {
var loader = Y.Env._loader;
if (loader) {
//loader._config(Y.config);
loader.ignoreRegistered = false;
loader.onEnd = null;
loader.data = null;
loader.required = [];
loader.loadType = null;
} else {
loader = new Y.Loader(Y.config);
Y.Env._loader = loader;
}
YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ]));
return loader;
},
clobber = function(r, s) {
for (var i in s) {
if (s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
},
ALREADY_DONE = { success: true };
// Stamp the documentElement (HTML) with a class of "yui-loaded" to
// enable styles that need to key off of JS being enabled.
if (docEl && docClass.indexOf(DOC_LABEL) == -1) {
if (docClass) {
docClass += ' ';
}
docClass += DOC_LABEL;
docEl.className = docClass;
}
if (VERSION.indexOf('@') > -1) {
VERSION = '3.3.0'; // dev time hack for cdn test
}
proto = {
/**
* Applies a new configuration object to the YUI instance config.
* This will merge new group/module definitions, and will also
* update the loader cache if necessary. Updating Y.config directly
* will not update the cache.
* @method applyConfig
* @param {Object} o the configuration object.
* @since 3.2.0
*/
applyConfig: function(o) {
o = o || NOOP;
var attr,
name,
// detail,
config = this.config,
mods = config.modules,
groups = config.groups,
rls = config.rls,
loader = this.Env._loader;
for (name in o) {
if (o.hasOwnProperty(name)) {
attr = o[name];
if (mods && name == 'modules') {
clobber(mods, attr);
} else if (groups && name == 'groups') {
clobber(groups, attr);
} else if (rls && name == 'rls') {
clobber(rls, attr);
} else if (name == 'win') {
config[name] = attr.contentWindow || attr;
config.doc = config[name].document;
} else if (name == '_yuid') {
// preserve the guid
} else {
config[name] = attr;
}
}
}
if (loader) {
loader._config(o);
}
},
/**
* Old way to apply a config to the instance (calls `applyConfig` under the hood)
* @private
* @method _config
* @param {Object} o The config to apply
*/
_config: function(o) {
this.applyConfig(o);
},
/**
* Initialize this YUI instance
* @private
* @method _init
*/
_init: function() {
var filter,
Y = this,
G_ENV = YUI.Env,
Env = Y.Env,
prop;
/**
* The version number of the YUI instance.
* @property version
* @type string
*/
Y.version = VERSION;
if (!Env) {
Y.Env = {
core: ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3'],
mods: {}, // flat module map
versions: {}, // version module map
base: BASE,
cdn: BASE + VERSION + '/build/',
// bootstrapped: false,
_idx: 0,
_used: {},
_attached: {},
_missed: [],
_yidx: 0,
_uidx: 0,
_guidp: 'y',
_loaded: {},
// serviced: {},
// Regex in English:
// I'll start at the \b(simpleyui).
// 1. Look in the test string for "simpleyui" or "yui" or
// "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it
// can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string.
// 2. After #1 must come a forward slash followed by the string matched in #1, so
// "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants".
// 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min",
// so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt".
// 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js"
// 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string,
// then capture the junk between the LAST "&" and the string in 1-4. So
// "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js"
// will capture "3.3.0/build/"
//
// Regex Exploded:
// (?:\? Find a ?
// (?:[^&]*&) followed by 0..n characters followed by an &
// * in fact, find as many sets of characters followed by a & as you can
// ([^&]*) capture the stuff after the last & in \1
// )? but it's ok if all this ?junk&more_junk stuff isn't even there
// \b(simpleyui| after a word break find either the string "simpleyui" or
// yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters
// ) and store the simpleyui or yui-* string in \2
// \/\2 then comes a / followed by the simpleyui or yui-* string in \2
// (?:-(min|debug))? optionally followed by "-min" or "-debug"
// .js and ending in ".js"
_BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,
parseBasePath: function(src, pattern) {
var match = src.match(pattern),
path, filter;
if (match) {
path = RegExp.leftContext || src.slice(0, src.indexOf(match[0]));
// this is to set up the path to the loader. The file
// filter for loader should match the yui include.
filter = match[3];
// extract correct path for mixed combo urls
// http://yuilibrary.com/projects/yui3/ticket/2528423
if (match[1]) {
path += '?' + match[1];
}
path = {
filter: filter,
path: path
}
}
return path;
},
getBase: G_ENV && G_ENV.getBase ||
function(pattern) {
var nodes = (doc && doc.getElementsByTagName('script')) || [],
path = Env.cdn, parsed,
i, len, src;
for (i = 0, len = nodes.length; i < len; ++i) {
src = nodes[i].src;
if (src) {
parsed = Y.Env.parseBasePath(src, pattern);
if (parsed) {
filter = parsed.filter;
path = parsed.path;
break;
}
}
}
// use CDN default
return path;
}
};
Env = Y.Env;
Env._loaded[VERSION] = {};
if (G_ENV && Y !== YUI) {
Env._yidx = ++G_ENV._yidx;
Env._guidp = ('yui_' + VERSION + '_' +
Env._yidx + '_' + time).replace(/\./g, '_');
} else if (YUI._YUI) {
G_ENV = YUI._YUI.Env;
Env._yidx += G_ENV._yidx;
Env._uidx += G_ENV._uidx;
for (prop in G_ENV) {
if (!(prop in Env)) {
Env[prop] = G_ENV[prop];
}
}
delete YUI._YUI;
}
Y.id = Y.stamp(Y);
instances[Y.id] = Y;
}
Y.constructor = YUI;
// configuration defaults
Y.config = Y.config || {
win: win,
doc: doc,
debug: true,
useBrowserConsole: true,
throwFail: true,
bootstrap: true,
cacheUse: true,
fetchCSS: true,
use_rls: false,
rls_timeout: 2000
};
if (YUI.Env.rls_disabled) {
Y.config.use_rls = false;
}
Y.config.lang = Y.config.lang || 'en-US';
Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE);
if (!filter || (!('mindebug').indexOf(filter))) {
filter = 'min';
}
filter = (filter) ? '-' + filter : filter;
Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js';
},
/**
* Finishes the instance setup. Attaches whatever modules were defined
* when the yui modules was registered.
* @method _setup
* @private
*/
_setup: function(o) {
var i, Y = this,
core = [],
mods = YUI.Env.mods,
//extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3'];
extras = Y.config.core || [].concat(YUI.Env.core); //Clone it..
for (i = 0; i < extras.length; i++) {
if (mods[extras[i]]) {
core.push(extras[i]);
}
}
Y._attach(['yui-base']);
Y._attach(core);
if (Y.Loader) {
getLoader(Y);
}
},
/**
* Executes a method on a YUI instance with
* the specified id if the specified method is whitelisted.
* @method applyTo
* @param id {String} the YUI instance id.
* @param method {String} the name of the method to exectute.
* Ex: 'Object.keys'.
* @param args {Array} the arguments to apply to the method.
* @return {Object} the return value from the applied method or null.
*/
applyTo: function(id, method, args) {
if (!(method in APPLY_TO_AUTH)) {
this.log(method + ': applyTo not allowed', 'warn', 'yui');
return null;
}
var instance = instances[id], nest, m, i;
if (instance) {
nest = method.split('.');
m = instance;
for (i = 0; i < nest.length; i = i + 1) {
m = m[nest[i]];
if (!m) {
this.log('applyTo not found: ' + method, 'warn', 'yui');
}
}
return m.apply(instance, args);
}
return null;
},
/**
Registers a module with the YUI global. The easiest way to create a
first-class YUI module is to use the YUI component build tool.
http://yuilibrary.com/projects/builder
The build system will produce the `YUI.add` wrapper for you module, along
with any configuration info required for the module.
@method add
@param name {String} module name.
@param fn {Function} entry point into the module that is used to bind module to the YUI instance.
@param {YUI} fn.Y The YUI instance this module is executed in.
@param {String} fn.name The name of the module
@param version {String} version string.
@param details {Object} optional config data:
@param details.requires {Array} features that must be present before this module can be attached.
@param details.optional {Array} optional features that should be present if loadOptional
is defined. Note: modules are not often loaded this way in YUI 3,
but this field is still useful to inform the user that certain
features in the component will require additional dependencies.
@param details.use {Array} features that are included within this module which need to
be attached automatically when this module is attached. This
supports the YUI 3 rollup system -- a module with submodules
defined will need to have the submodules listed in the 'use'
config. The YUI component build tool does this for you.
@return {YUI} the YUI instance.
@example
YUI.add('davglass', function(Y, name) {
Y.davglass = function() {
alert('Dav was here!');
};
}, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] });
*/
add: function(name, fn, version, details) {
details = details || {};
var env = YUI.Env,
mod = {
name: name,
fn: fn,
version: version,
details: details
},
loader,
i, versions = env.versions;
env.mods[name] = mod;
versions[version] = versions[version] || {};
versions[version][name] = mod;
for (i in instances) {
if (instances.hasOwnProperty(i)) {
loader = instances[i].Env._loader;
if (loader) {
if (!loader.moduleInfo[name]) {
loader.addModule(details, name);
}
}
}
}
return this;
},
/**
* Executes the function associated with each required
* module, binding the module to the YUI instance.
* @param {Array} r The array of modules to attach
* @param {Boolean} [moot=false] Don't throw a warning if the module is not attached
* @method _attach
* @private
*/
_attach: function(r, moot) {
var i, name, mod, details, req, use, after,
mods = YUI.Env.mods,
aliases = YUI.Env.aliases,
Y = this, j,
loader = Y.Env._loader,
done = Y.Env._attached,
len = r.length, loader,
c = [];
//Check for conditional modules (in a second+ instance) and add their requirements
//TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass
for (i = 0; i < len; i++) {
name = r[i];
mod = mods[name];
c.push(name);
if (loader && loader.conditions[name]) {
Y.Object.each(loader.conditions[name], function(def) {
var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y)));
if (go) {
c.push(def.name);
}
});
}
}
r = c;
len = r.length;
for (i = 0; i < len; i++) {
if (!done[r[i]]) {
name = r[i];
mod = mods[name];
if (aliases && aliases[name]) {
Y._attach(aliases[name]);
continue;
}
if (!mod) {
if (loader && loader.moduleInfo[name]) {
mod = loader.moduleInfo[name];
moot = true;
}
//if (!loader || !loader.moduleInfo[name]) {
//if ((!loader || !loader.moduleInfo[name]) && !moot) {
if (!moot) {
if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) {
Y.Env._missed.push(name);
Y.Env._missed = Y.Array.dedupe(Y.Env._missed);
Y.message('NOT loaded: ' + name, 'warn', 'yui');
}
}
} else {
done[name] = true;
//Don't like this, but in case a mod was asked for once, then we fetch it
//We need to remove it from the missed list ^davglass
for (j = 0; j < Y.Env._missed.length; j++) {
if (Y.Env._missed[j] === name) {
Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui');
Y.Env._missed.splice(j, 1);
}
}
details = mod.details;
req = details.requires;
use = details.use;
after = details.after;
if (req) {
for (j = 0; j < req.length; j++) {
if (!done[req[j]]) {
if (!Y._attach(req)) {
return false;
}
break;
}
}
}
if (after) {
for (j = 0; j < after.length; j++) {
if (!done[after[j]]) {
if (!Y._attach(after, true)) {
return false;
}
break;
}
}
}
if (mod.fn) {
try {
mod.fn(Y, name);
} catch (e) {
Y.error('Attach error: ' + name, e, name);
return false;
}
}
if (use) {
for (j = 0; j < use.length; j++) {
if (!done[use[j]]) {
if (!Y._attach(use)) {
return false;
}
break;
}
}
}
}
}
}
return true;
},
/**
* Attaches one or more modules to the YUI instance. When this
* is executed, the requirements are analyzed, and one of
* several things can happen:
*
* * All requirements are available on the page -- The modules
* are attached to the instance. If supplied, the use callback
* is executed synchronously.
*
* * Modules are missing, the Get utility is not available OR
* the 'bootstrap' config is false -- A warning is issued about
* the missing modules and all available modules are attached.
*
* * Modules are missing, the Loader is not available but the Get
* utility is and boostrap is not false -- The loader is bootstrapped
* before doing the following....
*
* * Modules are missing and the Loader is available -- The loader
* expands the dependency tree and fetches missing modules. When
* the loader is finshed the callback supplied to use is executed
* asynchronously.
*
* @method use
* @param modules* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*
* @example
* // loads and attaches dd and its dependencies
* YUI().use('dd', function(Y) {});
*
* // loads and attaches dd and node as well as all of their dependencies (since 3.4.0)
* YUI().use(['dd', 'node'], function(Y) {});
*
* // attaches all modules that are available on the page
* YUI().use('*', function(Y) {});
*
* // intrinsic YUI gallery support (since 3.1.0)
* YUI().use('gallery-yql', function(Y) {});
*
* // intrinsic YUI 2in3 support (since 3.1.0)
* YUI().use('yui2-datatable', function(Y) {});
*
* @return {YUI} the YUI instance.
*/
use: function() {
var args = SLICE.call(arguments, 0),
callback = args[args.length - 1],
Y = this,
i = 0,
name,
Env = Y.Env,
provisioned = true;
// The last argument supplied to use can be a load complete callback
if (Y.Lang.isFunction(callback)) {
args.pop();
} else {
callback = null;
}
if (Y.Lang.isArray(args[0])) {
args = args[0];
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y._loading) {
Y._useQueue = Y._useQueue || new Y.Queue();
Y._useQueue.add([args, callback]);
} else {
Y._use(args, function(Y, response) {
Y._notify(callback, response, args);
});
}
return Y;
},
/**
* Notify handler from Loader for attachment/load errors
* @method _notify
* @param callback {Function} The callback to pass to the `Y.config.loadErrorFn`
* @param response {Object} The response returned from Loader
* @param args {Array} The aruments passed from Loader
* @private
*/
_notify: function(callback, response, args) {
if (!response.success && this.config.loadErrorFn) {
this.config.loadErrorFn.call(this, this, callback, response, args);
} else if (callback) {
try {
callback(this, response);
} catch (e) {
this.error('use callback error', e, args);
}
}
},
/**
* This private method is called from the `use` method queue. To ensure that only one set of loading
* logic is performed at a time.
* @method _use
* @private
* @param args* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*/
_use: function(args, callback) {
if (!this.Array) {
this._attach(['yui-base']);
}
var len, loader, handleBoot, handleRLS,
Y = this,
G_ENV = YUI.Env,
mods = G_ENV.mods,
Env = Y.Env,
used = Env._used,
queue = G_ENV._loaderQueue,
firstArg = args[0],
YArray = Y.Array,
config = Y.config,
boot = config.bootstrap,
missing = [],
r = [],
ret = true,
fetchCSS = config.fetchCSS,
process = function(names, skip) {
if (!names.length) {
return;
}
YArray.each(names, function(name) {
// add this module to full list of things to attach
if (!skip) {
r.push(name);
}
// only attach a module once
if (used[name]) {
return;
}
var m = mods[name], req, use;
if (m) {
used[name] = true;
req = m.details.requires;
use = m.details.use;
} else {
// CSS files don't register themselves, see if it has
// been loaded
if (!G_ENV._loaded[VERSION][name]) {
missing.push(name);
} else {
used[name] = true; // probably css
}
}
// make sure requirements are attached
if (req && req.length) {
process(req);
}
// make sure we grab the submodule dependencies too
if (use && use.length) {
process(use, 1);
}
});
},
handleLoader = function(fromLoader) {
var response = fromLoader || {
success: true,
msg: 'not dynamic'
},
redo, origMissing,
ret = true,
data = response.data;
Y._loading = false;
if (data) {
origMissing = missing;
missing = [];
r = [];
process(data);
redo = missing.length;
if (redo) {
if (missing.sort().join() ==
origMissing.sort().join()) {
redo = false;
}
}
}
if (redo && data) {
Y._loading = false;
Y._use(args, function() {
if (Y._attach(data)) {
Y._notify(callback, response, data);
}
});
} else {
if (data) {
ret = Y._attach(data);
}
if (ret) {
Y._notify(callback, response, args);
}
}
if (Y._useQueue && Y._useQueue.size() && !Y._loading) {
Y._use.apply(Y, Y._useQueue.next());
}
};
// YUI().use('*'); // bind everything available
if (firstArg === '*') {
ret = Y._attach(Y.Object.keys(mods));
if (ret) {
handleLoader();
}
return Y;
}
// use loader to expand dependencies and sort the
// requirements if it is available.
if (boot && Y.Loader && args.length) {
loader = getLoader(Y);
loader.require(args);
loader.ignoreRegistered = true;
loader.calculate(null, (fetchCSS) ? null : 'js');
args = loader.sorted;
}
// process each requirement and any additional requirements
// the module metadata specifies
process(args);
len = missing.length;
if (len) {
missing = Y.Object.keys(YArray.hash(missing));
len = missing.length;
}
// dynamic load
if (boot && len && Y.Loader) {
Y._loading = true;
loader = getLoader(Y);
loader.onEnd = handleLoader;
loader.context = Y;
loader.data = args;
loader.ignoreRegistered = false;
loader.require(args);
loader.insert(null, (fetchCSS) ? null : 'js');
// loader.partial(missing, (fetchCSS) ? null : 'js');
} else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) {
G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue();
// server side loader service
handleRLS = function(instance, argz) {
var rls_end = function(o) {
handleLoader(o);
instance.rls_advance();
},
rls_url = instance._rls(argz);
if (rls_url) {
instance.rls_oncomplete(function(o) {
rls_end(o);
});
instance.Get.script(rls_url, {
data: argz,
timeout: instance.config.rls_timeout,
onFailure: instance.rls_handleFailure,
onTimeout: instance.rls_handleTimeout
});
} else {
rls_end({
success: true,
data: argz
});
}
};
G_ENV._rls_queue.add(function() {
G_ENV._rls_in_progress = true;
Y.rls_callback = callback;
Y.rls_locals(Y, args, handleRLS);
});
if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) {
G_ENV._rls_queue.next()();
}
} else if (boot && len && Y.Get && !Env.bootstrapped) {
Y._loading = true;
handleBoot = function() {
Y._loading = false;
queue.running = false;
Env.bootstrapped = true;
G_ENV._bootstrapping = false;
if (Y._attach(['loader'])) {
Y._use(args, callback);
}
};
if (G_ENV._bootstrapping) {
queue.add(handleBoot);
} else {
G_ENV._bootstrapping = true;
Y.Get.script(config.base + config.loaderPath, {
onEnd: handleBoot
});
}
} else {
ret = Y._attach(args);
if (ret) {
handleLoader();
}
}
return Y;
},
/**
Adds a namespace object onto the YUI global if called statically.
// creates YUI.your.namespace.here as nested objects
YUI.namespace("your.namespace.here");
If called as a method on a YUI <em>instance</em>, it creates the
namespace on the instance.
// creates Y.property.package
Y.namespace("property.package");
Dots in the input string cause `namespace` to create nested objects for
each token. If any part of the requested namespace already exists, the
current object will be left in place. This allows multiple calls to
`namespace` to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", the token is
discarded.
Be careful with namespace tokens. Reserved words may work in some browsers
and not others. For instance, the following will fail in some browsers
because the supported version of JavaScript reserves the word "long":
Y.namespace("really.long.nested.namespace");
@method namespace
@param {String} namespace* namespaces to create.
@return {Object} A reference to the last namespace object created.
**/
namespace: function() {
var a = arguments, o = this, i = 0, j, d, arg;
for (; i < a.length; i++) {
// d = ('' + a[i]).split('.');
arg = a[i];
if (arg.indexOf(PERIOD)) {
d = arg.split(PERIOD);
for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
} else {
o[arg] = o[arg] || {};
}
}
return o;
},
// this is replaced if the log module is included
log: NOOP,
message: NOOP,
// this is replaced if the dump module is included
dump: function (o) { return ''+o; },
/**
* Report an error. The reporting mechanism is controled by
* the `throwFail` configuration attribute. If throwFail is
* not specified, the message is written to the Logger, otherwise
* a JS error is thrown
* @method error
* @param msg {String} the error message.
* @param e {Error|String} Optional JS error that was caught, or an error string.
* @param data Optional additional info
* and `throwFail` is specified, this error will be re-thrown.
* @return {YUI} this YUI instance.
*/
error: function(msg, e, data) {
var Y = this, ret;
if (Y.config.errorFn) {
ret = Y.config.errorFn.apply(Y, arguments);
}
if (Y.config.throwFail && !ret) {
throw (e || new Error(msg));
} else {
Y.message(msg, 'error'); // don't scrub this one
}
return Y;
},
/**
* Generate an id that is unique among all YUI instances
* @method guid
* @param pre {String} optional guid prefix.
* @return {String} the guid.
*/
guid: function(pre) {
var id = this.Env._guidp + '_' + (++this.Env._uidx);
return (pre) ? (pre + id) : id;
},
/**
* Returns a `guid` associated with an object. If the object
* does not have one, a new one is created unless `readOnly`
* is specified.
* @method stamp
* @param o {Object} The object to stamp.
* @param readOnly {Boolean} if `true`, a valid guid will only
* be returned if the object has one assigned to it.
* @return {String} The object's guid or null.
*/
stamp: function(o, readOnly) {
var uid;
if (!o) {
return o;
}
// IE generates its own unique ID for dom nodes
// The uniqueID property of a document node returns a new ID
if (o.uniqueID && o.nodeType && o.nodeType !== 9) {
uid = o.uniqueID;
} else {
uid = (typeof o === 'string') ? o : o._yuid;
}
if (!uid) {
uid = this.guid();
if (!readOnly) {
try {
o._yuid = uid;
} catch (e) {
uid = null;
}
}
}
return uid;
},
/**
* Destroys the YUI instance
* @method destroy
* @since 3.3.0
*/
destroy: function() {
var Y = this;
if (Y.Event) {
Y.Event._unload();
}
delete instances[Y.id];
delete Y.Env;
delete Y.config;
}
/**
* instanceof check for objects that works around
* memory leak in IE when the item tested is
* window/document
* @method instanceOf
* @since 3.3.0
*/
};
YUI.prototype = proto;
// inheritance utilities are not available yet
for (prop in proto) {
if (proto.hasOwnProperty(prop)) {
YUI[prop] = proto[prop];
}
}
// set up the environment
YUI._init();
if (hasWin) {
// add a window load event at load time so we can capture
// the case where it fires before dynamic loading is
// complete.
add(window, 'load', handleLoad);
} else {
handleLoad();
}
YUI.Env.add = add;
YUI.Env.remove = remove;
/*global exports*/
// Support the CommonJS method for exporting our single global
if (typeof exports == 'object') {
exports.YUI = YUI;
}
}());
/**
* The config object contains all of the configuration options for
* the `YUI` instance. This object is supplied by the implementer
* when instantiating a `YUI` instance. Some properties have default
* values if they are not supplied by the implementer. This should
* not be updated directly because some values are cached. Use
* `applyConfig()` to update the config object on a YUI instance that
* has already been configured.
*
* @class config
* @static
*/
/**
* Allows the YUI seed file to fetch the loader component and library
* metadata to dynamically load additional dependencies.
*
* @property bootstrap
* @type boolean
* @default true
*/
/**
* Log to the browser console if debug is on and the browser has a
* supported console.
*
* @property useBrowserConsole
* @type boolean
* @default true
*/
/**
* A hash of log sources that should be logged. If specified, only
* log messages from these sources will be logged.
*
* @property logInclude
* @type object
*/
/**
* A hash of log sources that should be not be logged. If specified,
* all sources are logged if not on this list.
*
* @property logExclude
* @type object
*/
/**
* Set to true if the yui seed file was dynamically loaded in
* order to bootstrap components relying on the window load event
* and the `domready` custom event.
*
* @property injected
* @type boolean
* @default false
*/
/**
* If `throwFail` is set, `Y.error` will generate or re-throw a JS Error.
* Otherwise the failure is logged.
*
* @property throwFail
* @type boolean
* @default true
*/
/**
* The window/frame that this instance should operate in.
*
* @property win
* @type Window
* @default the window hosting YUI
*/
/**
* The document associated with the 'win' configuration.
*
* @property doc
* @type Document
* @default the document hosting YUI
*/
/**
* A list of modules that defines the YUI core (overrides the default).
*
* @property core
* @type string[]
*/
/**
* A list of languages in order of preference. This list is matched against
* the list of available languages in modules that the YUI instance uses to
* determine the best possible localization of language sensitive modules.
* Languages are represented using BCP 47 language tags, such as "en-GB" for
* English as used in the United Kingdom, or "zh-Hans-CN" for simplified
* Chinese as used in China. The list can be provided as a comma-separated
* list or as an array.
*
* @property lang
* @type string|string[]
*/
/**
* The default date format
* @property dateFormat
* @type string
* @deprecated use configuration in `DataType.Date.format()` instead.
*/
/**
* The default locale
* @property locale
* @type string
* @deprecated use `config.lang` instead.
*/
/**
* The default interval when polling in milliseconds.
* @property pollInterval
* @type int
* @default 20
*/
/**
* The number of dynamic nodes to insert by default before
* automatically removing them. This applies to script nodes
* because removing the node will not make the evaluated script
* unavailable. Dynamic CSS is not auto purged, because removing
* a linked style sheet will also remove the style definitions.
* @property purgethreshold
* @type int
* @default 20
*/
/**
* The default interval when polling in milliseconds.
* @property windowResizeDelay
* @type int
* @default 40
*/
/**
* Base directory for dynamic loading
* @property base
* @type string
*/
/*
* The secure base dir (not implemented)
* For dynamic loading.
* @property secureBase
* @type string
*/
/**
* The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?`
* For dynamic loading.
* @property comboBase
* @type string
*/
/**
* The root path to prepend to module path for the combo service.
* Ex: 3.0.0b1/build/
* For dynamic loading.
* @property root
* @type string
*/
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
*
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
*
* For dynamic loading.
*
* @property filter
* @type string|object
*/
/**
* The `skin` config let's you configure application level skin
* customizations. It contains the following attributes which
* can be specified to override the defaults:
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin.
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* slider: ['capsule', 'round']
* }
*
* For dynamic loading.
*
* @property skin
*/
/**
* Hash of per-component filter specification. If specified for a given
* component, this overrides the filter config.
*
* For dynamic loading.
*
* @property filters
*/
/**
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies. Turning this off will
* disable combo handling for YUI and all module groups configured
* with a combo service.
*
* For dynamic loading.
*
* @property combine
* @type boolean
* @default true if 'base' is not supplied, false if it is.
*/
/**
* A list of modules that should never be dynamically loaded
*
* @property ignore
* @type string[]
*/
/**
* A list of modules that should always be loaded when required, even if already
* present on the page.
*
* @property force
* @type string[]
*/
/**
* Node or id for a node that should be used as the insertion point for new
* nodes. For dynamic loading.
*
* @property insertBefore
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded script
* nodes.
* @property jsAttributes
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded link
* nodes.
* @property cssAttributes
* @type string
*/
/**
* Number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout.
* @property timeout
* @type int
*/
/**
* Callback for the 'CSSComplete' event. When dynamically loading YUI
* components with CSS, this property fires when the CSS is finished
* loading but script loading is still ongoing. This provides an
* opportunity to enhance the presentation of a loading page a little
* bit before the entire loading process is done.
*
* @property onCSS
* @type function
*/
/**
* A hash of module definitions to add to the list of YUI components.
* These components can then be dynamically loaded side by side with
* YUI via the `use()` method. This is a hash, the key is the module
* name, and the value is an object literal specifying the metdata
* for the module. See `Loader.addModule` for the supported module
* metadata fields. Also see groups, which provides a way to
* configure the base and combo spec for a set of modules.
*
* modules: {
* mymod1: {
* requires: ['node'],
* fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js'
* },
* mymod2: {
* requires: ['mymod1'],
* fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js'
* }
* }
*
* @property modules
* @type object
*/
/**
* A hash of module group definitions. It for each group you
* can specify a list of modules and the base path and
* combo spec to use when dynamically loading the modules.
*
* groups: {
* yui2: {
* // specify whether or not this group has a combo service
* combine: true,
*
* // the base path for non-combo paths
* base: 'http://yui.yahooapis.com/2.8.0r4/build/',
*
* // the path to the combo service
* comboBase: 'http://yui.yahooapis.com/combo?',
*
* // a fragment to prepend to the path attribute when
* // when building combo urls
* root: '2.8.0r4/build/',
*
* // the module definitions
* modules: {
* yui2_yde: {
* path: "yahoo-dom-event/yahoo-dom-event.js"
* },
* yui2_anim: {
* path: "animation/animation.js",
* requires: ['yui2_yde']
* }
* }
* }
* }
*
* @property groups
* @type object
*/
/**
* The loader 'path' attribute to the loader itself. This is combined
* with the 'base' attribute to dynamically load the loader component
* when boostrapping with the get utility alone.
*
* @property loaderPath
* @type string
* @default loader/loader-min.js
*/
/**
* Specifies whether or not YUI().use(...) will attempt to load CSS
* resources at all. Any truthy value will cause CSS dependencies
* to load when fetching script. The special value 'force' will
* cause CSS dependencies to be loaded even if no script is needed.
*
* @property fetchCSS
* @type boolean|string
* @default true
*/
/**
* The default gallery version to build gallery module urls
* @property gallery
* @type string
* @since 3.1.0
*/
/**
* The default YUI 2 version to build yui2 module urls. This is for
* intrinsic YUI 2 support via the 2in3 project. Also see the '2in3'
* config for pulling different revisions of the wrapped YUI 2
* modules.
* @since 3.1.0
* @property yui2
* @type string
* @default 2.8.1
*/
/**
* The 2in3 project is a deployment of the various versions of YUI 2
* deployed as first-class YUI 3 modules. Eventually, the wrapper
* for the modules will change (but the underlying YUI 2 code will
* be the same), and you can select a particular version of
* the wrapper modules via this config.
* @since 3.1.0
* @property 2in3
* @type string
* @default 1
*/
/**
* Alternative console log function for use in environments without
* a supported native console. The function is executed in the
* YUI instance context.
* @since 3.1.0
* @property logFn
* @type Function
*/
/**
* A callback to execute when Y.error is called. It receives the
* error message and an javascript error object if Y.error was
* executed because a javascript error was caught. The function
* is executed in the YUI instance context.
*
* @since 3.2.0
* @property errorFn
* @type Function
*/
/**
* A callback to execute when the loader fails to load one or
* more resource. This could be because of a script load
* failure. It can also fail if a javascript module fails
* to register itself, but only when the 'requireRegistration'
* is true. If this function is defined, the use() callback will
* only be called when the loader succeeds, otherwise it always
* executes unless there was a javascript error when attaching
* a module.
*
* @since 3.3.0
* @property loadErrorFn
* @type Function
*/
/**
* When set to true, the YUI loader will expect that all modules
* it is responsible for loading will be first-class YUI modules
* that register themselves with the YUI global. If this is
* set to true, loader will fail if the module registration fails
* to happen after the script is loaded.
*
* @since 3.3.0
* @property requireRegistration
* @type boolean
* @default false
*/
/**
* Cache serviced use() requests.
* @since 3.3.0
* @property cacheUse
* @type boolean
* @default true
* @deprecated no longer used
*/
/**
* The parameter defaults for the remote loader service. **Requires the rls seed file.** The properties that are supported:
*
* * `m`: comma separated list of module requirements. This
* must be the param name even for custom implemetations.
* * `v`: the version of YUI to load. Defaults to the version
* of YUI that is being used.
* * `gv`: the version of the gallery to load (see the gallery config)
* * `env`: comma separated list of modules already on the page.
* this must be the param name even for custom implemetations.
* * `lang`: the languages supported on the page (see the lang config)
* * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config).
* * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers
* * `filt`: a filter def to apply to the urls (see the filter config).
* * `filts`: a list of custom filters to apply per module
* * `tests`: this is a map of conditional module test function id keys
* with the values of 1 if the test passes, 0 if not. This must be
* the name of the querystring param in custom templates.
*
* @since 3.2.0
* @property rls
* @type {Object}
*/
/**
* The base path to the remote loader service. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_base
* @type {String}
*/
/**
* The template to use for building the querystring portion
* of the remote loader service url. The default is determined
* by the rls config -- each property that has a value will be
* represented. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_tmpl
* @type {String}
* @example
* m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests}
*
*/
/**
* Configure the instance to use a remote loader service instead of
* the client loader. **Requires the rls seed file.**
*
* @since 3.2.0
* @property use_rls
* @type {Boolean}
*/
YUI.add('yui-base', function(Y) {
/*
* YUI stub
* @module yui
* @submodule yui-base
*/
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Provides core language utilites and extensions used throughout YUI.
*
* @class Lang
* @static
*/
var L = Y.Lang || (Y.Lang = {}),
STRING_PROTO = String.prototype,
TOSTRING = Object.prototype.toString,
TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g,
TRIMREGEX = /^\s+|\s+$/g,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementation.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype);
/**
* Determines whether or not the provided item is an array.
*
* Returns `false` for array-like collections such as the function `arguments`
* collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to
* test for an array-like collection.
*
* @method isArray
* @param o The object to test.
* @return {boolean} true if o is an array.
* @static
*/
L.isArray = (!unsafeNatives && Array.isArray) || function (o) {
return L.type(o) === 'array';
};
/**
* Determines whether or not the provided item is a boolean.
* @method isBoolean
* @static
* @param o The object to test.
* @return {boolean} true if o is a boolean.
*/
L.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* <p>
* Determines whether or not the provided item is a function.
* Note: Internet Explorer thinks certain functions are objects:
* </p>
*
* <pre>
* var obj = document.createElement("object");
* Y.Lang.isFunction(obj.getAttribute) // reports false in IE
*
* var input = document.createElement("input"); // append to body
* Y.Lang.isFunction(input.focus) // reports false in IE
* </pre>
*
* <p>
* You will have to implement additional tests if these functions
* matter to you.
* </p>
*
* @method isFunction
* @static
* @param o The object to test.
* @return {boolean} true if o is a function.
*/
L.isFunction = function(o) {
return L.type(o) === 'function';
};
/**
* Determines whether or not the supplied item is a date instance.
* @method isDate
* @static
* @param o The object to test.
* @return {boolean} true if o is a date.
*/
L.isDate = function(o) {
return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* Determines whether or not the provided item is null.
* @method isNull
* @static
* @param o The object to test.
* @return {boolean} true if o is null.
*/
L.isNull = function(o) {
return o === null;
};
/**
* Determines whether or not the provided item is a legal number.
* @method isNumber
* @static
* @param o The object to test.
* @return {boolean} true if o is a number.
*/
L.isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
/**
* Determines whether or not the provided item is of type object
* or function. Note that arrays are also objects, so
* <code>Y.Lang.isObject([]) === true</code>.
* @method isObject
* @static
* @param o The object to test.
* @param failfn {boolean} fail if the input is a function.
* @return {boolean} true if o is an object.
* @see isPlainObject
*/
L.isObject = function(o, failfn) {
var t = typeof o;
return (o && (t === 'object' ||
(!failfn && (t === 'function' || L.isFunction(o))))) || false;
};
/**
* Determines whether or not the provided item is a string.
* @method isString
* @static
* @param o The object to test.
* @return {boolean} true if o is a string.
*/
L.isString = function(o) {
return typeof o === 'string';
};
/**
* Determines whether or not the provided item is undefined.
* @method isUndefined
* @static
* @param o The object to test.
* @return {boolean} true if o is undefined.
*/
L.isUndefined = function(o) {
return typeof o === 'undefined';
};
/**
* Returns a string without any leading or trailing whitespace. If
* the input is not a string, the input will be returned untouched.
* @method trim
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trim = STRING_PROTO.trim ? function(s) {
return s && s.trim ? s.trim() : s;
} : function (s) {
try {
return s.replace(TRIMREGEX, '');
} catch (e) {
return s;
}
};
/**
* Returns a string without any leading whitespace.
* @method trimLeft
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimLeft = STRING_PROTO.trimLeft ? function (s) {
return s.trimLeft();
} : function (s) {
return s.replace(/^\s+/, '');
};
/**
* Returns a string without any trailing whitespace.
* @method trimRight
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimRight = STRING_PROTO.trimRight ? function (s) {
return s.trimRight();
} : function (s) {
return s.replace(/\s+$/, '');
};
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
L.isValue = function(o) {
var t = L.type(o);
switch (t) {
case 'number':
return isFinite(o);
case 'null': // fallthru
case 'undefined':
return false;
default:
return !!t;
}
};
/**
* <p>
* Returns a string representing the type of the item passed in.
* </p>
*
* <p>
* Known issues:
* </p>
*
* <ul>
* <li>
* <code>typeof HTMLElementCollection</code> returns function in Safari, but
* <code>Y.type()</code> reports object, which could be a good thing --
* but it actually caused the logic in <code>Y.Lang.isObject</code> to fail.
* </li>
* </ul>
*
* @method type
* @param o the item to test.
* @return {string} the detected type.
* @static
*/
L.type = function(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
/**
* Lightweight version of <code>Y.substitute</code>. Uses the same template
* structure as <code>Y.substitute</code>, but doesn't support recursion,
* auto-object coersion, or formats.
* @method sub
* @param {string} s String to be modified.
* @param {object} o Object containing replacement values.
* @return {string} the substitute result.
* @static
* @since 3.2.0
*/
L.sub = function(s, o) {
return s.replace ? s.replace(SUBREGEX, function (match, key) {
return L.isUndefined(o[key]) ? match : o[key];
}) : s;
};
/**
* Returns the current time in milliseconds.
*
* @method now
* @return {Number} Current time in milliseconds.
* @static
* @since 3.3.0
*/
L.now = Date.now || function () {
return new Date().getTime();
};
/**
@module yui
@submodule yui-base
*/
var Lang = Y.Lang,
Native = Array.prototype,
hasOwn = Object.prototype.hasOwnProperty;
/**
Provides utility methods for working with arrays. Additional array helpers can
be found in the `collection` and `array-extras` modules.
`Y.Array(thing)` returns a native array created from _thing_. Depending on
_thing_'s type, one of the following will happen:
* Arrays are returned unmodified unless a non-zero _startIndex_ is
specified.
* Array-like collections (see `Array.test()`) are converted to arrays.
* For everything else, a new array is created with _thing_ as the sole
item.
Note: elements that are also collections, such as `<form>` and `<select>`
elements, are not automatically converted to arrays. To force a conversion,
pass `true` as the value of the _force_ parameter.
@class Array
@constructor
@param {Any} thing The thing to arrayify.
@param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like
collection, a subset of items starting at the specified index will be
returned.
@param {Boolean} [force=false] If `true`, _thing_ will be treated as an
array-like collection no matter what.
@return {Array} A native array created from _thing_, according to the rules
described above.
**/
function YArray(thing, startIndex, force) {
var len, result;
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
// IE throws when trying to slice HTMLElement collections.
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
/**
Dedupes an array of strings, returning an array that's guaranteed to contain
only one copy of a given string.
This method differs from `Array.unique()` in that it's optimized for use only
with strings, whereas `unique` may be used with other types (but is slower).
Using `dedupe()` with non-string values may result in unexpected behavior.
@method dedupe
@param {String[]} array Array of strings to dedupe.
@return {Array} Deduped copy of _array_.
@static
@since 3.4.0
**/
YArray.dedupe = function (array) {
var hash = {},
results = [],
i, item, len;
for (i = 0, len = array.length; i < len; ++i) {
item = array[i];
if (!hasOwn.call(hash, item)) {
hash[item] = 1;
results.push(item);
}
}
return results;
};
/**
Executes the supplied function on each item in the array. This method wraps
the native ES5 `Array.forEach()` method if available.
@method each
@param {Array} array Array to iterate.
@param {Function} fn Function to execute on each item in the array. The function
will receive the following arguments:
@param {Any} fn.item Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {YUI} The YUI instance.
@static
**/
YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) {
Native.forEach.call(array || [], fn, thisObj || Y);
return Y;
} : function (array, fn, thisObj) {
for (var i = 0, len = (array && array.length) || 0; i < len; ++i) {
if (i in array) {
fn.call(thisObj || Y, array[i], i, array);
}
}
return Y;
};
/**
Alias for `each()`.
@method forEach
@static
**/
/**
Returns an object using the first array as keys and the second as values. If
the second array is not provided, or if it doesn't contain the same number of
values as the first array, then `true` will be used in place of the missing
values.
@example
Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']);
// => {a: 'foo', b: 'bar', c: true}
@method hash
@param {String[]} keys Array of strings to use as keys.
@param {Array} [values] Array to use as values.
@return {Object} Hash using the first array as keys and the second as values.
@static
**/
YArray.hash = function (keys, values) {
var hash = {},
vlen = (values && values.length) || 0,
i, len;
for (i = 0, len = keys.length; i < len; ++i) {
if (i in keys) {
hash[keys[i]] = vlen > i && i in values ? values[i] : true;
}
}
return hash;
};
/**
Returns the index of the first item in the array that's equal (using a strict
equality check) to the specified _value_, or `-1` if the value isn't found.
This method wraps the native ES5 `Array.indexOf()` method if available.
@method indexOf
@param {Array} array Array to search.
@param {Any} value Value to search for.
@return {Number} Index of the item strictly equal to _value_, or `-1` if not
found.
@static
**/
YArray.indexOf = Native.indexOf ? function (array, value) {
// TODO: support fromIndex
return Native.indexOf.call(array, value);
} : function (array, value) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && array[i] === value) {
return i;
}
}
return -1;
};
/**
Numeric sort convenience function.
The native `Array.prototype.sort()` function converts values to strings and
sorts them in lexicographic order, which is unsuitable for sorting numeric
values. Provide `Array.numericSort` as a custom sort function when you want
to sort values in numeric order.
@example
[42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort);
// => [4, 8, 15, 16, 23, 42]
@method numericSort
@param {Number} a First value to compare.
@param {Number} b Second value to compare.
@return {Number} Difference between _a_ and _b_.
@static
**/
YArray.numericSort = function (a, b) {
return a - b;
};
/**
Executes the supplied function on each item in the array. Returning a truthy
value from the function will stop the processing of remaining items.
@method some
@param {Array} array Array to iterate over.
@param {Function} fn Function to execute on each item. The function will receive
the following arguments:
@param {Any} fn.value Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated over.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Boolean} `true` if the function returns a truthy value on any of the
items in the array; `false` otherwise.
@static
**/
YArray.some = Native.some ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
/**
Evaluates _obj_ to determine if it's an array, an array-like collection, or
something else. This is useful when working with the function `arguments`
collection and `HTMLElement` collections.
Note: This implementation doesn't consider elements that are also
collections, such as `<form>` and `<select>`, to be array-like.
@method test
@param {Object} obj Object to test.
@return {Number} A number indicating the results of the test:
* 0: Neither an array nor an array-like collection.
* 1: Real array.
* 2: Array-like collection.
@static
**/
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or alert (window),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* A simple FIFO queue. Items are added to the Queue with add(1..n items) and
* removed using next().
*
* @class Queue
* @constructor
* @param {MIXED} item* 0..n items to seed the queue.
*/
function Queue() {
this._init();
this.add.apply(this, arguments);
}
Queue.prototype = {
/**
* Initialize the queue
*
* @method _init
* @protected
*/
_init: function() {
/**
* The collection of enqueued items
*
* @property _q
* @type Array
* @protected
*/
this._q = [];
},
/**
* Get the next item in the queue. FIFO support
*
* @method next
* @return {MIXED} the next item in the queue.
*/
next: function() {
return this._q.shift();
},
/**
* Get the last in the queue. LIFO support.
*
* @method last
* @return {MIXED} the last item in the queue.
*/
last: function() {
return this._q.pop();
},
/**
* Add 0..n items to the end of the queue.
*
* @method add
* @param {MIXED} item* 0..n items.
* @return {object} this queue.
*/
add: function() {
this._q.push.apply(this._q, arguments);
return this;
},
/**
* Returns the current number of queued items.
*
* @method size
* @return {Number} The size.
*/
size: function() {
return this._q.length;
}
};
Y.Queue = Queue;
YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue();
/**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@submodule yui-base
**/
var CACHED_DELIMITER = '__',
hasOwn = Object.prototype.hasOwnProperty,
isObject = Y.Lang.isObject;
/**
Returns a wrapper for a function which caches the return value of that function,
keyed off of the combined string representation of the argument values provided
when the wrapper is called.
Calling this function again with the same arguments will return the cached value
rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful `toString()` method may result in unexpected caching behavior. For
example, the objects `{}` and `{foo: 'bar'}` would both be converted to the
string `[object Object]` when used as a cache key.
@method cached
@param {Function} source The function to memoize.
@param {Object} [cache={}] Object in which to store cached values. You may seed
this object with pre-existing cached values if desired.
@param {any} [refetch] If supplied, this value is compared with the cached value
using a `==` comparison. If the values are equal, the wrapped function is
executed again even though a cached value exists.
@return {Function} Wrapped function.
@for YUI
**/
Y.cached = function (source, cache, refetch) {
cache || (cache = {});
return function (arg) {
var key = arguments.length > 1 ?
Array.prototype.join.call(arguments, CACHED_DELIMITER) :
String(arg);
if (!(key in cache) || (refetch && cache[key] == refetch)) {
cache[key] = source.apply(source, arguments);
}
return cache[key];
};
};
/**
Returns a new object containing all of the properties of all the supplied
objects. The properties from later objects will overwrite those in earlier
objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use `clone()`.
@method merge
@param {Object} objects* One or more objects to merge.
@return {Object} A new merged object.
**/
Y.merge = function () {
var args = arguments,
i = 0,
len = args.length,
result = {};
for (; i < len; ++i) {
Y.mix(result, args[i], true);
}
return result;
};
/**
Mixes _supplier_'s properties into _receiver_.
Properties on _receiver_ or _receiver_'s prototype will not be overwritten or
shadowed unless the _overwrite_ parameter is `true`, and will not be merged
unless the _merge_ parameter is `true`.
In the default mode (0), only properties the supplier owns are copied (prototype
properties are not copied). The following copying modes are available:
* `0`: _Default_. Object to object.
* `1`: Prototype to prototype.
* `2`: Prototype to prototype and object to object.
* `3`: Prototype to object.
* `4`: Object to prototype.
@method mix
@param {Function|Object} receiver The object or function to receive the mixed
properties.
@param {Function|Object} supplier The object or function supplying the
properties to be mixed.
@param {Boolean} [overwrite=false] If `true`, properties that already exist
on the receiver will be overwritten with properties from the supplier.
@param {String[]} [whitelist] An array of property names to copy. If
specified, only the whitelisted properties will be copied, and all others
will be ignored.
@param {Number} [mode=0] Mix mode to use. See above for available modes.
@param {Boolean} [merge=false] If `true`, objects and arrays that already
exist on the receiver will have the corresponding object/array from the
supplier merged into them, rather than being skipped or overwritten. When
both _overwrite_ and _merge_ are `true`, _merge_ takes precedence.
@return {Function|Object|YUI} The receiver, or the YUI instance if the
specified receiver is falsy.
**/
Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) {
var alwaysOverwrite, exists, from, i, key, len, to;
// If no supplier is given, we return the receiver. If no receiver is given,
// we return Y. Returning Y doesn't make much sense to me, but it's
// grandfathered in for backcompat reasons.
if (!receiver || !supplier) {
return receiver || Y;
}
if (mode) {
// In mode 2 (prototype to prototype and object to object), we recurse
// once to do the proto to proto mix. The object to object mix will be
// handled later on.
if (mode === 2) {
Y.mix(receiver.prototype, supplier.prototype, overwrite,
whitelist, 0, merge);
}
// Depending on which mode is specified, we may be copying from or to
// the prototypes of the supplier and receiver.
from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
// If either the supplier or receiver doesn't actually have a
// prototype property, then we could end up with an undefined `from`
// or `to`. If that happens, we abort and return the receiver.
if (!from || !to) {
return receiver;
}
} else {
from = supplier;
to = receiver;
}
// If `overwrite` is truthy and `merge` is falsy, then we can skip a
// property existence check on each iteration and save some time.
alwaysOverwrite = overwrite && !merge;
if (whitelist) {
for (i = 0, len = whitelist.length; i < len; ++i) {
key = whitelist[i];
// We call `Object.prototype.hasOwnProperty` instead of calling
// `hasOwnProperty` on the object itself, since the object's
// `hasOwnProperty` method may have been overridden or removed.
// Also, some native objects don't implement a `hasOwnProperty`
// method.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
// If we're in merge mode, and the key is present on both
// objects, and the value on both objects is either an object or
// an array (but not a function), then we recurse to merge the
// `from` value into the `to` value instead of overwriting it.
//
// Note: It's intentional that the whitelist isn't passed to the
// recursive call here. This is legacy behavior that lots of
// code still depends on.
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
// We're not in merge mode, so we'll only copy the `from` value
// to the `to` value if we're in overwrite mode or if the
// current key doesn't exist on the `to` object.
to[key] = from[key];
}
}
} else {
for (key in from) {
// The code duplication here is for runtime performance reasons.
// Combining whitelist and non-whitelist operations into a single
// loop or breaking the shared logic out into a function both result
// in worse performance, and Y.mix is critical enough that the byte
// tradeoff is worth it.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
to[key] = from[key];
}
}
// If this is an IE browser with the JScript enumeration bug, force
// enumeration of the buggy properties by making a recursive call with
// the buggy properties as the whitelist.
if (Y.Object._hasEnumBug) {
Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge);
}
}
return receiver;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Adds utilities to the YUI instance for working with objects.
*
* @class Object
*/
var hasOwn = Object.prototype.hasOwnProperty,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementations.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype),
UNDEFINED, // <-- Note the comma. We're still declaring vars.
/**
* Returns a new object that uses _obj_ as its prototype. This method wraps the
* native ES5 `Object.create()` method if available, but doesn't currently
* pass through `Object.create()`'s second argument (properties) in order to
* ensure compatibility with older browsers.
*
* @method ()
* @param {Object} obj Prototype object.
* @return {Object} New object using _obj_ as its prototype.
* @static
*/
O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) {
// We currently wrap the native Object.create instead of simply aliasing it
// to ensure consistency with our fallback shim, which currently doesn't
// support Object.create()'s second argument (properties). Once we have a
// safe fallback for the properties arg, we can stop wrapping
// Object.create().
return Object.create(obj);
} : (function () {
// Reusable constructor function for the Object.create() shim.
function F() {}
// The actual shim.
return function (obj) {
F.prototype = obj;
return new F();
};
}()),
/**
* Property names that IE doesn't enumerate in for..in loops, even when they
* should be enumerable. When `_hasEnumBug` is `true`, it's necessary to
* manually enumerate these properties.
*
* @property _forceEnum
* @type String[]
* @protected
* @static
*/
forceEnum = O._forceEnum = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'toLocaleString',
'valueOf'
],
/**
* `true` if this browser has the JScript enumeration bug that prevents
* enumeration of the properties named in the `_forceEnum` array, `false`
* otherwise.
*
* See:
* - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug>
* - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation>
*
* @property _hasEnumBug
* @type {Boolean}
* @protected
* @static
*/
hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'),
/**
* Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or
* exists only on _obj_'s prototype. This is essentially a safer version of
* `obj.hasOwnProperty()`.
*
* @method owns
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
owns = O.owns = function (obj, key) {
return !!obj && hasOwn.call(obj, key);
}; // <-- End of var declarations.
/**
* Alias for `owns()`.
*
* @method hasKey
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
O.hasKey = owns;
/**
* Returns an array containing the object's enumerable keys. Does not include
* prototype keys or non-enumerable keys.
*
* Note that keys are returned in enumeration order (that is, in the same order
* that they would be enumerated by a `for-in` loop), which may not be the same
* as the order in which they were defined.
*
* This method is an alias for the native ES5 `Object.keys()` method if
* available.
*
* @example
*
* Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'});
* // => ['a', 'b', 'c']
*
* @method keys
* @param {Object} obj An object.
* @return {String[]} Array of keys.
* @static
*/
O.keys = (!unsafeNatives && Object.keys) || function (obj) {
if (!Y.Lang.isObject(obj)) {
throw new TypeError('Object.keys called on a non-object');
}
var keys = [],
i, key, len;
for (key in obj) {
if (owns(obj, key)) {
keys.push(key);
}
}
if (hasEnumBug) {
for (i = 0, len = forceEnum.length; i < len; ++i) {
key = forceEnum[i];
if (owns(obj, key)) {
keys.push(key);
}
}
}
return keys;
};
/**
* Returns an array containing the values of the object's enumerable keys.
*
* Note that values are returned in enumeration order (that is, in the same
* order that they would be enumerated by a `for-in` loop), which may not be the
* same as the order in which they were defined.
*
* @example
*
* Y.Object.values({a: 'foo', b: 'bar', c: 'baz'});
* // => ['foo', 'bar', 'baz']
*
* @method values
* @param {Object} obj An object.
* @return {Array} Array of values.
* @static
*/
O.values = function (obj) {
var keys = O.keys(obj),
i = 0,
len = keys.length,
values = [];
for (; i < len; ++i) {
values.push(obj[keys[i]]);
}
return values;
};
/**
* Returns the number of enumerable keys owned by an object.
*
* @method size
* @param {Object} obj An object.
* @return {Number} The object's size.
* @static
*/
O.size = function (obj) {
try {
return O.keys(obj).length;
} catch (ex) {
return 0; // Legacy behavior for non-objects.
}
};
/**
* Returns `true` if the object owns an enumerable property with the specified
* value.
*
* @method hasValue
* @param {Object} obj An object.
* @param {any} value The value to search for.
* @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise.
* @static
*/
O.hasValue = function (obj, value) {
return Y.Array.indexOf(O.values(obj), value) > -1;
};
/**
* Executes a function on each enumerable property in _obj_. The function
* receives the value, the key, and the object itself as parameters (in that
* order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method each
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {YUI} the YUI instance.
* @chainable
* @static
*/
O.each = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
fn.call(thisObj || Y, obj[key], key, obj);
}
}
return Y;
};
/**
* Executes a function on each enumerable property in _obj_, but halts if the
* function returns a truthy value. The function receives the value, the key,
* and the object itself as paramters (in that order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method some
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {Boolean} `true` if any execution of _fn_ returns a truthy value,
* `false` otherwise.
* @static
*/
O.some = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
if (fn.call(thisObj || Y, obj[key], key, obj)) {
return true;
}
}
}
return false;
};
/**
* Retrieves the sub value at the provided path,
* from the value object provided.
*
* @method getValue
* @static
* @param o The object from which to extract the property value.
* @param path {Array} A path array, specifying the object traversal path
* from which to obtain the sub value.
* @return {Any} The value stored in the path, undefined if not found,
* undefined if the source is not an object. Returns the source object
* if an empty path is provided.
*/
O.getValue = function(o, path) {
if (!Y.Lang.isObject(o)) {
return UNDEFINED;
}
var i,
p = Y.Array(path),
l = p.length;
for (i = 0; o !== UNDEFINED && i < l; i++) {
o = o[p[i]];
}
return o;
};
/**
* Sets the sub-attribute value at the provided path on the
* value object. Returns the modified value object, or
* undefined if the path is invalid.
*
* @method setValue
* @static
* @param o The object on which to set the sub value.
* @param path {Array} A path array, specifying the object traversal path
* at which to set the sub value.
* @param val {Any} The new value for the sub-attribute.
* @return {Object} The modified object, with the new sub value set, or
* undefined, if the path was invalid.
*/
O.setValue = function(o, path, val) {
var i,
p = Y.Array(path),
leafIdx = p.length - 1,
ref = o;
if (leafIdx >= 0) {
for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) {
ref = ref[p[i]];
}
if (ref !== UNDEFINED) {
ref[p[i]] = val;
} else {
return UNDEFINED;
}
}
return o;
};
/**
* Returns `true` if the object has no enumerable properties of its own.
*
* @method isEmpty
* @param {Object} obj An object.
* @return {Boolean} `true` if the object is empty.
* @static
* @since 3.2.0
*/
O.isEmpty = function (obj) {
return !O.keys(obj).length;
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* YUI user agent detection.
* Do not fork for a browser if it can be avoided. Use feature detection when
* you can. Use the user agent as a last resort. For all fields listed
* as @type float, UA stores a version number for the browser engine,
* 0 otherwise. This value may or may not map to the version number of
* the browser using the engine. The value is presented as a float so
* that it can easily be used for boolean evaluation as well as for
* looking for a particular range of versions. Because of this,
* some of the granularity of the version info may be lost. The fields that
* are @type string default to null. The API docs list the values that
* these fields can have.
* @class UA
* @static
*/
/**
* Static method on `YUI.Env` for parsing a UA string. Called at instantiation
* to populate `Y.UA`.
*
* @static
* @method parseUA
* @param {String} [subUA=navigator.userAgent] UA string to parse
* @returns {Object} The Y.UA object
*/
YUI.Env.parseUA = function(subUA) {
var numberify = function(s) {
var c = 0;
return parseFloat(s.replace(/\./g, function() {
return (c++ == 1) ? '' : '.';
}));
},
win = Y.config.win,
nav = win && win.navigator,
o = {
/**
* Internet Explorer version number or 0. Example: 6
* @property ie
* @type float
* @static
*/
ie: 0,
/**
* Opera version number or 0. Example: 9.2
* @property opera
* @type float
* @static
*/
opera: 0,
/**
* Gecko engine revision number. Will evaluate to 1 if Gecko
* is detected but the revision could not be found. Other browsers
* will be 0. Example: 1.8
* <pre>
* Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7
* Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
* Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
* Firefox 3.0 <-- 1.9
* Firefox 3.5 <-- 1.91
* </pre>
* @property gecko
* @type float
* @static
*/
gecko: 0,
/**
* AppleWebKit version. KHTML browsers that are not WebKit browsers
* will evaluate to 1, other browsers 0. Example: 418.9
* <pre>
* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
* latest available for Mac OSX 10.3.
* Safari 2.0.2: 416 <-- hasOwnProperty introduced
* Safari 2.0.4: 418 <-- preventDefault fixed
* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
* different versions of webkit
* Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been
* updated, but not updated
* to the latest patch.
* Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native
* SVG and many major issues fixed).
* Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic
* update from 2.x via the 10.4.11 OS patch.
* Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event.
* yahoo.com user agent hack removed.
* </pre>
* http://en.wikipedia.org/wiki/Safari_version_history
* @property webkit
* @type float
* @static
*/
webkit: 0,
/**
* Safari will be detected as webkit, but this property will also
* be populated with the Safari version number
* @property safari
* @type float
* @static
*/
safari: 0,
/**
* Chrome will be detected as webkit, but this property will also
* be populated with the Chrome version number
* @property chrome
* @type float
* @static
*/
chrome: 0,
/**
* The mobile property will be set to a string containing any relevant
* user agent information when a modern mobile browser is detected.
* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
* devices with the WebKit-based browser, and Opera Mini.
* @property mobile
* @type string
* @default null
* @static
*/
mobile: null,
/**
* Adobe AIR version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property air
* @type float
*/
air: 0,
/**
* Detects Apple iPad's OS version
* @property ipad
* @type float
* @static
*/
ipad: 0,
/**
* Detects Apple iPhone's OS version
* @property iphone
* @type float
* @static
*/
iphone: 0,
/**
* Detects Apples iPod's OS version
* @property ipod
* @type float
* @static
*/
ipod: 0,
/**
* General truthy check for iPad, iPhone or iPod
* @property ios
* @type float
* @default null
* @static
*/
ios: null,
/**
* Detects Googles Android OS version
* @property android
* @type float
* @static
*/
android: 0,
/**
* Detects Palms WebOS version
* @property webos
* @type float
* @static
*/
webos: 0,
/**
* Google Caja version number or 0.
* @property caja
* @type float
*/
caja: nav && nav.cajaVersion,
/**
* Set to true if the page appears to be in SSL
* @property secure
* @type boolean
* @static
*/
secure: false,
/**
* The operating system. Currently only detecting windows or macintosh
* @property os
* @type string
* @default null
* @static
*/
os: null
},
ua = subUA || nav && nav.userAgent,
loc = win && win.location,
href = loc && loc.href,
m;
/**
* The User Agent string that was parsed
* @property userAgent
* @type String
* @static
*/
o.userAgent = ua;
o.secure = href && (href.toLowerCase().indexOf('https') === 0);
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh/i).test(ua)) {
o.os = 'macintosh';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
// Modern KHTML browsers should qualify as Safari X-Grade
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
o.safari = o.webkit;
// Mobile browser check
if (/ Mobile\//.test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/);
if (m) {
// Nokia N-series, webOS, ex: NokiaN95
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
if (/Mobile/.test(ua)) {
o.mobile = 'Android';
}
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
}
m = ua.match(/Chrome\/([^\s]*)/);
if (m && m[1]) {
o.chrome = numberify(m[1]); // Chrome
o.safari = 0; //Reset safari back to 0
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
}
}
}
}
}
}
//It was a parsed UA, do not assign the global value.
if (!subUA) {
YUI.Env.UA = o;
}
return o;
};
Y.UA = YUI.Env.UA || YUI.Env.parseUA();
YUI.Env.aliases = {
"anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],
"app": ["controller","model","model-list","view"],
"attribute": ["attribute-base","attribute-complex"],
"autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],
"base": ["base-base","base-pluginhost","base-build"],
"cache": ["cache-base","cache-offline","cache-plugin"],
"collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],
"dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],
"datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],
"datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"],
"datatype": ["datatype-number","datatype-date","datatype-xml"],
"datatype-date": ["datatype-date-parse","datatype-date-format"],
"datatype-number": ["datatype-number-parse","datatype-number-format"],
"datatype-xml": ["datatype-xml-parse","datatype-xml-format"],
"dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],
"dom": ["dom-base","dom-screen","dom-style","selector-native","selector"],
"editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],
"event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"],
"event-custom": ["event-custom-base","event-custom-complex"],
"event-gestures": ["event-flick","event-move"],
"highlight": ["highlight-base","highlight-accentfold"],
"history": ["history-base","history-hash","history-hash-ie","history-html5"],
"io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],
"json": ["json-parse","json-stringify"],
"loader": ["loader-base","loader-rollup","loader-yui3"],
"node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],
"pluginhost": ["pluginhost-base","pluginhost-config"],
"querystring": ["querystring-parse","querystring-stringify"],
"recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],
"resize": ["resize-base","resize-proxy","resize-constrain"],
"slider": ["slider-base","slider-value-range","clickable-rail","range-slider"],
"text": ["text-accentfold","text-wordbreak"],
"widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"]
};
}, '@VERSION@' );
YUI.add('get', function(Y) {
/**
* Provides a mechanism to fetch remote resources and
* insert them into a document.
* @module yui
* @submodule get
*/
/**
* Fetches and inserts one or more script or link nodes into the document
* @class Get
* @static
*/
var ua = Y.UA,
L = Y.Lang,
TYPE_JS = 'text/javascript',
TYPE_CSS = 'text/css',
STYLESHEET = 'stylesheet',
SCRIPT = 'script',
AUTOPURGE = 'autopurge',
UTF8 = 'utf-8',
LINK = 'link',
ASYNC = 'async',
ALL = true,
// FireFox does not support the onload event for link nodes, so
// there is no way to make the css requests synchronous. This means
// that the css rules in multiple files could be applied out of order
// in this browser if a later request returns before an earlier one.
// Safari too.
ONLOAD_SUPPORTED = {
script: ALL,
css: !(ua.webkit || ua.gecko)
},
/**
* hash of queues to manage multiple requests
* @property queues
* @private
*/
queues = {},
/**
* queue index used to generate transaction ids
* @property qidx
* @type int
* @private
*/
qidx = 0,
/**
* interal property used to prevent multiple simultaneous purge
* processes
* @property purging
* @type boolean
* @private
*/
purging,
/**
* Clear timeout state
*
* @method _clearTimeout
* @param {Object} q Queue data
* @private
*/
_clearTimeout = function(q) {
var timer = q.timer;
if (timer) {
clearTimeout(timer);
q.timer = null;
}
},
/**
* Generates an HTML element, this is not appended to a document
* @method _node
* @param {string} type the type of element.
* @param {Object} attr the fixed set of attribute for the type.
* @param {Object} custAttrs optional Any custom attributes provided by the user.
* @param {Window} win optional window to create the element in.
* @return {HTMLElement} the generated node.
* @private
*/
_node = function(type, attr, custAttrs, win) {
var w = win || Y.config.win,
d = w.document,
n = d.createElement(type),
i;
if (custAttrs) {
Y.mix(attr, custAttrs);
}
for (i in attr) {
if (attr[i] && attr.hasOwnProperty(i)) {
n.setAttribute(i, attr[i]);
}
}
return n;
},
/**
* Generates a link node
* @method _linkNode
* @param {string} url the url for the css file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_linkNode = function(url, win, attributes) {
return _node(LINK, {
id: Y.guid(),
type: TYPE_CSS,
rel: STYLESHEET,
href: url
}, attributes, win);
},
/**
* Generates a script node
* @method _scriptNode
* @param {string} url the url for the script file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_scriptNode = function(url, win, attributes) {
return _node(SCRIPT, {
id: Y.guid(),
type: TYPE_JS,
src: url
}, attributes, win);
},
/**
* Returns the data payload for callback functions.
* @method _returnData
* @param {object} q the queue.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @return {object} the state data from the request.
* @private
*/
_returnData = function(q, msg, result) {
return {
tId: q.tId,
win: q.win,
data: q.data,
nodes: q.nodes,
msg: msg,
statusText: result,
purge: function() {
_purge(this.tId);
}
};
},
/**
* The transaction is finished
* @method _end
* @param {string} id the id of the request.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @private
*/
_end = function(id, msg, result) {
var q = queues[id],
onEnd = q && q.onEnd;
q.finished = true;
if (onEnd) {
onEnd.call(q.context, _returnData(q, msg, result));
}
},
/**
* The request failed, execute fail handler with whatever
* was accomplished. There isn't a failure case at the
* moment unless you count aborted transactions
* @method _fail
* @param {string} id the id of the request
* @private
*/
_fail = function(id, msg) {
var q = queues[id],
onFailure = q.onFailure;
_clearTimeout(q);
if (onFailure) {
onFailure.call(q.context, _returnData(q, msg));
}
_end(id, msg, 'failure');
},
/**
* Abort the transaction
*
* @method _abort
* @param {Object} id
* @private
*/
_abort = function(id) {
_fail(id, 'transaction ' + id + ' was aborted');
},
/**
* The request is complete, so executing the requester's callback
* @method _complete
* @param {string} id the id of the request.
* @private
*/
_complete = function(id) {
var q = queues[id],
onSuccess = q.onSuccess;
_clearTimeout(q);
if (q.aborted) {
_abort(id);
} else {
if (onSuccess) {
onSuccess.call(q.context, _returnData(q));
}
// 3.3.0 had undefined msg for this path.
_end(id, undefined, 'OK');
}
},
/**
* Get node reference, from string
*
* @method _getNodeRef
* @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned.
* @param {String} tId Queue id, used to determine document for queue
* @private
*/
_getNodeRef = function(nId, tId) {
var q = queues[tId],
n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
if (!n) {
_fail(tId, 'target node not found: ' + nId);
}
return n;
},
/**
* Removes the nodes for the specified queue
* @method _purge
* @param {string} tId the transaction id.
* @private
*/
_purge = function(tId) {
var nodes, doc, parent, sibling, node, attr, insertBefore,
i, l,
q = queues[tId];
if (q) {
nodes = q.nodes;
l = nodes.length;
// TODO: Why is node.parentNode undefined? Which forces us to do this...
/*
doc = q.win.document;
parent = doc.getElementsByTagName('head')[0];
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0];
if (insertBefore) {
sibling = _getNodeRef(insertBefore, tId);
if (sibling) {
parent = sibling.parentNode;
}
}
*/
for (i = 0; i < l; i++) {
node = nodes[i];
parent = node.parentNode;
if (node.clearAttributes) {
node.clearAttributes();
} else {
// This destroys parentNode ref, so we hold onto it above first.
for (attr in node) {
if (node.hasOwnProperty(attr)) {
delete node[attr];
}
}
}
parent.removeChild(node);
}
}
q.nodes = [];
},
/**
* Progress callback
*
* @method _progress
* @param {string} id The id of the request.
* @param {string} The url which just completed.
* @private
*/
_progress = function(id, url) {
var q = queues[id],
onProgress = q.onProgress,
o;
if (onProgress) {
o = _returnData(q);
o.url = url;
onProgress.call(q.context, o);
}
},
/**
* Timeout detected
* @method _timeout
* @param {string} id the id of the request.
* @private
*/
_timeout = function(id) {
var q = queues[id],
onTimeout = q.onTimeout;
if (onTimeout) {
onTimeout.call(q.context, _returnData(q));
}
_end(id, 'timeout', 'timeout');
},
/**
* onload callback
* @method _loaded
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_loaded = function(id, url) {
var q = queues[id],
sync = (q && !q.async);
if (!q) {
return;
}
if (sync) {
_clearTimeout(q);
}
_progress(id, url);
// TODO: Cleaning up flow to have a consistent end point
// !q.finished check is for the async case,
// where scripts may still be loading when we've
// already aborted. Ideally there should be a single path
// for this.
if (!q.finished) {
if (q.aborted) {
_abort(id);
} else {
if ((--q.remaining) === 0) {
_complete(id);
} else if (sync) {
_next(id);
}
}
}
},
/**
* Detects when a node has been loaded. In the case of
* script nodes, this does not guarantee that contained
* script is ready to use.
* @method _trackLoad
* @param {string} type the type of node to track.
* @param {HTMLElement} n the node to track.
* @param {string} id the id of the request.
* @param {string} url the url that is being loaded.
* @private
*/
_trackLoad = function(type, n, id, url) {
// TODO: Can we massage this to use ONLOAD_SUPPORTED[type]?
// IE supports the readystatechange event for script and css nodes
// Opera only for script nodes. Opera support onload for script
// nodes, but this doesn't fire when there is a load failure.
// The onreadystatechange appears to be a better way to respond
// to both success and failure.
if (ua.ie) {
n.onreadystatechange = function() {
var rs = this.readyState;
if ('loaded' === rs || 'complete' === rs) {
n.onreadystatechange = null;
_loaded(id, url);
}
};
} else if (ua.webkit) {
// webkit prior to 3.x is no longer supported
if (type === SCRIPT) {
// Safari 3.x supports the load event for script nodes (DOM2)
n.addEventListener('load', function() {
_loaded(id, url);
}, false);
}
} else {
// FireFox and Opera support onload (but not DOM2 in FF) handlers for
// script nodes. Opera, but not FF, supports the onload event for link nodes.
n.onload = function() {
_loaded(id, url);
};
n.onerror = function(e) {
_fail(id, e + ': ' + url);
};
}
},
_insertInDoc = function(node, id, win) {
// Add it to the head or insert it before 'insertBefore'.
// Work around IE bug if there is a base tag.
var q = queues[id],
doc = win.document,
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0],
sibling;
if (insertBefore) {
sibling = _getNodeRef(insertBefore, id);
if (sibling) {
sibling.parentNode.insertBefore(node, sibling);
}
} else {
// 3.3.0 assumed head is always around.
doc.getElementsByTagName('head')[0].appendChild(node);
}
},
/**
* Loads the next item for a given request
* @method _next
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_next = function(id) {
// Assigning out here for readability
var q = queues[id],
type = q.type,
attrs = q.attributes,
win = q.win,
timeout = q.timeout,
node,
url;
if (q.url.length > 0) {
url = q.url.shift();
// !q.timer ensures that this only happens once for async
if (timeout && !q.timer) {
q.timer = setTimeout(function() {
_timeout(id);
}, timeout);
}
if (type === SCRIPT) {
node = _scriptNode(url, win, attrs);
} else {
node = _linkNode(url, win, attrs);
}
// add the node to the queue so we can return it in the callback
q.nodes.push(node);
_trackLoad(type, node, id, url);
_insertInDoc(node, id, win);
if (!ONLOAD_SUPPORTED[type]) {
_loaded(id, url);
}
if (q.async) {
// For sync, the _next call is chained in _loaded
_next(id);
}
}
},
/**
* Removes processed queues and corresponding nodes
* @method _autoPurge
* @private
*/
_autoPurge = function() {
if (purging) {
return;
}
purging = true;
var i, q;
for (i in queues) {
if (queues.hasOwnProperty(i)) {
q = queues[i];
if (q.autopurge && q.finished) {
_purge(q.tId);
delete queues[i];
}
}
}
purging = false;
},
/**
* Saves the state for the request and begins loading
* the requested urls
* @method queue
* @param {string} type the type of node to insert.
* @param {string} url the url to load.
* @param {object} opts the hash of options for this request.
* @return {object} transaction object.
* @private
*/
_queue = function(type, url, opts) {
opts = opts || {};
var id = 'q' + (qidx++),
thresh = opts.purgethreshold || Y.Get.PURGE_THRESH,
q;
if (qidx % thresh === 0) {
_autoPurge();
}
// Merge to protect opts (grandfathered in).
q = queues[id] = Y.merge(opts);
// Avoid mix, merge overhead. Known set of props.
q.tId = id;
q.type = type;
q.url = url;
q.finished = false;
q.nodes = [];
q.win = q.win || Y.config.win;
q.context = q.context || q;
q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false;
q.attributes = q.attributes || {};
q.attributes.charset = opts.charset || q.attributes.charset || UTF8;
if (ASYNC in q && type === SCRIPT) {
q.attributes.async = q.async;
}
q.url = (L.isString(q.url)) ? [q.url] : q.url;
// TODO: Do we really need to account for this developer error?
// If the url is undefined, this is probably a trailing comma problem in IE.
if (!q.url[0]) {
q.url.shift();
}
q.remaining = q.url.length;
_next(id);
return {
tId: id
};
};
Y.Get = {
/**
* The number of request required before an automatic purge.
* Can be configured via the 'purgethreshold' config
* @property PURGE_THRESH
* @static
* @type int
* @default 20
* @private
*/
PURGE_THRESH: 20,
/**
* Abort a transaction
* @method abort
* @static
* @param {string|object} o Either the tId or the object returned from
* script() or css().
*/
abort : function(o) {
var id = (L.isString(o)) ? o : o.tId,
q = queues[id];
if (q) {
q.aborted = true;
}
},
/**
* Fetches and inserts one or more script nodes into the head
* of the current document or the document in a specified window.
*
* @method script
* @static
* @param {string|string[]} url the url or urls to the script(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the script(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onTimeout</dt>
* <dd>
* callback to execute when a timeout occurs.
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onEnd</dt>
* <dd>a function that executes when the transaction finishes,
* regardless of the exit path</dd>
* <dt>onFailure</dt>
* <dd>
* callback to execute when the script load operation fails
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted successfully</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove any nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading
* (useful when passing in an array of js files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code>
* property, which identifies the file which was loaded.</dd>
* <dt>async</dt>
* <dd>
* <p>When passing in an array of JS files, setting this flag to true
* will insert them into the document in parallel, as opposed to the
* default behavior, which is to chain load them serially. It will also
* set the async attribute on the script node to true.</p>
* <p>Setting async:true
* will lead to optimal file download performance allowing the browser to
* download multiple scripts in parallel, and execute them as soon as they
* are available.</p>
* <p>Note that async:true does not guarantee execution order of the
* scripts being downloaded. They are executed in whichever order they
* are received.</p>
* </dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>autopurge</dt>
* <dd>
* setting to true will let the utilities cleanup routine purge
* the script once loaded
* </dd>
* <dt>purgethreshold</dt>
* <dd>
* The number of transaction before autopurge should be initiated
* </dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callback when the script(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling.
* If this is not specified, nodes will be inserted before a base
* tag should it exist. Otherwise, the nodes will be appended to the
* end of the document head.</dd>
* </dl>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* <dt>timeout</dt>
* <dd>Number of milliseconds to wait before aborting and firing
* the timeout event</dd>
* <pre>
* Y.Get.script(
* ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
* "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"],
* {
* onSuccess: function(o) {
* this.log("won't cause error because Y is the context");
* // immediately
* },
* onFailure: function(o) {
* },
* onTimeout: function(o) {
* },
* data: "foo",
* timeout: 10000, // 10 second timeout
* context: Y, // make the YUI instance
* // win: otherframe // target another window/frame
* autopurge: true // allow the utility to choose when to
* // remove the nodes
* purgetheshold: 1 // purge previous transaction before
* // next transaction
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
script: function(url, opts) {
return _queue(SCRIPT, url, opts);
},
/**
* Fetches and inserts one or more css link nodes into the
* head of the current document or the document in a specified
* window.
* @method css
* @static
* @param {string} url the url or urls to the css file(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the css file(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>win</dl>
* <dd>the window the link nodes(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers,
* where onload for css is detected accurately.</dd>
* <dt>async</dt>
* <dd>When passing in an array of css files, setting this flag to true will insert them
* into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible).
* This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callbacks when the nodes(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling</dd>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* </dl>
* <pre>
* Y.Get.css("http://localhost/css/menu.css");
* </pre>
* <pre>
* Y.Get.css(
* ["http://localhost/css/menu.css",
* insertBefore: 'custom-styles' // nodes will be inserted
* // before the specified node
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
css: function(url, opts) {
return _queue('css', url, opts);
}
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('features', function(Y) {
var feature_tests = {};
/**
Contains the core of YUI's feature test architecture.
@module features
*/
/**
* Feature detection
* @class Features
* @static
*/
Y.mix(Y.namespace('Features'), {
/**
* Object hash of all registered feature tests
* @property tests
* @type Object
*/
tests: feature_tests,
/**
* Add a test to the system
*
* ```
* Y.Features.add("load", "1", {});
* ```
*
* @method add
* @param {String} cat The category, right now only 'load' is supported
* @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3
* @param {Object} o Object containing test properties
* @param {String} o.name The name of the test
* @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance
* @param {String} o.trigger The module that triggers this test.
*/
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
/**
* Execute all tests of a given category and return the serialized results
*
* ```
* caps=1:1;2:1;3:0
* ```
* @method all
* @param {String} cat The category to execute
* @param {Array} args The arguments to pass to the test function
* @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0
*/
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
/**
* Run a sepecific test and return a Boolean response.
*
* ```
* Y.Features.test("load", "1");
* ```
*
* @method test
* @param {String} cat The category of the test to run
* @param {String} name The name of the test to run
* @param {Array} args The arguments to pass to the test function
* @return {Boolean} True or false if the test passed/failed.
*/
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by src/loader/scripts/meta_join.py */
var add = Y.Features.add;
// graphics-canvas-default
add('load', '0', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// autocomplete-list-keys
add('load', '1', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// graphics-svg
add('load', '2', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '3', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// graphics-vml-default
add('load', '4', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '5', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// widget-base-ie
add('load', '6', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// transition-timer
add('load', '7', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// dom-style-ie
add('load', '8', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// selector-css2
add('load', '9', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// event-base-ie
add('load', '10', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// dd-gestures
add('load', '11', {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
});
// scrollview-base-ie
add('load', '12', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// graphics-canvas
add('load', '13', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-vml
add('load', '14', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('intl-base', function(Y) {
/**
* The Intl utility provides a central location for managing sets of
* localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
var SPLIT_REGEX = /[, ]/;
Y.mix(Y.namespace('Intl'), {
/**
* Returns the language among those available that
* best matches the preferred language list, using the Lookup
* algorithm of BCP 47.
* If none of the available languages meets the user's preferences,
* then "" is returned.
* Extended language ranges are not supported.
*
* @method lookupBestLang
* @param {String[] | String} preferredLanguages The list of preferred
* languages in descending preference order, represented as BCP 47
* language tags. A string array or a comma-separated list.
* @param {String[]} availableLanguages The list of languages
* that the application supports, represented as BCP 47 language
* tags.
*
* @return {String} The available language that best matches the
* preferred language list, or "".
* @since 3.1.0
*/
lookupBestLang: function(preferredLanguages, availableLanguages) {
var i, language, result, index;
// check whether the list of available languages contains language;
// if so return it
function scan(language) {
var i;
for (i = 0; i < availableLanguages.length; i += 1) {
if (language.toLowerCase() ===
availableLanguages[i].toLowerCase()) {
return availableLanguages[i];
}
}
}
if (Y.Lang.isString(preferredLanguages)) {
preferredLanguages = preferredLanguages.split(SPLIT_REGEX);
}
for (i = 0; i < preferredLanguages.length; i += 1) {
language = preferredLanguages[i];
if (!language || language === '*') {
continue;
}
// check the fallback sequence for one language
while (language.length > 0) {
result = scan(language);
if (result) {
return result;
} else {
index = language.lastIndexOf('-');
if (index >= 0) {
language = language.substring(0, index);
// one-character subtags get cut along with the
// following subtag
if (index >= 2 && language.charAt(index - 2) === '-') {
language = language.substring(0, index - 2);
}
} else {
// nothing available for this language
break;
}
}
}
}
return '';
}
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-log', function(Y) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 1,
warn: 1,
error: 1 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
if (src) {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console != UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera != UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher == Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-later', function(Y) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('loader-base', function(Y) {
/**
* The YUI loader core
* @module loader
* @submodule loader-base
*/
if (!YUI.Env[Y.version]) {
(function() {
var VERSION = Y.version,
BUILD = '/build/',
ROOT = VERSION + BUILD,
CDN_BASE = Y.Env.base,
GALLERY_VERSION = 'gallery-2011.09.14-20-40',
TNT = '2in3',
TNT_VERSION = '4',
YUI2_VERSION = '2.9.0',
COMBO_BASE = CDN_BASE + 'combo?',
META = { version: VERSION,
root: ROOT,
base: Y.Env.base,
comboBase: COMBO_BASE,
skin: { defaultSkin: 'sam',
base: 'assets/skins/',
path: 'skin.css',
after: ['cssreset',
'cssfonts',
'cssgrids',
'cssbase',
'cssreset-context',
'cssfonts-context']},
groups: {},
patterns: {} },
groups = META.groups,
yui2Update = function(tnt, yui2) {
var root = TNT + '.' +
(tnt || TNT_VERSION) + '/' +
(yui2 || YUI2_VERSION) + BUILD;
groups.yui2.base = CDN_BASE + root;
groups.yui2.root = root;
},
galleryUpdate = function(tag) {
var root = (tag || GALLERY_VERSION) + BUILD;
groups.gallery.base = CDN_BASE + root;
groups.gallery.root = root;
};
groups[VERSION] = {};
groups.gallery = {
ext: false,
combine: true,
comboBase: COMBO_BASE,
update: galleryUpdate,
patterns: { 'gallery-': { },
'lang/gallery-': {},
'gallerycss-': { type: 'css' } }
};
groups.yui2 = {
combine: true,
ext: false,
comboBase: COMBO_BASE,
update: yui2Update,
patterns: {
'yui2-': {
configFn: function(me) {
if (/-skin|reset|fonts|grids|base/.test(me.name)) {
me.type = 'css';
me.path = me.path.replace(/\.js/, '.css');
// this makes skins in builds earlier than
// 2.6.0 work as long as combine is false
me.path = me.path.replace(/\/yui2-skin/,
'/assets/skins/sam/yui2-skin');
}
}
}
}
};
galleryUpdate();
yui2Update();
YUI.Env[VERSION] = META;
}());
}
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* @module loader
* @main loader
* @submodule loader-base
*/
var NOT_FOUND = {},
NO_REQUIREMENTS = [],
MAX_URL_LENGTH = 2048,
GLOBAL_ENV = YUI.Env,
GLOBAL_LOADED = GLOBAL_ENV._loaded,
CSS = 'css',
JS = 'js',
INTL = 'intl',
VERSION = Y.version,
ROOT_LANG = '',
YObject = Y.Object,
oeach = YObject.each,
YArray = Y.Array,
_queue = GLOBAL_ENV._loaderQueue,
META = GLOBAL_ENV[VERSION],
SKIN_PREFIX = 'skin-',
L = Y.Lang,
ON_PAGE = GLOBAL_ENV.mods,
modulekey,
cache,
_path = function(dir, file, type, nomin) {
var path = dir + '/' + file;
if (!nomin) {
path += '-min';
}
path += '.' + (type || CSS);
return path;
};
if (YUI.Env.aliases) {
YUI.Env.aliases = {}; //Don't need aliases if Loader is present
}
/**
* The component metadata is stored in Y.Env.meta.
* Part of the loader module.
* @property meta
* @for YUI
*/
Y.Env.meta = META;
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* While the loader can be instantiated by the end user, it normally is not.
* @see YUI.use for the normal use case. The use function automatically will
* pull in missing dependencies.
*
* @constructor
* @class Loader
* @param {object} o an optional set of configuration options. Valid options:
* <ul>
* <li>base:
* The base dir</li>
* <li>comboBase:
* The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li>
* <li>root:
* The root path to prepend to module names for the combo service.
* Ex: 2.5.2/build/</li>
* <li>filter:.
*
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).
* </dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
*
* </li>
* <li>filters: per-component filter specification. If specified
* for a given component, this overrides the filter config. _Note:_ This does not work on combo urls, use the filter property instead.</li>
* <li>combine:
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies</li>
* <li>ignore:
* A list of modules that should never be dynamically loaded</li>
* <li>force:
* A list of modules that should always be loaded when required, even if
* already present on the page</li>
* <li>insertBefore:
* Node or id for a node that should be used as the insertion point for
* new nodes</li>
* <li>charset:
* charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes)
* </li>
* <li>jsAttributes: object literal containing attributes to add to script
* nodes</li>
* <li>cssAttributes: object literal containing attributes to add to link
* nodes</li>
* <li>timeout:
* The number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout</li>
* <li>context:
* execution context for all callbacks</li>
* <li>onSuccess:
* callback for the 'success' event</li>
* <li>onFailure: callback for the 'failure' event</li>
* <li>onCSS: callback for the 'CSSComplete' event. When loading YUI
* components with CSS the CSS is loaded first, then the script. This
* provides a moment you can tie into to improve
* the presentation of the page while the script is loading.</li>
* <li>onTimeout:
* callback for the 'timeout' event</li>
* <li>onProgress:
* callback executed each time a script or css file is loaded</li>
* <li>modules:
* A list of module definitions. See Loader.addModule for the supported
* module metadata</li>
* <li>groups:
* A list of group definitions. Each group can contain specific definitions
* for base, comboBase, combine, and accepts a list of modules. See above
* for the description of these properties.</li>
* <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic
* support for YUI 2 modules in YUI 3 relies on versions of the YUI 2
* components inside YUI 3 module wrappers. These wrappers
* change over time to accomodate the issues that arise from running YUI 2
* in a YUI 3 sandbox.</li>
* <li>yui2: when using the 2in3 project, you can select the version of
* YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0,
* 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2
* going forward.</li>
* </ul>
*/
Y.Loader = function(o) {
var defaults = META.modules,
self = this;
modulekey = META.md5;
/**
* Internal callback to handle multiple internal insert() calls
* so that css is inserted prior to js
* @property _internalCallback
* @private
*/
// self._internalCallback = null;
/**
* Callback that will be executed when the loader is finished
* with an insert
* @method onSuccess
* @type function
*/
// self.onSuccess = null;
/**
* Callback that will be executed if there is a failure
* @method onFailure
* @type function
*/
// self.onFailure = null;
/**
* Callback for the 'CSSComplete' event. When loading YUI components
* with CSS the CSS is loaded first, then the script. This provides
* a moment you can tie into to improve the presentation of the page
* while the script is loading.
* @method onCSS
* @type function
*/
// self.onCSS = null;
/**
* Callback executed each time a script or css file is loaded
* @method onProgress
* @type function
*/
// self.onProgress = null;
/**
* Callback that will be executed if a timeout occurs
* @method onTimeout
* @type function
*/
// self.onTimeout = null;
/**
* The execution context for all callbacks
* @property context
* @default {YUI} the YUI instance
*/
self.context = Y;
/**
* Data that is passed to all callbacks
* @property data
*/
// self.data = null;
/**
* Node reference or id where new nodes should be inserted before
* @property insertBefore
* @type string|HTMLElement
*/
// self.insertBefore = null;
/**
* The charset attribute for inserted nodes
* @property charset
* @type string
* @deprecated , use cssAttributes or jsAttributes.
*/
// self.charset = null;
/**
* An object literal containing attributes to add to link nodes
* @property cssAttributes
* @type object
*/
// self.cssAttributes = null;
/**
* An object literal containing attributes to add to script nodes
* @property jsAttributes
* @type object
*/
// self.jsAttributes = null;
/**
* The base directory.
* @property base
* @type string
* @default http://yui.yahooapis.com/[YUI VERSION]/build/
*/
self.base = Y.Env.meta.base + Y.Env.meta.root;
/**
* Base path for the combo service
* @property comboBase
* @type string
* @default http://yui.yahooapis.com/combo?
*/
self.comboBase = Y.Env.meta.comboBase;
/*
* Base path for language packs.
*/
// self.langBase = Y.Env.meta.langBase;
// self.lang = "";
/**
* If configured, the loader will attempt to use the combo
* service for YUI resources and configured external resources.
* @property combine
* @type boolean
* @default true if a base dir isn't in the config
*/
self.combine = o.base &&
(o.base.indexOf(self.comboBase.substr(0, 20)) > -1);
/**
* The default seperator to use between files in a combo URL
* @property comboSep
* @type {String}
* @default Ampersand
*/
self.comboSep = '&';
/**
* Max url length for combo urls. The default is 2048. This is the URL
* limit for the Yahoo! hosted combo servers. If consuming
* a different combo service that has a different URL limit
* it is possible to override this default by supplying
* the maxURLLength config option. The config option will
* only take effect if lower than the default.
*
* @property maxURLLength
* @type int
*/
self.maxURLLength = MAX_URL_LENGTH;
/**
* Ignore modules registered on the YUI global
* @property ignoreRegistered
* @default false
*/
// self.ignoreRegistered = false;
/**
* Root path to prepend to module path for the combo
* service
* @property root
* @type string
* @default [YUI VERSION]/build/
*/
self.root = Y.Env.meta.root;
/**
* Timeout value in milliseconds. If set, self value will be used by
* the get utility. the timeout event will fire if
* a timeout occurs.
* @property timeout
* @type int
*/
self.timeout = 0;
/**
* A list of modules that should not be loaded, even if
* they turn up in the dependency tree
* @property ignore
* @type string[]
*/
// self.ignore = null;
/**
* A list of modules that should always be loaded, even
* if they have already been inserted into the page.
* @property force
* @type string[]
*/
// self.force = null;
self.forceMap = {};
/**
* Should we allow rollups
* @property allowRollup
* @type boolean
* @default false
*/
self.allowRollup = false;
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).
* </dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
* @property filter
* @type string| {searchExp: string, replaceStr: string}
*/
// self.filter = null;
/**
* per-component filter specification. If specified for a given
* component, this overrides the filter config.
* @property filters
* @type object
*/
self.filters = {};
/**
* The list of requested modules
* @property required
* @type {string: boolean}
*/
self.required = {};
/**
* If a module name is predefined when requested, it is checked againsts
* the patterns provided in this property. If there is a match, the
* module is added with the default configuration.
*
* At the moment only supporting module prefixes, but anticipate
* supporting at least regular expressions.
* @property patterns
* @type Object
*/
// self.patterns = Y.merge(Y.Env.meta.patterns);
self.patterns = {};
/**
* The library metadata
* @property moduleInfo
*/
// self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo);
self.moduleInfo = {};
self.groups = Y.merge(Y.Env.meta.groups);
/**
* Provides the information used to skin the skinnable components.
* The following skin definition would result in 'skin1' and 'skin2'
* being loaded for calendar (if calendar was requested), and
* 'sam' for all other skinnable components:
*
* <code>
* skin: {
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin. ex:
* // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* calendar: ['skin1', 'skin2']
* }
* }
* </code>
* @property skin
*/
self.skin = Y.merge(Y.Env.meta.skin);
/*
* Map of conditional modules
* @since 3.2.0
*/
self.conditions = {};
// map of modules with a hash of modules that meet the requirement
// self.provides = {};
self.config = o;
self._internal = true;
cache = GLOBAL_ENV._renderedMods;
if (cache) {
oeach(cache, function modCache(v, k) {
//self.moduleInfo[k] = Y.merge(v);
self.moduleInfo[k] = v;
});
cache = GLOBAL_ENV._conditions;
oeach(cache, function condCache(v, k) {
//self.conditions[k] = Y.merge(v);
self.conditions[k] = v;
});
} else {
oeach(defaults, self.addModule, self);
}
if (!GLOBAL_ENV._renderedMods) {
//GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo);
//GLOBAL_ENV._conditions = Y.merge(self.conditions);
GLOBAL_ENV._renderedMods = self.moduleInfo;
GLOBAL_ENV._conditions = self.conditions;
}
self._inspectPage();
self._internal = false;
self._config(o);
self.testresults = null;
if (Y.config.tests) {
self.testresults = Y.config.tests;
}
/**
* List of rollup files found in the library metadata
* @property rollups
*/
// self.rollups = null;
/**
* Whether or not to load optional dependencies for
* the requested modules
* @property loadOptional
* @type boolean
* @default false
*/
// self.loadOptional = false;
/**
* All of the derived dependencies in sorted order, which
* will be populated when either calculate() or insert()
* is called
* @property sorted
* @type string[]
*/
self.sorted = [];
/**
* Set when beginning to compute the dependency tree.
* Composed of what YUI reports to be loaded combined
* with what has been loaded by any instance on the page
* with the version number specified in the metadata.
* @property loaded
* @type {string: boolean}
*/
self.loaded = GLOBAL_LOADED[VERSION];
/*
* A list of modules to attach to the YUI instance when complete.
* If not supplied, the sorted list of dependencies are applied.
* @property attaching
*/
// self.attaching = null;
/**
* Flag to indicate the dependency tree needs to be recomputed
* if insert is called again.
* @property dirty
* @type boolean
* @default true
*/
self.dirty = true;
/**
* List of modules inserted by the utility
* @property inserted
* @type {string: boolean}
*/
self.inserted = {};
/**
* List of skipped modules during insert() because the module
* was not defined
* @property skipped
*/
self.skipped = {};
// Y.on('yui:load', self.loadNext, self);
self.tested = {};
/*
* Cached sorted calculate results
* @property results
* @since 3.2.0
*/
//self.results = {};
};
Y.Loader.prototype = {
FILTER_DEFS: {
RAW: {
'searchExp': '-min\\.js',
'replaceStr': '.js'
},
DEBUG: {
'searchExp': '-min\\.js',
'replaceStr': '-debug.js'
}
},
/*
* Check the pages meta-data and cache the result.
* @method _inspectPage
* @private
*/
_inspectPage: function() {
oeach(ON_PAGE, function(v, k) {
if (v.details) {
var m = this.moduleInfo[k],
req = v.details.requires,
mr = m && m.requires;
if (m) {
if (!m._inspected && req && mr.length != req.length) {
// console.log('deleting ' + m.name);
// m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr)));
delete m.expanded;
// delete m.expanded_map;
}
} else {
m = this.addModule(v.details, k);
}
m._inspected = true;
}
}, this);
},
/*
* returns true if b is not loaded, and is required directly or by means of modules it supersedes.
* @private
* @method _requires
* @param {String} mod1 The first module to compare
* @param {String} mod2 The second module to compare
*/
_requires: function(mod1, mod2) {
var i, rm, after_map, s,
info = this.moduleInfo,
m = info[mod1],
other = info[mod2];
if (!m || !other) {
return false;
}
rm = m.expanded_map;
after_map = m.after_map;
// check if this module should be sorted after the other
// do this first to short circut circular deps
if (after_map && (mod2 in after_map)) {
return true;
}
after_map = other.after_map;
// and vis-versa
if (after_map && (mod1 in after_map)) {
return false;
}
// check if this module requires one the other supersedes
s = info[mod2] && info[mod2].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod1, s[i])) {
return true;
}
}
}
s = info[mod1] && info[mod1].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod2, s[i])) {
return false;
}
}
}
// check if this module requires the other directly
// if (r && YArray.indexOf(r, mod2) > -1) {
if (rm && (mod2 in rm)) {
return true;
}
// external css files should be sorted below yui css
if (m.ext && m.type == CSS && !other.ext && other.type == CSS) {
return true;
}
return false;
},
/**
* Apply a new config to the Loader instance
* @method _config
* @param {Object} o The new configuration
*/
_config: function(o) {
var i, j, val, f, group, groupName, self = this;
// apply config values
if (o) {
for (i in o) {
if (o.hasOwnProperty(i)) {
val = o[i];
if (i == 'require') {
self.require(val);
} else if (i == 'skin') {
Y.mix(self.skin, o[i], true);
} else if (i == 'groups') {
for (j in val) {
if (val.hasOwnProperty(j)) {
groupName = j;
group = val[j];
self.addGroup(group, groupName);
}
}
} else if (i == 'modules') {
// add a hash of module definitions
oeach(val, self.addModule, self);
} else if (i == 'gallery') {
this.groups.gallery.update(val);
} else if (i == 'yui2' || i == '2in3') {
this.groups.yui2.update(o['2in3'], o.yui2);
} else if (i == 'maxURLLength') {
self[i] = Math.min(MAX_URL_LENGTH, val);
} else {
self[i] = val;
}
}
}
}
// fix filter
f = self.filter;
if (L.isString(f)) {
f = f.toUpperCase();
self.filterName = f;
self.filter = self.FILTER_DEFS[f];
if (f == 'DEBUG') {
self.require('yui-log', 'dump');
}
}
if (self.lang) {
self.require('intl-base', 'intl');
}
},
/**
* Returns the skin module name for the specified skin name. If a
* module name is supplied, the returned skin module name is
* specific to the module passed in.
* @method formatSkin
* @param {string} skin the name of the skin.
* @param {string} mod optional: the name of a module to skin.
* @return {string} the full skin module name.
*/
formatSkin: function(skin, mod) {
var s = SKIN_PREFIX + skin;
if (mod) {
s = s + '-' + mod;
}
return s;
},
/**
* Adds the skin def to the module info
* @method _addSkin
* @param {string} skin the name of the skin.
* @param {string} mod the name of the module.
* @param {string} parent parent module if this is a skin of a
* submodule or plugin.
* @return {string} the module name for the skin.
* @private
*/
_addSkin: function(skin, mod, parent) {
var mdef, pkg, name, nmod,
info = this.moduleInfo,
sinf = this.skin,
ext = info[mod] && info[mod].ext;
// Add a module definition for the module-specific skin css
if (mod) {
name = this.formatSkin(skin, mod);
if (!info[name]) {
mdef = info[mod];
pkg = mdef.pkg || mod;
nmod = {
name: name,
group: mdef.group,
type: 'css',
after: sinf.after,
path: (parent || pkg) + '/' + sinf.base + skin +
'/' + mod + '.css',
ext: ext
};
if (mdef.base) {
nmod.base = mdef.base;
}
if (mdef.configFn) {
nmod.configFn = mdef.configFn;
}
this.addModule(nmod, name);
}
}
return name;
},
/**
* Add a new module group
* <dl>
* <dt>name:</dt> <dd>required, the group name</dd>
* <dt>base:</dt> <dd>The base dir for this module group</dd>
* <dt>root:</dt> <dd>The root path to add to each combo
* resource path</dd>
* <dt>combine:</dt> <dd>combo handle</dd>
* <dt>comboBase:</dt> <dd>combo service base path</dd>
* <dt>modules:</dt> <dd>the group of modules</dd>
* </dl>
* @method addGroup
* @param {object} o An object containing the module data.
* @param {string} name the group name.
*/
addGroup: function(o, name) {
var mods = o.modules,
self = this;
name = name || o.name;
o.name = name;
self.groups[name] = o;
if (o.patterns) {
oeach(o.patterns, function(v, k) {
v.group = name;
self.patterns[k] = v;
});
}
if (mods) {
oeach(mods, function(v, k) {
v.group = name;
self.addModule(v, k);
}, self);
}
},
/**
* Add a new module to the component metadata.
* <dl>
* <dt>name:</dt> <dd>required, the component name</dd>
* <dt>type:</dt> <dd>required, the component type (js or css)
* </dd>
* <dt>path:</dt> <dd>required, the path to the script from
* "base"</dd>
* <dt>requires:</dt> <dd>array of modules required by this
* component</dd>
* <dt>optional:</dt> <dd>array of optional modules for this
* component</dd>
* <dt>supersedes:</dt> <dd>array of the modules this component
* replaces</dd>
* <dt>after:</dt> <dd>array of modules the components which, if
* present, should be sorted above this one</dd>
* <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply
* a hash instead of an array</dd>
* <dt>rollup:</dt> <dd>the number of superseded modules required
* for automatic rollup</dd>
* <dt>fullpath:</dt> <dd>If fullpath is specified, this is used
* instead of the configured base + path</dd>
* <dt>skinnable:</dt> <dd>flag to determine if skin assets should
* automatically be pulled in</dd>
* <dt>submodules:</dt> <dd>a hash of submodules</dd>
* <dt>group:</dt> <dd>The group the module belongs to -- this
* is set automatically when it is added as part of a group
* configuration.</dd>
* <dt>lang:</dt>
* <dd>array of BCP 47 language tags of languages for which this
* module has localized resource bundles,
* e.g., ["en-GB","zh-Hans-CN"]</dd>
* <dt>condition:</dt>
* <dd>Specifies that the module should be loaded automatically if
* a condition is met. This is an object with up to three fields:
* [trigger] - the name of a module that can trigger the auto-load
* [test] - a function that returns true when the module is to be
* loaded.
* [when] - specifies the load order of the conditional module
* with regard to the position of the trigger module.
* This should be one of three values: 'before', 'after', or
* 'instead'. The default is 'after'.
* </dd>
* <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd>
* </dl>
* @method addModule
* @param {object} o An object containing the module data.
* @param {string} name the module name (optional), required if not
* in the module data.
* @return {object} the module definition or null if
* the object passed in did not provide all required attributes.
*/
addModule: function(o, name) {
name = name || o.name;
//Only merge this data if the temp flag is set
//from an earlier pass from a pattern or else
//an override module (YUI_config) can not be used to
//replace a default module.
if (this.moduleInfo[name] && this.moduleInfo[name].temp) {
//This catches temp modules loaded via a pattern
// The module will be added twice, once from the pattern and
// Once from the actual add call, this ensures that properties
// that were added to the module the first time around (group: gallery)
// are also added the second time around too.
o = Y.merge(this.moduleInfo[name], o);
}
o.name = name;
if (!o || !o.name) {
return null;
}
if (!o.type) {
o.type = JS;
}
if (!o.path && !o.fullpath) {
o.path = _path(name, name, o.type);
}
o.supersedes = o.supersedes || o.use;
o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true;
o.requires = this.filterRequires(o.requires) || [];
// Handle submodule logic
var subs = o.submodules, i, l, t, sup, s, smod, plugins, plug,
j, langs, packName, supName, flatSup, flatLang, lang, ret,
overrides, skinname, when,
conditions = this.conditions, trigger;
// , existing = this.moduleInfo[name], newr;
this.moduleInfo[name] = o;
if (!o.langPack && o.lang) {
langs = YArray(o.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
}
}
if (subs) {
sup = o.supersedes || [];
l = 0;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
s.path = s.path || _path(name, i, o.type);
s.pkg = name;
s.group = o.group;
if (s.supersedes) {
sup = sup.concat(s.supersedes);
}
smod = this.addModule(s, i);
sup.push(i);
if (smod.skinnable) {
o.skinnable = true;
overrides = this.skin.overrides;
if (overrides && overrides[i]) {
for (j = 0; j < overrides[i].length; j++) {
skinname = this._addSkin(overrides[i][j],
i, name);
sup.push(skinname);
}
}
skinname = this._addSkin(this.skin.defaultSkin,
i, name);
sup.push(skinname);
}
// looks like we are expected to work out the metadata
// for the parent module language packs from what is
// specified in the child modules.
if (s.lang && s.lang.length) {
langs = YArray(s.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
supName = this.getLangPackName(lang, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
flatSup = flatSup || YArray.hash(smod.supersedes);
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
o.lang = o.lang || [];
flatLang = flatLang || YArray.hash(o.lang);
if (!(lang in flatLang)) {
o.lang.push(lang);
}
// Add rollup file, need to add to supersedes list too
// default packages
packName = this.getLangPackName(ROOT_LANG, name);
supName = this.getLangPackName(ROOT_LANG, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
// Add rollup file, need to add to supersedes list too
}
}
l++;
}
}
//o.supersedes = YObject.keys(YArray.hash(sup));
o.supersedes = YArray.dedupe(sup);
if (this.allowRollup) {
o.rollup = (l < 4) ? l : Math.min(l - 1, 4);
}
}
plugins = o.plugins;
if (plugins) {
for (i in plugins) {
if (plugins.hasOwnProperty(i)) {
plug = plugins[i];
plug.pkg = name;
plug.path = plug.path || _path(name, i, o.type);
plug.requires = plug.requires || [];
plug.group = o.group;
this.addModule(plug, i);
if (o.skinnable) {
this._addSkin(this.skin.defaultSkin, i, name);
}
}
}
}
if (o.condition) {
t = o.condition.trigger;
if (YUI.Env.aliases[t]) {
t = YUI.Env.aliases[t];
}
if (!Y.Lang.isArray(t)) {
t = [t];
}
for (i = 0; i < t.length; i++) {
trigger = t[i];
when = o.condition.when;
conditions[trigger] = conditions[trigger] || {};
conditions[trigger][name] = o.condition;
// the 'when' attribute can be 'before', 'after', or 'instead'
// the default is after.
if (when && when != 'after') {
if (when == 'instead') { // replace the trigger
o.supersedes = o.supersedes || [];
o.supersedes.push(trigger);
} else { // before the trigger
// the trigger requires the conditional mod,
// so it should appear before the conditional
// mod if we do not intersede.
}
} else { // after the trigger
o.after = o.after || [];
o.after.push(trigger);
}
}
}
if (o.after) {
o.after_map = YArray.hash(o.after);
}
// this.dirty = true;
if (o.configFn) {
ret = o.configFn(o);
if (ret === false) {
delete this.moduleInfo[name];
o = null;
}
}
return o;
},
/**
* Add a requirement for one or more module
* @method require
* @param {string[] | string*} what the modules to load.
*/
require: function(what) {
var a = (typeof what === 'string') ? YArray(arguments) : what;
this.dirty = true;
this.required = Y.merge(this.required, YArray.hash(this.filterRequires(a)));
this._explodeRollups();
},
/**
* Grab all the items that were asked for, check to see if the Loader
* meta-data contains a "use" array. If it doesm remove the asked item and replace it with
* the content of the "use".
* This will make asking for: "dd"
* Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin"
* @private
* @method _explodeRollups
*/
_explodeRollups: function() {
var self = this, m,
r = self.required;
if (!self.allowRollup) {
oeach(r, function(v, name) {
m = self.getModule(name);
if (m && m.use) {
//delete r[name];
YArray.each(m.use, function(v) {
m = self.getModule(v);
if (m && m.use) {
//delete r[v];
YArray.each(m.use, function(v) {
r[v] = true;
});
} else {
r[v] = true;
}
});
}
});
self.required = r;
}
},
/**
* Explodes the required array to remove aliases and replace them with real modules
* @method filterRequires
* @param {Array} r The original requires array
* @return {Array} The new array of exploded requirements
*/
filterRequires: function(r) {
if (r) {
if (!Y.Lang.isArray(r)) {
r = [r];
}
r = Y.Array(r);
var c = [], i, mod, o, m;
for (i = 0; i < r.length; i++) {
mod = this.getModule(r[i]);
if (mod && mod.use) {
for (o = 0; o < mod.use.length; o++) {
//Must walk the other modules in case a module is a rollup of rollups (datatype)
m = this.getModule(mod.use[o]);
if (m && m.use) {
c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use)));
} else {
c.push(mod.use[o]);
}
}
} else {
c.push(r[i]);
}
}
r = c;
}
return r;
},
/**
* Returns an object containing properties for all modules required
* in order to load the requested module
* @method getRequires
* @param {object} mod The module definition from moduleInfo.
* @return {array} the expanded requirement list.
*/
getRequires: function(mod) {
if (!mod || mod._parsed) {
return NO_REQUIREMENTS;
}
var i, m, j, add, packName, lang, testresults = this.testresults,
name = mod.name, cond, go,
adddef = ON_PAGE[name] && ON_PAGE[name].details,
d, k, m1,
r, old_mod,
o, skinmod, skindef, skinpar, skinname,
intl = mod.lang || mod.intl,
info = this.moduleInfo,
ftests = Y.Features && Y.Features.tests.load,
hash;
// console.log(name);
// pattern match leaves module stub that needs to be filled out
if (mod.temp && adddef) {
old_mod = mod;
mod = this.addModule(adddef, name);
mod.group = old_mod.group;
mod.pkg = old_mod.pkg;
delete mod.expanded;
}
// console.log('cache: ' + mod.langCache + ' == ' + this.lang);
// if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) {
if (mod.expanded && (!this.lang || mod.langCache === this.lang)) {
return mod.expanded;
}
d = [];
hash = {};
r = this.filterRequires(mod.requires);
if (mod.lang) {
//If a module has a lang attribute, auto add the intl requirement.
d.unshift('intl');
r.unshift('intl');
intl = true;
}
o = this.filterRequires(mod.optional);
mod._parsed = true;
mod.langCache = this.lang;
for (i = 0; i < r.length; i++) {
if (!hash[r[i]]) {
d.push(r[i]);
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
// get the requirements from superseded modules, if any
r = this.filterRequires(mod.supersedes);
if (r) {
for (i = 0; i < r.length; i++) {
if (!hash[r[i]]) {
// if this module has submodules, the requirements list is
// expanded to include the submodules. This is so we can
// prevent dups when a submodule is already loaded and the
// parent is requested.
if (mod.submodules) {
d.push(r[i]);
}
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
if (o && this.loadOptional) {
for (i = 0; i < o.length; i++) {
if (!hash[o[i]]) {
d.push(o[i]);
hash[o[i]] = true;
m = info[o[i]];
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
cond = this.conditions[name];
if (cond) {
if (testresults && ftests) {
oeach(testresults, function(result, id) {
var condmod = ftests[id].name;
if (!hash[condmod] && ftests[id].trigger == name) {
if (result && ftests[id]) {
hash[condmod] = true;
d.push(condmod);
}
}
});
} else {
oeach(cond, function(def, condmod) {
if (!hash[condmod]) {
go = def && ((def.ua && Y.UA[def.ua]) ||
(def.test && def.test(Y, r)));
if (go) {
hash[condmod] = true;
d.push(condmod);
m = this.getModule(condmod);
if (m) {
add = this.getRequires(m);
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}, this);
}
}
// Create skin modules
if (mod.skinnable) {
skindef = this.skin.overrides;
oeach(YUI.Env.aliases, function(o, n) {
if (Y.Array.indexOf(o, name) > -1) {
skinpar = n;
}
});
if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) {
skinname = name;
if (skindef[skinpar]) {
skinname = skinpar;
}
for (i = 0; i < skindef[skinname].length; i++) {
skinmod = this._addSkin(skindef[skinname][i], name);
d.push(skinmod);
}
} else {
skinmod = this._addSkin(this.skin.defaultSkin, name);
d.push(skinmod);
}
}
mod._parsed = false;
if (intl) {
if (mod.lang && !mod.langPack && Y.Intl) {
lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang);
packName = this.getLangPackName(lang, name);
if (packName) {
d.unshift(packName);
}
}
d.unshift(INTL);
}
mod.expanded_map = YArray.hash(d);
mod.expanded = YObject.keys(mod.expanded_map);
return mod.expanded;
},
/**
* Returns a hash of module names the supplied module satisfies.
* @method getProvides
* @param {string} name The name of the module.
* @return {object} what this module provides.
*/
getProvides: function(name) {
var m = this.getModule(name), o, s;
// supmap = this.provides;
if (!m) {
return NOT_FOUND;
}
if (m && !m.provides) {
o = {};
s = m.supersedes;
if (s) {
YArray.each(s, function(v) {
Y.mix(o, this.getProvides(v));
}, this);
}
o[name] = true;
m.provides = o;
}
return m.provides;
},
/**
* Calculates the dependency tree, the result is stored in the sorted
* property.
* @method calculate
* @param {object} o optional options object.
* @param {string} type optional argument to prune modules.
*/
calculate: function(o, type) {
if (o || type || this.dirty) {
if (o) {
this._config(o);
}
if (!this._init) {
this._setup();
}
this._explode();
if (this.allowRollup) {
this._rollup();
} else {
this._explodeRollups();
}
this._reduce();
this._sort();
}
},
/**
* Creates a "psuedo" package for languages provided in the lang array
* @method _addLangPack
* @param {String} lang The language to create
* @param {Object} m The module definition to create the language pack around
* @param {String} packName The name of the package (e.g: lang/datatype-date-en-US)
* @return {Object} The module definition
*/
_addLangPack: function(lang, m, packName) {
var name = m.name,
packPath,
existing = this.moduleInfo[packName];
if (!existing) {
packPath = _path((m.pkg || name), packName, JS, true);
this.addModule({ path: packPath,
intl: true,
langPack: true,
ext: m.ext,
group: m.group,
supersedes: [] }, packName);
if (lang) {
Y.Env.lang = Y.Env.lang || {};
Y.Env.lang[lang] = Y.Env.lang[lang] || {};
Y.Env.lang[lang][name] = true;
}
}
return this.moduleInfo[packName];
},
/**
* Investigates the current YUI configuration on the page. By default,
* modules already detected will not be loaded again unless a force
* option is encountered. Called by calculate()
* @method _setup
* @private
*/
_setup: function() {
var info = this.moduleInfo, name, i, j, m, l,
packName;
for (name in info) {
if (info.hasOwnProperty(name)) {
m = info[name];
if (m) {
// remove dups
//m.requires = YObject.keys(YArray.hash(m.requires));
m.requires = YArray.dedupe(m.requires);
// Create lang pack modules
if (m.lang && m.lang.length) {
// Setup root package if the module has lang defined,
// it needs to provide a root language pack
packName = this.getLangPackName(ROOT_LANG, name);
this._addLangPack(null, m, packName);
}
}
}
}
//l = Y.merge(this.inserted);
l = {};
// available modules
if (!this.ignoreRegistered) {
Y.mix(l, GLOBAL_ENV.mods);
}
// add the ignore list to the list of loaded packages
if (this.ignore) {
Y.mix(l, YArray.hash(this.ignore));
}
// expand the list to include superseded modules
for (j in l) {
if (l.hasOwnProperty(j)) {
Y.mix(l, this.getProvides(j));
}
}
// remove modules on the force list from the loaded list
if (this.force) {
for (i = 0; i < this.force.length; i++) {
if (this.force[i] in l) {
delete l[this.force[i]];
}
}
}
Y.mix(this.loaded, l);
this._init = true;
},
/**
* Builds a module name for a language pack
* @method getLangPackName
* @param {string} lang the language code.
* @param {string} mname the module to build it for.
* @return {string} the language pack module name.
*/
getLangPackName: function(lang, mname) {
return ('lang/' + mname + ((lang) ? '_' + lang : ''));
},
/**
* Inspects the required modules list looking for additional
* dependencies. Expands the required list to include all
* required modules. Called by calculate()
* @method _explode
* @private
*/
_explode: function() {
var r = this.required, m, reqs, done = {},
self = this;
// the setup phase is over, all modules have been created
self.dirty = false;
self._explodeRollups();
r = self.required;
oeach(r, function(v, name) {
if (!done[name]) {
done[name] = true;
m = self.getModule(name);
if (m) {
var expound = m.expound;
if (expound) {
r[expound] = self.getModule(expound);
reqs = self.getRequires(r[expound]);
Y.mix(r, YArray.hash(reqs));
}
reqs = self.getRequires(m);
Y.mix(r, YArray.hash(reqs));
}
}
});
},
/**
* Get's the loader meta data for the requested module
* @method getModule
* @param {String} mname The module name to get
* @return {Object} The module metadata
*/
getModule: function(mname) {
//TODO: Remove name check - it's a quick hack to fix pattern WIP
if (!mname) {
return null;
}
var p, found, pname,
m = this.moduleInfo[mname],
patterns = this.patterns;
// check the patterns library to see if we should automatically add
// the module with defaults
if (!m) {
for (pname in patterns) {
if (patterns.hasOwnProperty(pname)) {
p = patterns[pname];
// use the metadata supplied for the pattern
// as the module definition.
if (mname.indexOf(pname) > -1) {
found = p;
break;
}
}
}
if (found) {
if (p.action) {
p.action.call(this, mname, pname);
} else {
// ext true or false?
m = this.addModule(Y.merge(found), mname);
m.temp = true;
}
}
}
return m;
},
// impl in rollup submodule
_rollup: function() { },
/**
* Remove superceded modules and loaded modules. Called by
* calculate() after we have the mega list of all dependencies
* @method _reduce
* @return {object} the reduced dependency hash.
* @private
*/
_reduce: function(r) {
r = r || this.required;
var i, j, s, m, type = this.loadType,
ignore = this.ignore ? YArray.hash(this.ignore) : false;
for (i in r) {
if (r.hasOwnProperty(i)) {
m = this.getModule(i);
// remove if already loaded
if (((this.loaded[i] || ON_PAGE[i]) &&
!this.forceMap[i] && !this.ignoreRegistered) ||
(type && m && m.type != type)) {
delete r[i];
}
if (ignore && ignore[i]) {
delete r[i];
}
// remove anything this module supersedes
s = m && m.supersedes;
if (s) {
for (j = 0; j < s.length; j++) {
if (s[j] in r) {
delete r[s[j]];
}
}
}
}
}
return r;
},
/**
* Handles the queue when a module has been loaded for all cases
* @method _finish
* @private
* @param {String} msg The message from Loader
* @param {Boolean} success A boolean denoting success or failure
*/
_finish: function(msg, success) {
_queue.running = false;
var onEnd = this.onEnd;
if (onEnd) {
onEnd.call(this.context, {
msg: msg,
data: this.data,
success: success
});
}
this._continue();
},
/**
* The default Loader onSuccess handler, calls this.onSuccess with a payload
* @method _onSuccess
* @private
*/
_onSuccess: function() {
var self = this, skipped = Y.merge(self.skipped), fn,
failed = [], rreg = self.requireRegistration,
success, msg;
oeach(skipped, function(k) {
delete self.inserted[k];
});
self.skipped = {};
oeach(self.inserted, function(v, k) {
var mod = self.getModule(k);
if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) {
failed.push(k);
} else {
Y.mix(self.loaded, self.getProvides(k));
}
});
fn = self.onSuccess;
msg = (failed.length) ? 'notregistered' : 'success';
success = !(failed.length);
if (fn) {
fn.call(self.context, {
msg: msg,
data: self.data,
success: success,
failed: failed,
skipped: skipped
});
}
self._finish(msg, success);
},
/**
* The default Loader onFailure handler, calls this.onFailure with a payload
* @method _onFailure
* @private
*/
_onFailure: function(o) {
var f = this.onFailure, msg = 'failure: ' + o.msg;
if (f) {
f.call(this.context, {
msg: msg,
data: this.data,
success: false
});
}
this._finish(msg, false);
},
/**
* The default Loader onTimeout handler, calls this.onTimeout with a payload
* @method _onTimeout
* @private
*/
_onTimeout: function() {
var f = this.onTimeout;
if (f) {
f.call(this.context, {
msg: 'timeout',
data: this.data,
success: false
});
}
this._finish('timeout', false);
},
/**
* Sorts the dependency tree. The last step of calculate()
* @method _sort
* @private
*/
_sort: function() {
// create an indexed list
var s = YObject.keys(this.required),
// loaded = this.loaded,
done = {},
p = 0, l, a, b, j, k, moved, doneKey;
// keep going until we make a pass without moving anything
for (;;) {
l = s.length;
moved = false;
// start the loop after items that are already sorted
for (j = p; j < l; j++) {
// check the next module on the list to see if its
// dependencies have been met
a = s[j];
// check everything below current item and move if we
// find a requirement for the current item
for (k = j + 1; k < l; k++) {
doneKey = a + s[k];
if (!done[doneKey] && this._requires(a, s[k])) {
// extract the dependency so we can move it up
b = s.splice(k, 1);
// insert the dependency above the item that
// requires it
s.splice(j, 0, b[0]);
// only swap two dependencies once to short circut
// circular dependencies
done[doneKey] = true;
// keep working
moved = true;
break;
}
}
// jump out of loop if we moved something
if (moved) {
break;
// this item is sorted, move our pointer and keep going
} else {
p++;
}
}
// when we make it here and moved is false, we are
// finished sorting
if (!moved) {
break;
}
}
this.sorted = s;
},
/**
* (Unimplemented)
* @method partial
* @unimplemented
*/
partial: function(partial, o, type) {
this.sorted = partial;
this.insert(o, type, true);
},
/**
* Handles the actual insertion of script/link tags
* @method _insert
* @param {Object} source The YUI instance the request came from
* @param {Object} o The metadata to include
* @param {String} type JS or CSS
* @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta
*/
_insert: function(source, o, type, skipcalc) {
// restore the state at the time of the request
if (source) {
this._config(source);
}
// build the dependency list
// don't include type so we can process CSS and script in
// one pass when the type is not specified.
if (!skipcalc) {
this.calculate(o);
}
this.loadType = type;
if (!type) {
var self = this;
this._internalCallback = function() {
var f = self.onCSS, n, p, sib;
// IE hack for style overrides that are not being applied
if (this.insertBefore && Y.UA.ie) {
n = Y.config.doc.getElementById(this.insertBefore);
p = n.parentNode;
sib = n.nextSibling;
p.removeChild(n);
if (sib) {
p.insertBefore(n, sib);
} else {
p.appendChild(n);
}
}
if (f) {
f.call(self.context, Y);
}
self._internalCallback = null;
self._insert(null, null, JS);
};
this._insert(null, null, CSS);
return;
}
// set a flag to indicate the load has started
this._loading = true;
// flag to indicate we are done with the combo service
// and any additional files will need to be loaded
// individually
this._combineComplete = {};
// start the load
this.loadNext();
},
/**
* Once a loader operation is completely finished, process any additional queued items.
* @method _continue
* @private
*/
_continue: function() {
if (!(_queue.running) && _queue.size() > 0) {
_queue.running = true;
_queue.next()();
}
},
/**
* inserts the requested modules and their dependencies.
* <code>type</code> can be "js" or "css". Both script and
* css are inserted if type is not provided.
* @method insert
* @param {object} o optional options object.
* @param {string} type the type of dependency to insert.
*/
insert: function(o, type, skipsort) {
var self = this, copy = Y.merge(this);
delete copy.require;
delete copy.dirty;
_queue.add(function() {
self._insert(copy, o, type, skipsort);
});
this._continue();
},
/**
* Executed every time a module is loaded, and if we are in a load
* cycle, we attempt to load the next script. Public so that it
* is possible to call this if using a method other than
* Y.register to determine when scripts are fully loaded
* @method loadNext
* @param {string} mname optional the name of the module that has
* been loaded (which is usually why it is time to load the next
* one).
*/
loadNext: function(mname) {
// It is possible that this function is executed due to something
// else on the page loading a YUI module. Only react when we
// are actively loading something
if (!this._loading) {
return;
}
var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag,
comboSource, comboSources, mods, combining, urls, comboBase,
self = this,
type = self.loadType,
handleSuccess = function(o) {
self.loadNext(o.data);
},
handleCombo = function(o) {
self._combineComplete[type] = true;
var i, len = combining.length;
for (i = 0; i < len; i++) {
self.inserted[combining[i]] = true;
}
handleSuccess(o);
};
if (self.combine && (!self._combineComplete[type])) {
combining = [];
self._combining = combining;
s = self.sorted;
len = s.length;
// the default combo base
comboBase = self.comboBase;
url = comboBase;
urls = [];
comboSources = {};
for (i = 0; i < len; i++) {
comboSource = comboBase;
m = self.getModule(s[i]);
groupName = m && m.group;
if (groupName) {
group = self.groups[groupName];
if (!group.combine) {
m.combine = false;
continue;
}
m.combine = true;
if (group.comboBase) {
comboSource = group.comboBase;
}
if ("root" in group && L.isValue(group.root)) {
m.root = group.root;
}
}
comboSources[comboSource] = comboSources[comboSource] || [];
comboSources[comboSource].push(m);
}
for (j in comboSources) {
if (comboSources.hasOwnProperty(j)) {
url = j;
mods = comboSources[j];
len = mods.length;
for (i = 0; i < len; i++) {
// m = self.getModule(s[i]);
m = mods[i];
// Do not try to combine non-yui JS unless combo def
// is found
if (m && (m.type === type) && (m.combine || !m.ext)) {
frag = ((L.isValue(m.root)) ? m.root : self.root) + m.path;
frag = self._filter(frag, m.name);
if ((url !== j) && (i <= (len - 1)) &&
((frag.length + url.length) > self.maxURLLength)) {
//Hack until this is rewritten to use an array and not string concat:
if (url.substr(url.length - 1, 1) === self.comboSep) {
url = url.substr(0, (url.length - 1));
}
urls.push(self._filter(url));
url = j;
}
url += frag;
if (i < (len - 1)) {
url += self.comboSep;
}
combining.push(m.name);
}
}
if (combining.length && (url != j)) {
//Hack until this is rewritten to use an array and not string concat:
if (url.substr(url.length - 1, 1) === self.comboSep) {
url = url.substr(0, (url.length - 1));
}
urls.push(self._filter(url));
}
}
}
if (combining.length) {
// if (m.type === CSS) {
if (type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
fn(urls, {
data: self._loading,
onSuccess: handleCombo,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
} else {
self._combineComplete[type] = true;
}
}
if (mname) {
// if the module that was just loaded isn't what we were expecting,
// continue to wait
if (mname !== self._loading) {
return;
}
// The global handler that is called when each module is loaded
// will pass that module name to this function. Storing this
// data to avoid loading the same module multiple times
// centralize this in the callback
self.inserted[mname] = true;
// self.loaded[mname] = true;
// provided = self.getProvides(mname);
// Y.mix(self.loaded, provided);
// Y.mix(self.inserted, provided);
if (self.onProgress) {
self.onProgress.call(self.context, {
name: mname,
data: self.data
});
}
}
s = self.sorted;
len = s.length;
for (i = 0; i < len; i = i + 1) {
// this.inserted keeps track of what the loader has loaded.
// move on if this item is done.
if (s[i] in self.inserted) {
continue;
}
// Because rollups will cause multiple load notifications
// from Y, loadNext may be called multiple times for
// the same module when loading a rollup. We can safely
// skip the subsequent requests
if (s[i] === self._loading) {
return;
}
// log("inserting " + s[i]);
m = self.getModule(s[i]);
if (!m) {
if (!self.skipped[s[i]]) {
msg = 'Undefined module ' + s[i] + ' skipped';
// self.inserted[s[i]] = true;
self.skipped[s[i]] = true;
}
continue;
}
group = (m.group && self.groups[m.group]) || NOT_FOUND;
// The load type is stored to offer the possibility to load
// the css separately from the script.
if (!type || type === m.type) {
self._loading = s[i];
if (m.type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
url = (m.fullpath) ? self._filter(m.fullpath, s[i]) :
self._url(m.path, s[i], group.base || m.base);
fn(url, {
data: s[i],
onSuccess: handleSuccess,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
}
}
// we are finished
self._loading = null;
fn = self._internalCallback;
// internal callback for loading css first
if (fn) {
self._internalCallback = null;
fn.call(self);
} else {
self._onSuccess();
}
},
/**
* Apply filter defined for this instance to a url/path
* @method _filter
* @param {string} u the string to filter.
* @param {string} name the name of the module, if we are processing
* a single module as opposed to a combined url.
* @return {string} the filtered string.
* @private
*/
_filter: function(u, name) {
var f = this.filter,
hasFilter = name && (name in this.filters),
modFilter = hasFilter && this.filters[name],
groupName = this.moduleInfo[name] ? this.moduleInfo[name].group:null;
if (groupName && this.groups[groupName].filter) {
modFilter = this.groups[groupName].filter;
hasFilter = true;
};
if (u) {
if (hasFilter) {
f = (L.isString(modFilter)) ?
this.FILTER_DEFS[modFilter.toUpperCase()] || null :
modFilter;
}
if (f) {
u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr);
}
}
return u;
},
/**
* Generates the full url for a module
* @method _url
* @param {string} path the path fragment.
* @param {String} name The name of the module
* @pamra {String} [base=self.base] The base url to use
* @return {string} the full url.
* @private
*/
_url: function(path, name, base) {
return this._filter((base || this.base || '') + path, name);
},
/**
* Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
* @method resolve
* @param {Boolean} [calc=false] Perform a loader.calculate() before anything else
* @param {Array} [s=loader.sorted] An override for the loader.sorted array
* @return {Object} Object hash (js and css) of two arrays of file lists
* @example This method can be used as an off-line dep calculator
*
* var Y = YUI();
* var loader = new Y.Loader({
* filter: 'debug',
* base: '../../',
* root: 'build/',
* combine: true,
* require: ['node', 'dd', 'console']
* });
* var out = loader.resolve(true);
*
*/
resolve: function(calc, s) {
var self = this, i, m, url, out = { js: [], css: [] };
if (calc) {
self.calculate();
}
s = s || self.sorted;
for (i = 0; i < s.length; i++) {
m = self.getModule(s[i]);
if (m) {
if (self.combine) {
url = self._filter((self.root + m.path), m.name, self.root);
} else {
url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name);
}
out[m.type].push(url);
}
}
if (self.combine) {
out.js = [self.comboBase + out.js.join(self.comboSep)];
out.css = [self.comboBase + out.css.join(self.comboSep)];
}
return out;
},
/**
* Returns an Object hash of hashes built from `loader.sorted` or from an arbitrary list of sorted modules.
* @method hash
* @private
* @param {Boolean} [calc=false] Perform a loader.calculate() before anything else
* @param {Array} [s=loader.sorted] An override for the loader.sorted array
* @return {Object} Object hash (js and css) of two object hashes of file lists, with the module name as the key
* @example This method can be used as an off-line dep calculator
*
* var Y = YUI();
* var loader = new Y.Loader({
* filter: 'debug',
* base: '../../',
* root: 'build/',
* combine: true,
* require: ['node', 'dd', 'console']
* });
* var out = loader.hash(true);
*
*/
hash: function(calc, s) {
var self = this, i, m, url, out = { js: {}, css: {} };
if (calc) {
self.calculate();
}
s = s || self.sorted;
for (i = 0; i < s.length; i++) {
m = self.getModule(s[i]);
if (m) {
url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name);
out[m.type][m.name] = url;
}
}
return out;
}
};
}, '@VERSION@' ,{requires:['get']});
YUI.add('loader-rollup', function(Y) {
/**
* Optional automatic rollup logic for reducing http connections
* when not using a combo service.
* @module loader
* @submodule rollup
*/
/**
* Look for rollup packages to determine if all of the modules a
* rollup supersedes are required. If so, include the rollup to
* help reduce the total number of connections required. Called
* by calculate(). This is an optional feature, and requires the
* appropriate submodule to function.
* @method _rollup
* @for Loader
* @private
*/
Y.Loader.prototype._rollup = function() {
var i, j, m, s, r = this.required, roll,
info = this.moduleInfo, rolled, c, smod;
// find and cache rollup modules
if (this.dirty || !this.rollups) {
this.rollups = {};
for (i in info) {
if (info.hasOwnProperty(i)) {
m = this.getModule(i);
// if (m && m.rollup && m.supersedes) {
if (m && m.rollup) {
this.rollups[i] = m;
}
}
}
this.forceMap = (this.force) ? Y.Array.hash(this.force) : {};
}
// make as many passes as needed to pick up rollup rollups
for (;;) {
rolled = false;
// go through the rollup candidates
for (i in this.rollups) {
if (this.rollups.hasOwnProperty(i)) {
// there can be only one, unless forced
if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) {
m = this.getModule(i);
s = m.supersedes || [];
roll = false;
// @TODO remove continue
if (!m.rollup) {
continue;
}
c = 0;
// check the threshold
for (j = 0; j < s.length; j++) {
smod = info[s[j]];
// if the superseded module is loaded, we can't
// load the rollup unless it has been forced.
if (this.loaded[s[j]] && !this.forceMap[s[j]]) {
roll = false;
break;
// increment the counter if this module is required.
// if we are beyond the rollup threshold, we will
// use the rollup module
} else if (r[s[j]] && m.type == smod.type) {
c++;
roll = (c >= m.rollup);
if (roll) {
break;
}
}
}
if (roll) {
// add the rollup
r[i] = true;
rolled = true;
// expand the rollup's dependencies
this.getRequires(m);
}
}
}
}
// if we made it here w/o rolling up something, we are done
if (!rolled) {
break;
}
}
};
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('loader-yui3', function(Y) {
/* This file is auto-generated by src/loader/scripts/meta_join.py */
/**
* YUI 3 module metadata
* @module loader
* @submodule yui3
*/
YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {
"align-plugin": {
"requires": [
"node-screen",
"node-pluginhost"
]
},
"anim": {
"use": [
"anim-base",
"anim-color",
"anim-curve",
"anim-easing",
"anim-node-plugin",
"anim-scroll",
"anim-xy"
]
},
"anim-base": {
"requires": [
"base-base",
"node-style"
]
},
"anim-color": {
"requires": [
"anim-base"
]
},
"anim-curve": {
"requires": [
"anim-xy"
]
},
"anim-easing": {
"requires": [
"anim-base"
]
},
"anim-node-plugin": {
"requires": [
"node-pluginhost",
"anim-base"
]
},
"anim-scroll": {
"requires": [
"anim-base"
]
},
"anim-xy": {
"requires": [
"anim-base",
"node-screen"
]
},
"app": {
"use": [
"controller",
"model",
"model-list",
"view"
]
},
"array-extras": {
"requires": [
"yui-base"
]
},
"array-invoke": {
"requires": [
"yui-base"
]
},
"arraylist": {
"requires": [
"yui-base"
]
},
"arraylist-add": {
"requires": [
"arraylist"
]
},
"arraylist-filter": {
"requires": [
"arraylist"
]
},
"arraysort": {
"requires": [
"yui-base"
]
},
"async-queue": {
"requires": [
"event-custom"
]
},
"attribute": {
"use": [
"attribute-base",
"attribute-complex"
]
},
"attribute-base": {
"requires": [
"event-custom"
]
},
"attribute-complex": {
"requires": [
"attribute-base"
]
},
"autocomplete": {
"use": [
"autocomplete-base",
"autocomplete-sources",
"autocomplete-list",
"autocomplete-plugin"
]
},
"autocomplete-base": {
"optional": [
"autocomplete-sources"
],
"requires": [
"array-extras",
"base-build",
"escape",
"event-valuechange",
"node-base"
]
},
"autocomplete-filters": {
"requires": [
"array-extras",
"text-wordbreak"
]
},
"autocomplete-filters-accentfold": {
"requires": [
"array-extras",
"text-accentfold",
"text-wordbreak"
]
},
"autocomplete-highlighters": {
"requires": [
"array-extras",
"highlight-base"
]
},
"autocomplete-highlighters-accentfold": {
"requires": [
"array-extras",
"highlight-accentfold"
]
},
"autocomplete-list": {
"after": [
"autocomplete-sources"
],
"lang": [
"en"
],
"requires": [
"autocomplete-base",
"event-resize",
"node-screen",
"selector-css3",
"shim-plugin",
"widget",
"widget-position",
"widget-position-align"
],
"skinnable": true
},
"autocomplete-list-keys": {
"condition": {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
},
"requires": [
"autocomplete-list",
"base-build"
]
},
"autocomplete-plugin": {
"requires": [
"autocomplete-list",
"node-pluginhost"
]
},
"autocomplete-sources": {
"optional": [
"io-base",
"json-parse",
"jsonp",
"yql"
],
"requires": [
"autocomplete-base"
]
},
"base": {
"use": [
"base-base",
"base-pluginhost",
"base-build"
]
},
"base-base": {
"after": [
"attribute-complex"
],
"requires": [
"attribute-base"
]
},
"base-build": {
"requires": [
"base-base"
]
},
"base-pluginhost": {
"requires": [
"base-base",
"pluginhost"
]
},
"cache": {
"use": [
"cache-base",
"cache-offline",
"cache-plugin"
]
},
"cache-base": {
"requires": [
"base"
]
},
"cache-offline": {
"requires": [
"cache-base",
"json"
]
},
"cache-plugin": {
"requires": [
"plugin",
"cache-base"
]
},
"calendar": {
"lang": [
"en",
"ja",
"ru"
],
"requires": [
"calendar-base",
"calendarnavigator"
],
"skinnable": true
},
"calendar-base": {
"lang": [
"en",
"ja",
"ru"
],
"requires": [
"widget",
"substitute",
"datatype-date",
"datatype-date-math",
"cssgrids"
],
"skinnable": true
},
"calendarnavigator": {
"requires": [
"plugin",
"classnamemanager",
"datatype-date",
"node",
"substitute"
],
"skinnable": true
},
"charts": {
"requires": [
"dom",
"datatype-number",
"datatype-date",
"event-custom",
"event-mouseenter",
"widget",
"widget-position",
"widget-stack",
"graphics"
]
},
"classnamemanager": {
"requires": [
"yui-base"
]
},
"clickable-rail": {
"requires": [
"slider-base"
]
},
"collection": {
"use": [
"array-extras",
"arraylist",
"arraylist-add",
"arraylist-filter",
"array-invoke"
]
},
"console": {
"lang": [
"en",
"es",
"ja"
],
"requires": [
"yui-log",
"widget",
"substitute"
],
"skinnable": true
},
"console-filters": {
"requires": [
"plugin",
"console"
],
"skinnable": true
},
"controller": {
"optional": [
"querystring-parse"
],
"requires": [
"array-extras",
"base-build",
"history"
]
},
"cookie": {
"requires": [
"yui-base"
]
},
"createlink-base": {
"requires": [
"editor-base"
]
},
"cssbase": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"type": "css"
},
"cssbase-context": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"type": "css"
},
"cssfonts": {
"type": "css"
},
"cssfonts-context": {
"type": "css"
},
"cssgrids": {
"optional": [
"cssreset",
"cssfonts"
],
"type": "css"
},
"cssreset": {
"type": "css"
},
"cssreset-context": {
"type": "css"
},
"dataschema": {
"use": [
"dataschema-base",
"dataschema-json",
"dataschema-xml",
"dataschema-array",
"dataschema-text"
]
},
"dataschema-array": {
"requires": [
"dataschema-base"
]
},
"dataschema-base": {
"requires": [
"base"
]
},
"dataschema-json": {
"requires": [
"dataschema-base",
"json"
]
},
"dataschema-text": {
"requires": [
"dataschema-base"
]
},
"dataschema-xml": {
"requires": [
"dataschema-base"
]
},
"datasource": {
"use": [
"datasource-local",
"datasource-io",
"datasource-get",
"datasource-function",
"datasource-cache",
"datasource-jsonschema",
"datasource-xmlschema",
"datasource-arrayschema",
"datasource-textschema",
"datasource-polling"
]
},
"datasource-arrayschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-array"
]
},
"datasource-cache": {
"requires": [
"datasource-local",
"plugin",
"cache-base"
]
},
"datasource-function": {
"requires": [
"datasource-local"
]
},
"datasource-get": {
"requires": [
"datasource-local",
"get"
]
},
"datasource-io": {
"requires": [
"datasource-local",
"io-base"
]
},
"datasource-jsonschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-json"
]
},
"datasource-local": {
"requires": [
"base"
]
},
"datasource-polling": {
"requires": [
"datasource-local"
]
},
"datasource-textschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-text"
]
},
"datasource-xmlschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-xml"
]
},
"datatable": {
"use": [
"datatable-base",
"datatable-datasource",
"datatable-sort",
"datatable-scroll"
]
},
"datatable-base": {
"requires": [
"recordset-base",
"widget",
"substitute",
"event-mouseenter"
],
"skinnable": true
},
"datatable-datasource": {
"requires": [
"datatable-base",
"plugin",
"datasource-local"
]
},
"datatable-scroll": {
"requires": [
"datatable-base",
"plugin"
]
},
"datatable-sort": {
"lang": [
"en"
],
"requires": [
"datatable-base",
"plugin",
"recordset-sort"
]
},
"datatype": {
"use": [
"datatype-number",
"datatype-date",
"datatype-xml"
]
},
"datatype-date": {
"supersedes": [
"datatype-date-format"
],
"use": [
"datatype-date-parse",
"datatype-date-format"
]
},
"datatype-date-format": {
"lang": [
"ar",
"ar-JO",
"ca",
"ca-ES",
"da",
"da-DK",
"de",
"de-AT",
"de-DE",
"el",
"el-GR",
"en",
"en-AU",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JO",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-US",
"es",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-EC",
"es-ES",
"es-MX",
"es-PE",
"es-PY",
"es-US",
"es-UY",
"es-VE",
"fi",
"fi-FI",
"fr",
"fr-BE",
"fr-CA",
"fr-FR",
"hi",
"hi-IN",
"id",
"id-ID",
"it",
"it-IT",
"ja",
"ja-JP",
"ko",
"ko-KR",
"ms",
"ms-MY",
"nb",
"nb-NO",
"nl",
"nl-BE",
"nl-NL",
"pl",
"pl-PL",
"pt",
"pt-BR",
"ro",
"ro-RO",
"ru",
"ru-RU",
"sv",
"sv-SE",
"th",
"th-TH",
"tr",
"tr-TR",
"vi",
"vi-VN",
"zh-Hans",
"zh-Hans-CN",
"zh-Hant",
"zh-Hant-HK",
"zh-Hant-TW"
]
},
"datatype-date-math": {
"requires": [
"yui-base"
]
},
"datatype-date-parse": {},
"datatype-number": {
"use": [
"datatype-number-parse",
"datatype-number-format"
]
},
"datatype-number-format": {},
"datatype-number-parse": {},
"datatype-xml": {
"use": [
"datatype-xml-parse",
"datatype-xml-format"
]
},
"datatype-xml-format": {},
"datatype-xml-parse": {},
"dd": {
"use": [
"dd-ddm-base",
"dd-ddm",
"dd-ddm-drop",
"dd-drag",
"dd-proxy",
"dd-constrain",
"dd-drop",
"dd-scroll",
"dd-delegate"
]
},
"dd-constrain": {
"requires": [
"dd-drag"
]
},
"dd-ddm": {
"requires": [
"dd-ddm-base",
"event-resize"
]
},
"dd-ddm-base": {
"requires": [
"node",
"base",
"yui-throttle",
"classnamemanager"
]
},
"dd-ddm-drop": {
"requires": [
"dd-ddm"
]
},
"dd-delegate": {
"requires": [
"dd-drag",
"dd-drop-plugin",
"event-mouseenter"
]
},
"dd-drag": {
"requires": [
"dd-ddm-base"
]
},
"dd-drop": {
"requires": [
"dd-drag",
"dd-ddm-drop"
]
},
"dd-drop-plugin": {
"requires": [
"dd-drop"
]
},
"dd-gestures": {
"condition": {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
},
"requires": [
"dd-drag",
"event-synthetic",
"event-gestures"
]
},
"dd-plugin": {
"optional": [
"dd-constrain",
"dd-proxy"
],
"requires": [
"dd-drag"
]
},
"dd-proxy": {
"requires": [
"dd-drag"
]
},
"dd-scroll": {
"requires": [
"dd-drag"
]
},
"dial": {
"lang": [
"en",
"es"
],
"requires": [
"widget",
"dd-drag",
"substitute",
"event-mouseenter",
"event-move",
"event-key",
"transition",
"intl"
],
"skinnable": true
},
"dom": {
"use": [
"dom-base",
"dom-screen",
"dom-style",
"selector-native",
"selector"
]
},
"dom-base": {
"requires": [
"dom-core"
]
},
"dom-core": {
"requires": [
"oop",
"features"
]
},
"dom-deprecated": {
"requires": [
"dom-base"
]
},
"dom-screen": {
"requires": [
"dom-base",
"dom-style"
]
},
"dom-style": {
"requires": [
"dom-base"
]
},
"dom-style-ie": {
"condition": {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
},
"requires": [
"dom-style"
]
},
"dump": {
"requires": [
"yui-base"
]
},
"editor": {
"use": [
"frame",
"selection",
"exec-command",
"editor-base",
"editor-para",
"editor-br",
"editor-bidi",
"editor-tab",
"createlink-base"
]
},
"editor-base": {
"requires": [
"base",
"frame",
"node",
"exec-command",
"selection"
]
},
"editor-bidi": {
"requires": [
"editor-base"
]
},
"editor-br": {
"requires": [
"editor-base"
]
},
"editor-lists": {
"requires": [
"editor-base"
]
},
"editor-para": {
"requires": [
"editor-base"
]
},
"editor-tab": {
"requires": [
"editor-base"
]
},
"escape": {
"requires": [
"yui-base"
]
},
"event": {
"after": [
"node-base"
],
"use": [
"event-base",
"event-delegate",
"event-synthetic",
"event-mousewheel",
"event-mouseenter",
"event-key",
"event-focus",
"event-resize",
"event-hover",
"event-outside"
]
},
"event-base": {
"after": [
"node-base"
],
"requires": [
"event-custom-base"
]
},
"event-base-ie": {
"after": [
"event-base"
],
"condition": {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
},
"requires": [
"node-base"
]
},
"event-custom": {
"use": [
"event-custom-base",
"event-custom-complex"
]
},
"event-custom-base": {
"requires": [
"oop"
]
},
"event-custom-complex": {
"requires": [
"event-custom-base"
]
},
"event-delegate": {
"requires": [
"node-base"
]
},
"event-flick": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-focus": {
"requires": [
"event-synthetic"
]
},
"event-gestures": {
"use": [
"event-flick",
"event-move"
]
},
"event-hover": {
"requires": [
"event-mouseenter"
]
},
"event-key": {
"requires": [
"event-synthetic"
]
},
"event-mouseenter": {
"requires": [
"event-synthetic"
]
},
"event-mousewheel": {
"requires": [
"node-base"
]
},
"event-move": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-outside": {
"requires": [
"event-synthetic"
]
},
"event-resize": {
"requires": [
"node-base",
"event-synthetic"
]
},
"event-simulate": {
"requires": [
"event-base"
]
},
"event-synthetic": {
"requires": [
"node-base",
"event-custom-complex"
]
},
"event-touch": {
"requires": [
"node-base"
]
},
"event-valuechange": {
"requires": [
"event-focus",
"event-synthetic"
]
},
"exec-command": {
"requires": [
"frame"
]
},
"features": {
"requires": [
"yui-base"
]
},
"frame": {
"requires": [
"base",
"node",
"selector-css3",
"substitute",
"yui-throttle"
]
},
"get": {
"requires": [
"yui-base"
]
},
"graphics": {
"requires": [
"node",
"event-custom",
"pluginhost"
]
},
"graphics-canvas": {
"condition": {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-canvas-default": {
"condition": {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
}
},
"graphics-svg": {
"condition": {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-svg-default": {
"condition": {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
}
},
"graphics-vml": {
"condition": {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-vml-default": {
"condition": {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
}
},
"highlight": {
"use": [
"highlight-base",
"highlight-accentfold"
]
},
"highlight-accentfold": {
"requires": [
"highlight-base",
"text-accentfold"
]
},
"highlight-base": {
"requires": [
"array-extras",
"classnamemanager",
"escape",
"text-wordbreak"
]
},
"history": {
"use": [
"history-base",
"history-hash",
"history-hash-ie",
"history-html5"
]
},
"history-base": {
"requires": [
"event-custom-complex"
]
},
"history-hash": {
"after": [
"history-html5"
],
"requires": [
"event-synthetic",
"history-base",
"yui-later"
]
},
"history-hash-ie": {
"condition": {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
},
"requires": [
"history-hash",
"node-base"
]
},
"history-html5": {
"optional": [
"json"
],
"requires": [
"event-base",
"history-base",
"node-base"
]
},
"imageloader": {
"requires": [
"base-base",
"node-style",
"node-screen"
]
},
"intl": {
"requires": [
"intl-base",
"event-custom"
]
},
"intl-base": {
"requires": [
"yui-base"
]
},
"io": {
"use": [
"io-base",
"io-xdr",
"io-form",
"io-upload-iframe",
"io-queue"
]
},
"io-base": {
"requires": [
"event-custom-base",
"querystring-stringify-simple"
]
},
"io-form": {
"requires": [
"io-base",
"node-base"
]
},
"io-queue": {
"requires": [
"io-base",
"queue-promote"
]
},
"io-upload-iframe": {
"requires": [
"io-base",
"node-base"
]
},
"io-xdr": {
"requires": [
"io-base",
"datatype-xml"
]
},
"json": {
"use": [
"json-parse",
"json-stringify"
]
},
"json-parse": {
"requires": [
"yui-base"
]
},
"json-stringify": {
"requires": [
"yui-base"
]
},
"jsonp": {
"requires": [
"get",
"oop"
]
},
"jsonp-url": {
"requires": [
"jsonp"
]
},
"loader": {
"use": [
"loader-base",
"loader-rollup",
"loader-yui3"
]
},
"loader-base": {
"requires": [
"get"
]
},
"loader-rollup": {
"requires": [
"loader-base"
]
},
"loader-yui3": {
"requires": [
"loader-base"
]
},
"model": {
"requires": [
"base-build",
"escape",
"json-parse"
]
},
"model-list": {
"requires": [
"array-extras",
"array-invoke",
"arraylist",
"base-build",
"escape",
"json-parse",
"model"
]
},
"node": {
"use": [
"node-base",
"node-event-delegate",
"node-pluginhost",
"node-screen",
"node-style"
]
},
"node-base": {
"requires": [
"event-base",
"node-core",
"dom-base"
]
},
"node-core": {
"requires": [
"dom-core",
"selector"
]
},
"node-deprecated": {
"requires": [
"node-base"
]
},
"node-event-delegate": {
"requires": [
"node-base",
"event-delegate"
]
},
"node-event-html5": {
"requires": [
"node-base"
]
},
"node-event-simulate": {
"requires": [
"node-base",
"event-simulate"
]
},
"node-flick": {
"requires": [
"classnamemanager",
"transition",
"event-flick",
"plugin"
],
"skinnable": true
},
"node-focusmanager": {
"requires": [
"attribute",
"node",
"plugin",
"node-event-simulate",
"event-key",
"event-focus"
]
},
"node-load": {
"requires": [
"node-base",
"io-base"
]
},
"node-menunav": {
"requires": [
"node",
"classnamemanager",
"plugin",
"node-focusmanager"
],
"skinnable": true
},
"node-pluginhost": {
"requires": [
"node-base",
"pluginhost"
]
},
"node-screen": {
"requires": [
"dom-screen",
"node-base"
]
},
"node-style": {
"requires": [
"dom-style",
"node-base"
]
},
"oop": {
"requires": [
"yui-base"
]
},
"overlay": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain"
],
"skinnable": true
},
"panel": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain",
"widget-modality",
"widget-autohide",
"widget-buttons"
],
"skinnable": true
},
"plugin": {
"requires": [
"base-base"
]
},
"pluginhost": {
"use": [
"pluginhost-base",
"pluginhost-config"
]
},
"pluginhost-base": {
"requires": [
"yui-base"
]
},
"pluginhost-config": {
"requires": [
"pluginhost-base"
]
},
"profiler": {
"requires": [
"yui-base"
]
},
"querystring": {
"use": [
"querystring-parse",
"querystring-stringify"
]
},
"querystring-parse": {
"requires": [
"yui-base",
"array-extras"
]
},
"querystring-parse-simple": {
"requires": [
"yui-base"
]
},
"querystring-stringify": {
"requires": [
"yui-base"
]
},
"querystring-stringify-simple": {
"requires": [
"yui-base"
]
},
"queue-promote": {
"requires": [
"yui-base"
]
},
"range-slider": {
"requires": [
"slider-base",
"slider-value-range",
"clickable-rail"
]
},
"recordset": {
"use": [
"recordset-base",
"recordset-sort",
"recordset-filter",
"recordset-indexer"
]
},
"recordset-base": {
"requires": [
"base",
"arraylist"
]
},
"recordset-filter": {
"requires": [
"recordset-base",
"array-extras",
"plugin"
]
},
"recordset-indexer": {
"requires": [
"recordset-base",
"plugin"
]
},
"recordset-sort": {
"requires": [
"arraysort",
"recordset-base",
"plugin"
]
},
"resize": {
"use": [
"resize-base",
"resize-proxy",
"resize-constrain"
]
},
"resize-base": {
"requires": [
"base",
"widget",
"substitute",
"event",
"oop",
"dd-drag",
"dd-delegate",
"dd-drop"
],
"skinnable": true
},
"resize-constrain": {
"requires": [
"plugin",
"resize-base"
]
},
"resize-plugin": {
"optional": [
"resize-constrain"
],
"requires": [
"resize-base",
"plugin"
]
},
"resize-proxy": {
"requires": [
"plugin",
"resize-base"
]
},
"rls": {
"requires": [
"get",
"features"
]
},
"scrollview": {
"requires": [
"scrollview-base",
"scrollview-scrollbars"
]
},
"scrollview-base": {
"requires": [
"widget",
"event-gestures",
"transition"
],
"skinnable": true
},
"scrollview-base-ie": {
"condition": {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
},
"requires": [
"scrollview-base"
]
},
"scrollview-list": {
"requires": [
"plugin",
"classnamemanager"
],
"skinnable": true
},
"scrollview-paginator": {
"requires": [
"plugin"
]
},
"scrollview-scrollbars": {
"requires": [
"classnamemanager",
"transition",
"plugin"
],
"skinnable": true
},
"selection": {
"requires": [
"node"
]
},
"selector": {
"requires": [
"selector-native"
]
},
"selector-css2": {
"condition": {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
},
"requires": [
"selector-native"
]
},
"selector-css3": {
"requires": [
"selector-native",
"selector-css2"
]
},
"selector-native": {
"requires": [
"dom-base"
]
},
"shim-plugin": {
"requires": [
"node-style",
"node-pluginhost"
]
},
"slider": {
"use": [
"slider-base",
"slider-value-range",
"clickable-rail",
"range-slider"
]
},
"slider-base": {
"requires": [
"widget",
"dd-constrain",
"substitute"
],
"skinnable": true
},
"slider-value-range": {
"requires": [
"slider-base"
]
},
"sortable": {
"requires": [
"dd-delegate",
"dd-drop-plugin",
"dd-proxy"
]
},
"sortable-scroll": {
"requires": [
"dd-scroll",
"sortable"
]
},
"stylesheet": {
"requires": [
"yui-base"
]
},
"substitute": {
"optional": [
"dump"
],
"requires": [
"yui-base"
]
},
"swf": {
"requires": [
"event-custom",
"node",
"swfdetect",
"escape"
]
},
"swfdetect": {
"requires": [
"yui-base"
]
},
"tabview": {
"requires": [
"widget",
"widget-parent",
"widget-child",
"tabview-base",
"node-pluginhost",
"node-focusmanager"
],
"skinnable": true
},
"tabview-base": {
"requires": [
"node-event-delegate",
"classnamemanager",
"skin-sam-tabview"
]
},
"tabview-plugin": {
"requires": [
"tabview-base"
]
},
"test": {
"requires": [
"event-simulate",
"event-custom",
"substitute",
"json-stringify"
],
"skinnable": true
},
"text": {
"use": [
"text-accentfold",
"text-wordbreak"
]
},
"text-accentfold": {
"requires": [
"array-extras",
"text-data-accentfold"
]
},
"text-data-accentfold": {
"requires": [
"yui-base"
]
},
"text-data-wordbreak": {
"requires": [
"yui-base"
]
},
"text-wordbreak": {
"requires": [
"array-extras",
"text-data-wordbreak"
]
},
"transition": {
"requires": [
"node-style"
]
},
"transition-timer": {
"condition": {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
},
"requires": [
"transition"
]
},
"uploader": {
"requires": [
"event-custom",
"node",
"base",
"swf"
]
},
"view": {
"requires": [
"base-build",
"node-event-delegate"
]
},
"widget": {
"use": [
"widget-base",
"widget-htmlparser",
"widget-uievents",
"widget-skin"
]
},
"widget-anim": {
"requires": [
"plugin",
"anim-base",
"widget"
]
},
"widget-autohide": {
"requires": [
"widget",
"event-outside",
"base-build",
"event-key"
],
"skinnable": false
},
"widget-base": {
"requires": [
"attribute",
"event-focus",
"base-base",
"base-pluginhost",
"node-base",
"node-style",
"classnamemanager"
],
"skinnable": true
},
"widget-base-ie": {
"condition": {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
},
"requires": [
"widget-base"
]
},
"widget-buttons": {
"requires": [
"widget",
"base-build",
"widget-stdmod"
],
"skinnable": true
},
"widget-child": {
"requires": [
"base-build",
"widget"
]
},
"widget-htmlparser": {
"requires": [
"widget-base"
]
},
"widget-locale": {
"requires": [
"widget-base"
]
},
"widget-modality": {
"requires": [
"widget",
"event-outside",
"base-build"
],
"skinnable": false
},
"widget-parent": {
"requires": [
"base-build",
"arraylist",
"widget"
]
},
"widget-position": {
"requires": [
"base-build",
"node-screen",
"widget"
]
},
"widget-position-align": {
"requires": [
"widget-position"
]
},
"widget-position-constrain": {
"requires": [
"widget-position"
]
},
"widget-skin": {
"requires": [
"widget-base"
]
},
"widget-stack": {
"requires": [
"base-build",
"widget"
],
"skinnable": true
},
"widget-stdmod": {
"requires": [
"base-build",
"widget"
]
},
"widget-uievents": {
"requires": [
"widget-base",
"node-event-delegate"
]
},
"yql": {
"requires": [
"jsonp",
"jsonp-url"
]
},
"yui": {},
"yui-base": {},
"yui-later": {
"requires": [
"yui-base"
]
},
"yui-log": {
"requires": [
"yui-base"
]
},
"yui-rls": {},
"yui-throttle": {
"requires": [
"yui-base"
]
}
};
YUI.Env[Y.version].md5 = '94b4cd94d5b5f12f01ec8758dc2d9a6e';
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3' ]});
|
src/components/panel/__tests__/index.js | KleeGroup/focus-components |
import TestUtils from 'react-dom/test-utils';
import React from 'react';
import ReactDOM from 'react-dom';
import Panel from '../';
import { init, translate } from 'focus-core/translation';
const i18nConfig = {
resources: {},
lng: 'fr-FR'///langOpts.i18nCulture
};
const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils;
describe('The Panel', () => {
beforeEach(() => {
init(i18nConfig);
});
describe('when mounted with no props', () => {
let reactComponent, domNode;
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should render data-focus attribute', () => {
expect(reactComponent).toBeDefined();
expect(reactComponent).toBeInstanceOf(Object);
expect(domNode.tagName).toBe('DIV');
expect(domNode.getAttribute('data-focus')).toBe('panel');
expect(domNode.getAttribute('data-spy')).not.toBeNull();
expect(domNode.getAttribute('data-spy')).not.toBeUndefined();
});
it('should have a data-spy attribute', () => {
expect(domNode.getAttribute('data-spy')).not.toBeNull();
expect(domNode.getAttribute('data-spy')).not.toBeUndefined();
});
it('should be material designed', () => {
expect(domNode.getAttribute('class')).toBe('mdl-card mdl-card--border mdl-shadow--4dp');
});
it('should not have a title section', () => {
const titleSection = domNode.querySelector('[data-focus="panel-title"]');
expect(titleSection).toBeNull();
});
it('should have a content section', () => {
const contentSection = domNode.querySelector('[data-focus="panel-content"]');
expect(contentSection).toBeDefined();
});
it('should not have a top actions', () => {
const topActions = domNode.querySelector('[data-focus="panel-title"] .actions');
expect(topActions).toBeNull();
});
it('should not have a bottom actions section', () => {
const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
expect(bottomSection).toBeNull();
});
});
describe('when mounted with title props', () => {
init({ resources: { dev: { translation: { panel: { title: 'This is a title' } } } } }, () => {
let reactComponent, domNode;
const title = 'panel.title';
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel title={title} />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should display a title', () => {
const titleContent = domNode.querySelector('[data-focus="panel-title"] h3');
expect(titleContent).toBeDefined();
expect(titleContent.tagName).toBe('H3');
expect(titleContent.getAttribute('data-spy-title')).toBeDefined();
expect(titleContent.innerHTML).toBe(translate(title));
});
});
});
describe('when mounted with actions props', () => {
let domNode, reactComponent;
const actions = () => <span>{'actions'}</span>;
describe('by default', () => {
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel actions={actions} />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should display actions top by default', () => {
const topActions = domNode.querySelector('[data-focus="panel-title"] .actions');
expect(topActions).toBeDefined();
});
it('should not have a bottom actions section', () => {
const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
expect(bottomSection).toBeNull();
});
});
describe('with actionsPosition top', () => {
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel actions={actions} actionsPosition='top' />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should display actions at the top', () => {
const topActions = domNode.querySelector('[data-focus="panel-title"] .actions');
expect(topActions).toBeDefined();
});
it('should not display action at the bottom', () => {
const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
expect(bottomSection).toBeNull();
});
});
describe('with actionsPosition bottom', () => {
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel actions={actions} actionsPosition='bottom' />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should not display actions at the top', () => {
const topActions = domNode.querySelector('[data-focus="panel-title"] .actions');
expect(topActions).toBeNull();
});
it('should display action at the bottom', () => {
const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
expect(bottomSection).toBeDefined();
});
});
describe('with actionsPosition both', () => {
beforeEach(() => {
reactComponent = renderIntoDocument(<Panel actions={actions} actionsPosition='both' />);
domNode = ReactDOM.findDOMNode(reactComponent);
});
it('should display actions at the top', () => {
const topActions = domNode.querySelector('[data-focus="panel-title"] .actions');
expect(topActions).toBeDefined();
});
it('should display action at the bottom', () => {
const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
expect(bottomSection).toBeDefined();
});
});
});
});
// <div className='mdl-card mdl-card--border mdl-shadow--4dp' data-spy={spyId} data-focus='panel' {...otherProps}>
// <div className='mdl-card__title mdl-card--border' data-focus='panel-title'>
// {title &&
// <h3 data-spy-title>{this.i18n(title)}</h3>
// }
// {shouldDisplayActionsTop &&
// <div className='actions'>{actions()}</div>
// }
// </div>
// <div className='mdl-card__supporting-text' data-focus='panel-content'>
// {children}
// </div>
// {shouldDisplayActionsBottom &&
// <div className='mdl-card__actions mdl-card--border' data-focus='panel-actions'>
// <div className='actions'>{actions()}</div>
// </div>
// }
// </div>
|
ajax/libs/6to5/2.4.3/browser-polyfill.js | pc035860/cdnjs | (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){require("core-js/shim");require("regenerator/runtime")},{"core-js/shim":2,"regenerator/runtime":3}],2:[function(require,module,exports){!function(returnThis,framework,undefined){"use strict";var global=returnThis(),OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it)has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG)||hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,REFERENCE_GET;function part(){var length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return partial(this,args,length,holder,_,false)}function partial(fn,argsPart,lengthPart,holder,_,bind,context){assertFunction(fn);return function(){var that=bind?context:this,length=arguments.length,i=0,j=0,args;if(!holder&&!length)return invoke(fn,argsPart,that);args=argsPart.slice();if(holder)for(;lengthPart>i;i++)if(args[i]===_)args[i]=arguments[j++];while(length>j)args.push(arguments[j++]);return invoke(fn,args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object;function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=ES5Object(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn,that){var O=Object(assertDefined(this)),self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el,fromIndex){var O=ES5Object(assertDefined(this)),length=toLength(O.length),index=toIndex(fromIndex,length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function turn(mapfn,target){assertFunction(mapfn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;for(;length>index;index++){if(mapfn(memo,O[index],index,this)===false)break}return memo}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},0,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);defineIterator(Base,NAME,createIter(DEFAULT),DEFAULT==VALUE?"values":"entries");DEFAULT&&$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:createIter(KEY+VALUE),keys:createIter(KEY),values:createIter(VALUE)})}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it);return SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){return assertObject((it[SYMBOL_ITERATOR]||Iterators[classof(it)]).call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(NODE)module.exports=core;if(isFunction(define)&&define.amd)define(function(){return core});if(!NODE||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive,unscopables"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(GLOBAL,{Reflect:{ownKeys:ownKeys}})}(safeSymbol("tag"),{},true);!function(isFinite,tmp){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(it){return(it=+it)==0||it!=it?it:it<0?-1:1},pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return x<1?NaN:log(x+sqrt(x*x-1))},asinh:asinh,atanh:function(x){return x==0?+x:log((1+ +x)/(1-x))/2},cbrt:function(x){return sign(x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x)+exp(-x))/2},expm1:function(x){return x==0?+x:x>-1e-6&&x<1e-6?+x+x*x/2:exp(x)-1},fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,length=arguments.length,value;while(length--){value=+arguments[length];if(value==Infinity||value==-Infinity)return Infinity;sum+=value*value}return sqrt(sum)},imul:function(x,y){var UInt16=65535,xl=UInt16&x,yl=UInt16&y;return 0|xl*yl+((UInt16&x>>>16)*yl+xl*(UInt16&y>>>16)<<16>>>0)},log1p:function(x){return x>-1e-8&&x<1e-8?x-x*x/2:log(1+ +x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return x==0?+x:(exp(x)-exp(-x))/2},tanh:function(x){return isFinite(x)?x==0?+x:(exp(x)-exp(-x))/(exp(x)+exp(-x)):sign(x)},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(isObject(it)&&it instanceof RegExp)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=ES5Object(assertDefined(callSite.raw)),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString,endPosition){assertNotRegExp(searchString);var len=this.length,end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return String(this).slice(end-searchString.length,end)===searchString},includes:function(searchString,position){return!!~String(assertDefined(this)).indexOf(searchString,position)},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString,position){assertNotRegExp(searchString);var index=toLength(min(position,this.length));searchString+="";return String(this).slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike,mapfn,that){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start,end){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value,start,end){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(start,length),endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:ES5Object(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});if(/./g.flags!="g")defineProperty(RegExp[PROTOTYPE],"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")})}}(isFinite,{});isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(Function()))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new this[CONSTRUCTOR](function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=this,values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=this;return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new this(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&getPrototypeOf(x)===this[PROTOTYPE]?x:new this(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),DATA=safeSymbol("data"),WEAK=safeSymbol("weak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0;function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];framework&&hidden(proto,key,function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result})}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn,that){var f=ctx(callbackfn,that,3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function setWeak(that,key,value){has(assertObject(key),WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value;return that}function hasWeak(key){return isObject(key)&&has(key,WEAK)&&has(key[WEAK],this[UID])}var weakMethods={"delete":function(key){return hasWeak.call(this,key)&&delete key[WEAK][this[UID]]},has:hasWeak};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAK))return key[WEAK][this[UID]]},set:function(key,value){return setWeak(this,key,value)}},weakMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return setWeak(this,value,true)}},weakMethods,false,true)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=ES5Object(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(){function setArrayStatics(keys,length){$define(STATIC,ARRAY,turn.call(array(keys),function(memo,key){if(key in ArrayProto)memo[key]=ctx(call,ArrayProto[key],length)},{}))}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn")}()}(Function("return this"),true)},{}],3:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;
if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1;function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next}return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{}]},{},[1]); |
ajax/libs/muicss/0.5.2/react/mui-react.min.js | sufuf3/cdnjs | !function(e){var t=e.babelHelpers={};t["typeof"]="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},t.jsx=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,r,n,l){var o=t&&t.defaultProps,s=arguments.length-3;if(r||0===s||(r={}),r&&o)for(var a in o)void 0===r[a]&&(r[a]=o[a]);else r||(r=o||{});if(1===s)r.children=l;else if(s>1){for(var i=Array(s),u=0;s>u;u++)i[u]=arguments[u+3];r.children=i}return{$$typeof:e,type:t,key:void 0===n?null:""+n,ref:null,props:r,_owner:null}}}(),t.asyncToGenerator=function(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,r){function n(l,o){try{var s=t[l](o),a=s.value}catch(i){return void r(i)}return s.done?void e(a):Promise.resolve(a).then(function(e){return n("next",e)},function(e){return n("throw",e)})}return n("next")})}},t.classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),t.defineEnumerableProperties=function(e,t){for(var r in t){var n=t[r];n.configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,r,n)}return e},t.defaults=function(e,t){for(var r=Object.getOwnPropertyNames(t),n=0;n<r.length;n++){var l=r[n],o=Object.getOwnPropertyDescriptor(t,l);o&&o.configurable&&void 0===e[l]&&Object.defineProperty(e,l,o)}return e},t.defineProperty=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},t["extends"]=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.get=function r(e,t,n){null===e&&(e=Function.prototype);var l=Object.getOwnPropertyDescriptor(e,t);if(void 0===l){var o=Object.getPrototypeOf(e);return null===o?void 0:r(o,t,n)}if("value"in l)return l.value;var s=l.get;if(void 0!==s)return s.call(n)},t.inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},t["instanceof"]=function(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?t[Symbol.hasInstance](e):e instanceof t},t.interopRequireDefault=function(e){return e&&e.__esModule?e:{"default":e}},t.interopRequireWildcard=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t},t.newArrowCheck=function(e,t){if(e!==t)throw new TypeError("Cannot instantiate an arrow function")},t.objectDestructuringEmpty=function(e){if(null==e)throw new TypeError("Cannot destructure undefined")},t.objectWithoutProperties=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r},t.possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},t.selfGlobal="undefined"==typeof e?self:e,t.set=function n(e,t,r,l){var o=Object.getOwnPropertyDescriptor(e,t);if(void 0===o){var s=Object.getPrototypeOf(e);null!==s&&n(s,t,r,l)}else if("value"in o&&o.writable)o.value=r;else{var a=o.set;void 0!==a&&a.call(l,r)}return r},t.slicedToArray=function(){function e(e,t){var r=[],n=!0,l=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(i){l=!0,o=i}finally{try{!n&&a["return"]&&a["return"]()}finally{if(l)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),t.slicedToArrayLoose=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e)){for(var r,n=[],l=e[Symbol.iterator]();!(r=l.next()).done&&(n.push(r.value),!t||n.length!==t););return n}throw new TypeError("Invalid attempt to destructure non-iterable instance")},t.taggedTemplateLiteral=function(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))},t.taggedTemplateLiteralLoose=function(e,t){return e.raw=t,e},t.temporalRef=function(e,t,r){if(e===r)throw new ReferenceError(t+" is not defined - temporal dead zone");return e},t.temporalUndefined={},t.toArray=function(e){return Array.isArray(e)?e:Array.from(e)},t.toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}}("undefined"==typeof global?self:global),function e(t,r,n){function l(s,a){if(!r[s]){if(!t[s]){var i="function"==typeof require&&require;if(!a&&i)return i(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=r[s]={exports:{}};t[s][0].call(u.exports,function(e){var r=t[s][1][e];return l(r?r:e)},u,u.exports,e,t,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s<n.length;s++)l(n[s]);return l}({1:[function(e,t,r){"use strict";!function(t){if(!t._muiReactLoaded){t._muiReactLoaded=!0;var r=t.mui=t.mui||[],n=r.react={};n.Appbar=e("src/react/appbar"),n.Button=e("src/react/button"),n.Caret=e("src/react/caret"),n.Checkbox=e("src/react/checkbox"),n.Col=e("src/react/col"),n.Container=e("src/react/container"),n.Divider=e("src/react/divider"),n.Dropdown=e("src/react/dropdown"),n.DropdownItem=e("src/react/dropdown-item"),n.Form=e("src/react/form"),n.Input=e("src/react/input"),n.Option=e("src/react/option"),n.Panel=e("src/react/panel"),n.Radio=e("src/react/radio"),n.Row=e("src/react/row"),n.Select=e("src/react/select"),n.Tab=e("src/react/tab"),n.Tabs=e("src/react/tabs"),n.Textarea=e("src/react/textarea")}}(window)},{"src/react/appbar":11,"src/react/button":12,"src/react/caret":13,"src/react/checkbox":14,"src/react/col":15,"src/react/container":16,"src/react/divider":17,"src/react/dropdown":19,"src/react/dropdown-item":18,"src/react/form":20,"src/react/input":21,"src/react/option":22,"src/react/panel":23,"src/react/radio":24,"src/react/row":25,"src/react/select":26,"src/react/tab":27,"src/react/tabs":28,"src/react/textarea":29}],2:[function(e,t,r){"use strict";t.exports={debug:!0}},{}],3:[function(e,t,r){"use strict";function n(e,t,r){var n,i,u,c,p=document.documentElement.clientHeight,d=t*s+2*a,f=Math.min(d,p);i=a+s-(l+o),i-=r*s,u=-1*e.getBoundingClientRect().top,c=p-f+u,n=Math.min(Math.max(i,u),c);var b,h,v=0;return d>p&&(b=a+(r+1)*s-(-1*n+l+o),h=t*s+2*a-f,v=Math.min(b,h)),{height:f+"px",top:n+"px",scrollTop:v}}var l=15,o=32,s=42,a=8;t.exports={getMenuPositionalCSS:n}},{}],4:[function(e,t,r){"use strict";function n(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)r=l[o].trim(),-1===n.indexOf(" "+r+" ")&&(n+=r+" ");e.setAttribute("class",n.trim())}}function l(e,t,r){if(void 0===t)return getComputedStyle(e);var n=s(t);{if("object"!==n){"string"===n&&void 0!==r&&(e.style[v(t)]=r);var l=getComputedStyle(e),o="array"===s(t);if(!o)return y(e,t,l);for(var a,i={},u=0;u<t.length;u++)a=t[u],i[a]=y(e,a,l);return i}for(var a in t)e.style[v(a)]=t[a]}}function o(e,t){return t&&e.getAttribute?h(e).indexOf(" "+t+" ")>-1:!1}function s(e){if(void 0===e)return"undefined";var t=Object.prototype.toString.call(e);if(0===t.indexOf("[object "))return t.slice(8,-1).toLowerCase();throw new Error("MUI: Could not understand type: "+t)}function a(e,t,r,n){n=void 0===n?!1:n,e.addEventListener(t,r,n);var l=e._muiEventCache=e._muiEventCache||{};l[t]=l[t]||[],l[t].push([r,n])}function i(e,t,r,n){n=void 0===n?!1:n;var l,o,s=e._muiEventCache=e._muiEventCache||{},a=s[t]||[];for(o=a.length;o--;)l=a[o],(void 0===r||l[0]===r&&l[1]===n)&&(a.splice(o,1),e.removeEventListener(t,l[0],l[1]))}function u(e,t,r,n){a(e,t,function l(n){r&&r.apply(this,arguments),i(e,t,l)},n)}function c(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}return e.scrollLeft}e===r?r.scrollTo(t,p(r)):e.scrollLeft=t}function p(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageYOffset||n.scrollTop)-(n.clientTop||0)}return e.scrollTop}e===r?r.scrollTo(c(r),t):e.scrollTop=t}function d(e){var t=window,r=e.getBoundingClientRect(),n=p(t),l=c(t);return{top:r.top+n,left:r.left+l,height:r.height,width:r.width}}function f(e){var t=!1,r=!0,n=document,l=n.defaultView,o=n.documentElement,s=n.addEventListener?"addEventListener":"attachEvent",a=n.addEventListener?"removeEventListener":"detachEvent",i=n.addEventListener?"":"on",u=function d(r){"readystatechange"==r.type&&"complete"!=n.readyState||(("load"==r.type?l:n)[a](i+r.type,d,!1),!t&&(t=!0)&&e.call(l,r.type||r))},c=function f(){try{o.doScroll("left")}catch(e){return void setTimeout(f,50)}u("poll")};if("complete"==n.readyState)e.call(l,"lazy");else{if(n.createEventObject&&o.doScroll){try{r=!l.frameElement}catch(p){}r&&c()}n[s](i+"DOMContentLoaded",u,!1),n[s](i+"readystatechange",u,!1),l[s](i+"load",u,!1)}}function b(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)for(r=l[o].trim();n.indexOf(" "+r+" ")>=0;)n=n.replace(" "+r+" "," ");e.setAttribute("class",n.trim())}}function h(e){var t=(e.getAttribute("class")||"").replace(/[\n\t]/g,"");return" "+t+" "}function v(e){return e.replace(C,function(e,t,r,n){return n?r.toUpperCase():r}).replace(g,"Moz$1")}function y(e,t,r){var n;return n=r.getPropertyValue(t),""!==n||e.ownerDocument||(n=e.style[v(t)]),n}var m,C=/([\:\-\_]+(.))/g,g=/^moz([A-Z])/;m={multiple:!0,selected:!0,checked:!0,disabled:!0,readonly:!0,required:!0,open:!0},t.exports={addClass:n,css:l,hasClass:o,off:i,offset:d,on:a,one:u,ready:f,removeClass:b,type:s,scrollLeft:c,scrollTop:p}},{}],5:[function(e,t,r){"use strict";function n(){var e=window;if(v.debug&&"undefined"!=typeof e.console)try{e.console.log.apply(e.console,arguments)}catch(t){var r=Array.prototype.slice.call(arguments);e.console.log(r.join("\n"))}}function l(e){var t,r=document;t=r.head||r.getElementsByTagName("head")[0]||r.documentElement;var n=r.createElement("style");return n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(r.createTextNode(e)),t.insertBefore(n,t.firstChild),n}function o(e,t){if(!t)throw new Error("MUI: "+e);"undefined"!=typeof console&&console.error("MUI Warning: "+e)}function s(e){if(m.push(e),void 0===m._initialized){var t=document;y.on(t,"animationstart",a),y.on(t,"mozAnimationStart",a),y.on(t,"webkitAnimationStart",a),m._initialized=!0}}function a(e){if("mui-node-inserted"===e.animationName)for(var t=e.target,r=m.length-1;r>=0;r--)m[r](t)}function i(e){var t="";for(var r in e)t+=e[r]?r+" ":"";return t.trim()}function u(){if(void 0!==h)return h;var e=document.createElement("x");return e.style.cssText="pointer-events:auto",h="auto"===e.style.pointerEvents}function c(e,t){return function(){e[t].apply(e,arguments)}}function p(e,t,r,n,l){var o,s=document.createEvent("HTMLEvents"),r=void 0!==r?r:!0,n=void 0!==n?n:!0;if(s.initEvent(t,r,n),l)for(o in l)s[o]=l[o];return e&&e.dispatchEvent(s),s}function d(){if(C+=1,1===C){var e=window,t=document;b={left:y.scrollLeft(e),top:y.scrollTop(e)},y.addClass(t.body,g),e.scrollTo(b.left,b.top)}}function f(){if(0!==C&&(C-=1,0===C)){var e=window,t=document;y.removeClass(t.body,g),e.scrollTo(b.left,b.top)}}var b,h,v=e("../config"),y=e("./jqLite"),m=[],C=0,g="mui-body--scroll-lock";t.exports={callback:c,classNames:i,disableScrollLock:f,dispatchEvent:p,enableScrollLock:d,log:n,loadStyle:l,onNodeInserted:s,raiseError:o,supportsPointerEvents:u}},{"../config":2,"./jqLite":4}],6:[function(e,t,r){"use strict";var n="You provided a `value` prop to a form field without an `OnChange` handler. Please see React documentation on controlled components";t.exports={controlledMessage:n}},{}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/jqLite"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/util"),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u="mui-btn",c="mui-ripple-effect",p={color:1,variant:1,size:1},d=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={ripples:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this.refs.buttonEl;e._muiDropdown=!0,e._muiRipple=!0}},{key:"onClick",value:function(e){var t=this.props.onClick;t&&t(e)}},{key:"onMouseDown",value:function(e){var t=s.offset(this.refs.buttonEl),r=t.height;"fab"===this.props.variant&&(r/=2);var n=this.state.ripples,l=Date.now();n[l]={xPos:e.pageX-t.left,yPos:e.pageY-t.top,diameter:r,teardownFn:this.teardownRipple.bind(this,l)},this.setState({ripples:n})}},{key:"onTouchStart",value:function(e){}},{key:"teardownRipple",value:function(e){var t=this.state.ripples;delete t[e],this.setState({ripples:t})}},{key:"render",value:function(){var e=u,t=void 0,r=void 0,n=this.state.ripples;for(t in p)r=this.props[t],"default"!==r&&(e+=" "+u+"--"+r);return l["default"].createElement("button",babelHelpers["extends"]({},this.props,{ref:"buttonEl",className:e+" "+this.props.className,onClick:this.onClick.bind(this),onMouseDown:this.onMouseDown.bind(this)}),this.props.children,Object.keys(n).map(function(e,t){var r=n[e];return l["default"].createElement(f,{key:e,xPos:r.xPos,yPos:r.yPos,diameter:r.diameter,onTeardown:r.teardownFn})}))}}]),t}(l["default"].Component);d.propTypes={color:i.oneOf(["default","primary","danger","dark","accent"]),disabled:i.bool,size:i.oneOf(["default","small","large"]),type:i.oneOf(["submit","button"]),variant:i.oneOf(["default","flat","raised","fab"]),onClick:i.func},d.defaultProps={className:"",color:"default",disabled:!1,size:"default",type:null,variant:"default",onClick:null};var f=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this,t=setTimeout(function(){var t=e.props.onTeardown;t&&t()},2e3);this.setState({teardownTimer:t})}},{key:"componentWillUnmount",value:function(){clearTimeout(this.state.teardownTimer)}},{key:"render",value:function(){var e=this.props.diameter,t=e/2,r={height:e,width:e,top:this.props.yPos-t||0,left:this.props.xPos-t||0};return l["default"].createElement("div",{className:c,style:r})}}]),t}(l["default"].Component);f.propTypes={xPos:i.number,yPos:i.number,diameter:i.number,onTeardown:i.func},f.defaultProps={xPos:0,yPos:0,diameter:0,onTeardown:null},r["default"]=d,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("span",babelHelpers["extends"]({},t,{className:"mui-caret "+this.props.className}))}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return null}}]),t}(l["default"].Component);s.propTypes={value:o.any,label:o.string,onActive:o.func},s.defaultProps={value:null,label:"",onActive:null},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TextField=void 0;var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=e("./_helpers"),i=l["default"].PropTypes,u=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e)),n=e.value,l=n||e.defaultValue;r.state={innerValue:l,isDirty:Boolean(l)},void 0!==n&&null===e.onChange&&s.raiseError(a.controlledMessage,!0);var o=s.callback;return r.onChangeCB=o(r,"onChange"),r.onFocusCB=o(r,"onFocus"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.inputEl._muiTextfield=!0}},{key:"onChange",value:function(e){this.setState({innerValue:e.target.value});var t=this.props.onChange;t&&t(e)}},{key:"onFocus",value:function(e){this.setState({isDirty:!0})}},{key:"triggerFocus",value:function(){this.refs.inputEl.focus()}},{key:"render",value:function(){var e={},t=Boolean(this.state.innerValue),r=void 0;e["mui--is-empty"]=!t,e["mui--is-not-empty"]=t,e["mui--is-dirty"]=this.state.isDirty,e["mui--is-invalid"]=this.props.invalid,e=s.classNames(e);var n=this.props,o=(n.children,babelHelpers.objectWithoutProperties(n,["children"]));return r="textarea"===this.props.type?l["default"].createElement("textarea",babelHelpers["extends"]({},o,{ref:"inputEl",className:e,rows:this.props.rows,placeholder:this.props.hint,value:this.props.value,defaultValue:this.props.defaultValue,autoFocus:this.props.autoFocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required})):l["default"].createElement("input",babelHelpers["extends"]({},o,{ref:"inputEl",className:e,type:this.props.type,value:this.props.value,defaultValue:this.props.defaultValue,placeholder:this.props.hint,autoFocus:this.props.autofocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required}))}}]),t}(l["default"].Component);u.propTypes={hint:i.string,value:i.string,type:i.string,autoFocus:i.bool,onChange:i.func},u.defaultProps={hint:null,type:null,autoFocus:!1,onChange:null};var c=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={style:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this;setTimeout(function(){var t=".15s ease-out",r=void 0;r={transition:t,WebkitTransition:t,MozTransition:t,OTransition:t,msTransform:t},e.setState({style:r})},150)}},{key:"render",value:function(){return l["default"].createElement("label",{style:this.state.style,onClick:this.props.onClick},this.props.text)}}]),t}(l["default"].Component);c.defaultProps={text:"",onClick:null};var p=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){s.supportsPointerEvents()===!1&&(e.target.style.cursor="text",this.refs.inputEl.triggerFocus())}},{key:"render",value:function(){var e={},t=void 0;return this.props.label.length&&(t=l["default"].createElement(c,{text:this.props.label,onClick:this.onClickCB})),e["mui-textfield"]=!0,e["mui-textfield--float-label"]=this.props.floatingLabel,e=s.classNames(e),l["default"].createElement("div",{className:e},l["default"].createElement(u,babelHelpers["extends"]({ref:"inputEl"},this.props)),t)}}]),t}(l["default"].Component);p.propTypes={label:i.string,floatingLabel:i.bool},p.defaultProps={label:"",floatingLabel:!1},r.TextField=p},{"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-appbar "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],12:[function(e,t,r){t.exports=e(7)},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],13:[function(e,t,r){t.exports=e(8)},{react:"CwoHg3"}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=(babelHelpers.interopRequireWildcard(o),e("./_helpers"),l["default"].PropTypes),a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,e.onChange,babelHelpers.objectWithoutProperties(e,["children","onChange"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-checkbox "+this.props.className}),l["default"].createElement("label",null,l["default"].createElement("input",{ref:"inputEl",type:"checkbox",name:this.props.name,value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled,onChange:this.props.onChange}),this.props.label))}}]),t}(l["default"].Component);a.propTypes={name:s.string,label:s.string,value:s.string,checked:s.bool,defaultChecked:s.bool,disabled:s.bool,onChange:s.func},a.defaultProps={className:"",name:null,label:null,disabled:!1,onChange:null},r["default"]=a,t.exports=r["default"]},{"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=["xs","sm","md","lg","xl"],i=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"defaultProps",value:function(){var e={className:""},t=void 0,r=void 0;for(t=a.length-1;t>-1;t--)r=a[t],e[r]=null,e[r+"-offset"]=null;return e}},{key:"render",value:function(){var e={},t=void 0,r=void 0,n=void 0,o=void 0;for(t=a.length-1;t>-1;t--)r=a[t],o="mui-col-"+r,n=this.props[r],n&&(e[o+"-"+n]=!0),n=this.props[r+"-offset"],n&&(e[o+"-offset-"+n]=!0);return e=s.classNames(e),l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="mui-container";return this.props.fluid&&(e+="-fluid"),l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.propTypes={fluid:l["default"].PropTypes.bool},o.defaultProps={className:"",fluid:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],17:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-divider "+this.props.className}))}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=l["default"].PropTypes,i=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){this.props.onClick&&this.props.onClick(this,e)}},{key:"render",value:function(){var e=this.props,t=e.children,r=(e.onClick,babelHelpers.objectWithoutProperties(e,["children","onClick"]));return l["default"].createElement("li",r,l["default"].createElement("a",{href:this.props.link,"data-mui-value":this.props.value,onClick:this.onClickCB},t))}}]),t}(l["default"].Component);i.propTypes={link:a.string,onClick:a.func},i.defaultProps={link:null,value:null,onClick:null},r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./button"),s=babelHelpers.interopRequireDefault(o),a=e("./caret"),i=babelHelpers.interopRequireDefault(a),u=e("../js/lib/jqLite"),c=babelHelpers.interopRequireWildcard(u),p=e("../js/lib/util"),d=babelHelpers.interopRequireWildcard(p),f=l["default"].PropTypes,b="mui-dropdown",h="mui-dropdown__menu",v="mui--is-open",y="mui-dropdown__menu--right",m=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={opened:!1,menuTop:0};var n=d.callback;return r.selectCB=n(r,"select"),r.onClickCB=n(r,"onClick"),r.onOutsideClickCB=n(r,"onOutsideClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){document.addEventListener("click",this.onOutsideClickCB)}},{key:"componentWillUnmount",value:function(){document.removeEventListener("click",this.onOutsideClickCB)}},{key:"onClick",value:function(e){if(0===e.button&&!this.props.disabled&&!e.defaultPrevented){this.toggle();var t=this.props.onClick;t&&t(e)}}},{key:"toggle",value:function(){return this.props.children?void(this.state.opened?this.close():this.open()):d.raiseError("Dropdown menu element not found")}},{key:"open",value:function(){var e=this.refs.wrapperEl.getBoundingClientRect(),t=void 0;t=this.refs.button.refs.buttonEl.getBoundingClientRect(),this.setState({opened:!0,menuTop:t.top-e.top+t.height})}},{key:"close",value:function(){this.setState({opened:!1})}},{key:"select",value:function(e){this.props.onSelect&&"A"===e.target.tagName&&this.props.onSelect(e.target.getAttribute("data-mui-value")),e.defaultPrevented||this.close()}},{key:"onOutsideClick",value:function(e){var t=this.refs.wrapperEl.contains(e.target);t||this.close()}},{key:"render",value:function(){var e=void 0,t=void 0,r=void 0;if(r="string"===c.type(this.props.label)?l["default"].createElement("span",null,this.props.label," ",l["default"].createElement(i["default"],null)):this.props.label,e=l["default"].createElement(s["default"],{ref:"button",type:"button",onClick:this.onClickCB,color:this.props.color,variant:this.props.variant,size:this.props.size,disabled:this.props.disabled},r),this.state.opened){var n={};n[h]=!0,n[v]=this.state.opened,n[y]="right"===this.props.alignMenu,n=d.classNames(n),t=l["default"].createElement("ul",{ref:"menuEl",className:n,style:{top:this.state.menuTop},onClick:this.selectCB},this.props.children)}var o=this.props,a=o.className,u=(o.children,o.onClick,babelHelpers.objectWithoutProperties(o,["className","children","onClick"]));return l["default"].createElement("div",babelHelpers["extends"]({},u,{ref:"wrapperEl",className:b+" "+a}),e,t)}}]),t}(l["default"].Component);m.propTypes={color:f.oneOf(["default","primary","danger","dark","accent"]),variant:f.oneOf(["default","flat","raised","fab"]),size:f.oneOf(["default","small","large"]),label:f.oneOfType([f.string,f.element]),alignMenu:f.oneOf(["left","right"]),onClick:f.func,onSelect:f.func,disabled:f.bool},m.defaultProps={className:"",color:"default",variant:"default",size:"default",label:"",alignMenu:"left",onClick:null,onSelect:null,disabled:!1},r["default"]=m,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,"./button":7,"./caret":8,react:"CwoHg3"}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="";return this.props.inline&&(e="mui-form--inline"),l["default"].createElement("form",babelHelpers["extends"]({},this.props,{className:e+" "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.propTypes={inline:l["default"].PropTypes.bool},o.defaultProps={className:"",inline:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./text-field"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={type:s.oneOf(["text","email","url","tel","password"])},a.defaultProps={type:"text"},r["default"]=a,t.exports=r["default"]},{"./text-field":10,react:"CwoHg3"}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=(babelHelpers.interopRequireWildcard(o),e("../js/lib/jqLite")),a=(babelHelpers.interopRequireWildcard(s),e("../js/lib/util")),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),
babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,babelHelpers.objectWithoutProperties(e,["children"]));return l["default"].createElement("option",babelHelpers["extends"]({},t,{value:this.props.value}),this.props.label)}}]),t}(l["default"].Component);u.propTypes={value:i.string,label:i.string},u.defaultProps={value:null,label:null},r["default"]=u,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-panel "+this.props.className}),this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],24:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e=this.props,t=(e.children,e.onChange,babelHelpers.objectWithoutProperties(e,["children","onChange"]));return l["default"].createElement("div",babelHelpers["extends"]({},t,{className:"mui-radio "+this.props.className}),l["default"].createElement("label",null,l["default"].createElement("input",{ref:"inputEl",type:"radio",name:this.props.name,value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled,onChange:this.props.onChange}),this.props.label))}}]),t}(l["default"].Component);s.propTypes={name:o.string,label:o.string,value:o.string,checked:o.bool,defaultChecked:o.bool,disabled:o.bool,onChange:o.func},s.defaultProps={className:"",name:null,label:null,disabled:!1,onChange:null},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=(babelHelpers.interopRequireWildcard(o),function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",babelHelpers["extends"]({},this.props,{className:"mui-row "+this.props.className}),this.props.children)}}]),t}(l["default"].Component));s.defaultProps={className:""},r["default"]=s,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],26:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/jqLite"),i=babelHelpers.interopRequireWildcard(a),u=e("../js/lib/util"),c=babelHelpers.interopRequireWildcard(u),p=e("./_helpers"),d=l["default"].PropTypes,f=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={showMenu:!1},e.readOnly===!1&&void 0!==e.value&&null===e.onChange&&c.raiseError(p.controlledMessage,!0),r.state.value=e.value;var n=c.callback;return r.hideMenuCB=n(r,"hideMenu"),r.onInnerChangeCB=n(r,"onInnerChange"),r.onInnerClickCB=n(r,"onInnerClick"),r.onInnerFocusCB=n(r,"onInnerFocus"),r.onInnerMouseDownCB=n(r,"onInnerMouseDown"),r.onKeydownCB=n(r,"onKeydown"),r.onMenuChangeCB=n(r,"onMenuChange"),r.onOuterFocusCB=n(r,"onOuterFocus"),r.onOuterBlurCB=n(r,"onOuterBlur"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.selectEl._muiSelect=!0,this.refs.wrapperEl.tabIndex=-1,this.props.autoFocus&&this.refs.wrapperEl.focus()}},{key:"componentWillReceiveProps",value:function(e){this.setState({value:e.value})}},{key:"onInnerMouseDown",value:function(e){0===e.button&&this.props.useDefault!==!0&&e.preventDefault()}},{key:"onInnerChange",value:function(e){var t=e.target.value;this.setState({value:t});var r=this.props.onChange;r&&r(t)}},{key:"onInnerClick",value:function(e){0===e.button&&this.showMenu()}},{key:"onInnerFocus",value:function(e){var t=this;this.props.useDefault!==!0&&setTimeout(function(){t.refs.wrapperEl.focus()},0)}},{key:"onOuterFocus",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;return t._muiOrigIndex=t.tabIndex,t.tabIndex=-1,t.disabled?this.refs.wrapperEl.blur():void i.on(document,"keydown",this.onKeydownCB)}}},{key:"onOuterBlur",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;t.tabIndex=t._muiOrigIndex,i.off(document,"keydown",this.onKeydownCB)}}},{key:"onKeydown",value:function(e){32!==e.keyCode&&38!==e.keyCode&&40!==e.keyCode||(e.preventDefault(),this.refs.selectEl.disabled!==!0&&this.showMenu())}},{key:"showMenu",value:function(){this.props.useDefault!==!0&&(c.enableScrollLock(),i.on(window,"resize",this.hideMenuCB),i.on(document,"click",this.hideMenuCB),this.setState({showMenu:!0}))}},{key:"hideMenu",value:function(){c.disableScrollLock(),i.off(window,"resize",this.hideMenuCB),i.off(document,"click",this.hideMenuCB),this.setState({showMenu:!1}),this.refs.selectEl.focus()}},{key:"onMenuChange",value:function(e){if(this.props.readOnly!==!0){this.setState({value:e});var t=this.props.onChange;t&&t(e)}}},{key:"render",value:function(){var e=void 0;this.state.showMenu&&(e=l["default"].createElement(b,{optionEls:this.refs.selectEl.children,wrapperEl:this.refs.wrapperEl,onChange:this.onMenuChangeCB,onClose:this.hideMenuCB}));var t=this.props,r=(t.children,t.onChange,babelHelpers.objectWithoutProperties(t,["children","onChange"]));return l["default"].createElement("div",babelHelpers["extends"]({},r,{ref:"wrapperEl",className:"mui-select "+this.props.className,onFocus:this.onOuterFocusCB,onBlur:this.onOuterBlurCB}),l["default"].createElement("select",{ref:"selectEl",name:this.props.name,value:this.state.value,defaultValue:this.props.defaultValue,disabled:this.props.disabled,multiple:this.props.multiple,readOnly:this.props.readOnly,required:this.props.required,onChange:this.onInnerChangeCB,onMouseDown:this.onInnerMouseDownCB,onClick:this.onInnerClickCB,onFocus:this.onInnerFocusCB},this.props.children),e)}}]),t}(l["default"].Component);f.propTypes={name:d.string,value:d.string,defaultValue:d.string,autoFocus:d.bool,disabled:d.bool,multiple:d.bool,readOnly:d.bool,required:d.bool,useDefault:d.bool,onChange:d.func},f.defaultProps={className:"",name:null,autoFocus:!1,disabled:!1,multiple:!1,readOnly:!1,required:!1,useDefault:!1,onChange:null};var b=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={origIndex:null,currentIndex:null},r.onKeydownCB=c.callback(r,"onKeydown"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){var e=this.props.optionEls,t=e.length,r=0,n=void 0;for(n=t-1;n>-1;n--)e[n].selected&&(r=n);this.setState({origIndex:r,currentIndex:r})}},{key:"componentDidMount",value:function(){setTimeout(function(){var e=document.activeElement;"body"!==e.nodeName.toLowerCase()&&e.blur()},0);var e=s.getMenuPositionalCSS(this.props.wrapperEl,this.props.optionEls.length,this.state.currentIndex),t=this.refs.wrapperEl;i.css(t,e),i.scrollTop(t,e.scrollTop),i.on(document,"keydown",this.onKeydownCB)}},{key:"componentWillUnmount",value:function(){i.off(document,"keydown",this.onKeydownCB)}},{key:"onClick",value:function(e,t){t.stopPropagation(),this.selectAndDestroy(e)}},{key:"onKeydown",value:function(e){var t=e.keyCode;return 9===t?this.destroy():(27!==t&&40!==t&&38!==t&&13!==t||e.preventDefault(),void(27===t?this.destroy():40===t?this.increment():38===t?this.decrement():13===t&&this.selectAndDestroy()))}},{key:"increment",value:function(){this.state.currentIndex!==this.props.optionEls.length-1&&this.setState({currentIndex:this.state.currentIndex+1})}},{key:"decrement",value:function(){0!==this.state.currentIndex&&this.setState({currentIndex:this.state.currentIndex-1})}},{key:"selectAndDestroy",value:function(e){e=void 0===e?this.state.currentIndex:e,e!==this.state.origIndex&&this.props.onChange(this.props.optionEls[e].value),this.destroy()}},{key:"destroy",value:function(){this.props.onClose()}},{key:"render",value:function(){var e=[],t=this.props.optionEls,r=t.length,n=void 0,o=void 0;for(o=0;r>o;o++)n=o===this.state.currentIndex?"mui--is-selected":"",e.push(l["default"].createElement("div",{key:o,className:n,onClick:this.onClick.bind(this,o)},t[o].textContent));return l["default"].createElement("div",{ref:"wrapperEl",className:"mui-select__menu"},e)}}]),t}(l["default"].Component);b.defaultProps={optionEls:[],wrapperEl:null,onChange:null,onClose:null},r["default"]=f,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,"./_helpers":6,react:"CwoHg3"}],27:[function(e,t,r){t.exports=e(9)},{react:"CwoHg3"}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./tab"),s=babelHelpers.interopRequireDefault(o),a=e("../js/lib/util"),i=babelHelpers.interopRequireWildcard(a),u=l["default"].PropTypes,c="mui-tabs__bar",p="mui-tabs__bar--justified",d="mui-tabs__pane",f="mui--is-active",b=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={currentSelectedIndex:e.initialSelectedIndex},r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e,t,r){e!==this.state.currentSelectedIndex&&(this.setState({currentSelectedIndex:e}),t.props.onActive&&t.props.onActive(t),this.props.onChange&&this.props.onChange(e,t.props.value,t,r))}},{key:"render",value:function(){var e=this.props,t=e.children,r=babelHelpers.objectWithoutProperties(e,["children"]),n=[],o=[],a=t.length,u=this.state.currentSelectedIndex%a,b=void 0,h=void 0,v=void 0,y=void 0;for(y=0;a>y;y++)h=t[y],h.type!==s["default"]&&i.raiseError("Expecting MUITab React Element"),b=y===u,n.push(l["default"].createElement("li",{key:y,className:b?f:""},l["default"].createElement("a",{onClick:this.onClick.bind(this,y,h)},h.props.label))),v=d+" ",b&&(v+=f),o.push(l["default"].createElement("div",{key:y,className:v},h.props.children));return v=c,this.props.justified&&(v+=" "+p),l["default"].createElement("div",r,l["default"].createElement("ul",{className:v},n),o)}}]),t}(l["default"].Component);b.propTypes={initialSelectedIndex:u.number,justified:u.bool,onChange:u.func},b.defaultProps={className:"",initialSelectedIndex:0,justified:!1,onChange:null},r["default"]=b,t.exports=r["default"]},{"../js/lib/util":5,"./tab":9,react:"CwoHg3"}],29:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./text-field"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={rows:s.number},a.defaultProps={type:"textarea",rows:2},r["default"]=a,t.exports=r["default"]},{"./text-field":10,react:"CwoHg3"}]},{},[1]); |
src/components/app.js | schesnowitz/react-redux | import React, { Component } from 'react';
import BookList from '../containers/book-list';
export default class App extends Component {
render() {
return (
<div>
<BookList />
</div>
);
}
}
|
src/svg-icons/action/perm-device-information.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermDeviceInformation = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
ActionPermDeviceInformation = pure(ActionPermDeviceInformation);
ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation';
ActionPermDeviceInformation.muiName = 'SvgIcon';
export default ActionPermDeviceInformation;
|
docs/src/pages/components/app-bar/SearchAppBar.js | allanalexandre/material-ui | import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import { fade } from '@material-ui/core/styles/colorManipulator';
import { makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: '100%',
[theme.breakpoints.up('sm')]: {
marginLeft: theme.spacing(1),
width: 'auto',
},
},
searchIcon: {
width: theme.spacing(7),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
inputRoot: {
color: 'inherit',
},
inputInput: {
padding: theme.spacing(1, 1, 1, 7),
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 120,
'&:focus': {
width: 200,
},
},
},
}));
function SearchAppBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="Open drawer"
>
<MenuIcon />
</IconButton>
<Typography className={classes.title} variant="h6" noWrap>
Material-UI
</Typography>
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
/>
</div>
</Toolbar>
</AppBar>
</div>
);
}
export default SearchAppBar;
|
data-browser-ui/public/app/components/tableComponents/td/relationComponents/geopoint.js | CloudBoost/cloudboost | import React from 'react';
import ReactDOM from 'react-dom';
import Dialog from 'material-ui/Dialog';
import TextField from 'material-ui/TextField';
class GeoPoint extends React.Component {
constructor(){
super()
this.state = {
isModalOpen:false
}
}
componentDidMount(){
}
openCloseModal(what){
this.state.isModalOpen = what
this.setState(this.state)
}
changeHandler(which,e){
let location
if(which == 'longitude'){
if(this.props.elementData){
location = new CB.CloudGeoPoint(e.target.value,( this.props.elementData.document.latitude || 0));
} else {
location = new CB.CloudGeoPoint(e.target.value,0);
}
} else {
if(this.props.elementData){
location = new CB.CloudGeoPoint((this.props.elementData.document.longitude || 0),e.target.value);
} else {
location = new CB.CloudGeoPoint(0,e.target.value);
}
}
this.props.updateElementData(location,this.props.columnData.name)
}
cancelGeoUpdate(){
this.openCloseModal(false)
}
handleClose(){
}
render() {
let data = {}
data.lat = this.props.elementData ? (this.props.elementData.latitude || 0) : 0
data.long = this.props.elementData ? (this.props.elementData.longitude || 0) : 0
return (
<div className="halfreldiv ">
<span className="textnamerlation"> { this.props.columnData.name } </span>
<span className="color888 spanrelcustom">{ JSON.stringify(data) }</span>
<i className="fa fa-expand fr filerle cp" aria-hidden="true" onClick={this.openCloseModal.bind(this,true)}></i>
<Dialog title="Geo Location EDITOR" modal={false} open={this.state.isModalOpen} onRequestClose={this.handleClose.bind(this)} titleClassName="modaltitle">
<TextField
hintText="Latitude"
floatingLabelText="Enter a Latitude"
value={
this.props.elementData ? (this.props.elementData.document.latitude || '') : ''
}
onChange={this.changeHandler.bind(this,'latitude')}
type="number"
/>
<TextField
hintText="Longitude"
floatingLabelText="Enter a Longitude"
value={
this.props.elementData ? (this.props.elementData.document.longitude || '') : ''
}
onChange={this.changeHandler.bind(this,'longitude')}
type="number"
/>
<button className="btn btn-danger fr" onClick={this.cancelGeoUpdate.bind(this)}>Done</button>
</Dialog>
</div>
);
}
}
export default GeoPoint; |
app/components/SideTree/SideTreeInner.js | youtogod/webpack-sample-project | import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
class SideTreeInner extends Component {
constructor(props) {
super(props);
console.log('new comp');
}
componentDidMount() {}
render() {
const {directory, location} = this.props;
const isActived = location.pathname === directory.path;
const {isDirectory, isLast, isOpened, type, isRoot, path, name, subDirectories} = directory;
const innerStyle = {
paddingRight: isDirectory ? '29px' : '10px',
marginBottom: isLast || isRoot && ((!isDirectory) || !isOpened) ? '0' : '15px',
color: isActived ? '#01a982' : '#7b7b7b'
}
const linkStyle = {
fontWeight: isRoot ? '500' : '400'
}
return (
<div className="side-tree-inner" style={innerStyle}>
{isDirectory ?
<span className={'side-tree-unfold ' + (isOpened ? 'glyphicon glyphicon-chevron-down' : 'glyphicon glyphicon-chevron-right')} onClick={this.props.toggleIsOpened}></span> :
<span className="side-tree-unfold-space"></span>
}
{isActived ?
<span className="side-tree-directory-type-open">{type}</span>
:
<span className="side-tree-directory-type-close">{type.charAt(0)}</span>
}
<NavLink exact className={'side-tree-directory' + (isActived ? '-actived' : '')} style={linkStyle} to={path}>
{name}
</NavLink>
{isDirectory && <div className={'side-tree-directory-number' + (isActived ? '-actived' : '')}>{(subDirectories || []).length}</div>}
</div>
);
}
}
export default SideTreeInner |
node_modules/react-native/local-cli/generator/templates/index.android.js | leechuanjun/TLReactNativeProject | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class <%= name %> extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
|
ajax/libs/mediaelement/2.14.2/jquery.js | thisispiers/cdnjs | /*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}
this.each(function() {
jQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return jQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = jQuery.isFunction( value );
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !isFunc && typeof value !== "string" ) {
value = jQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 ) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/*jshint validthis:true */
var prop, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.cur && hooks.cur.finish ) {
hooks.cur.finish.call( this );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.documentElement;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window ); |
packages/wix-style-react/src/InputWithLabel/test/InputWithLabel.spec.js | wix/wix-style-react | import React from 'react';
import ChevronDown from 'wix-ui-icons-common/ChevronDown';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import InputWithLabel from '../InputWithLabel';
import { inputWithLabelPrivateDriverFactory } from './InputWithLabel.private.uni.driver';
import dataHooks from '../../LabelledElement/dataHooks';
import Input from '../../Input';
describe('InputWithLabel', () => {
const render = createRendererWithUniDriver(
inputWithLabelPrivateDriverFactory,
);
afterEach(() => {
cleanup();
});
it('should render with value', async () => {
const value = 'my value';
const { driver } = render(<InputWithLabel value={value} />);
const currentValue = await driver.getValue();
expect(currentValue).toEqual(value);
});
it('should render without value', async () => {
const { driver } = render(<InputWithLabel />);
const currentValue = await driver.getValue();
expect(currentValue).toBeFalsy();
});
it('should render a label', async () => {
const label = 'my label';
const { driver } = render(
<InputWithLabel dataHook={dataHooks.labelledElement} label={label} />,
);
const currentLabel = await driver.getLabelText();
expect(currentLabel).toEqual(label);
});
it('should render no icons', async () => {
const { driver } = render(<InputWithLabel />);
expect(await driver.getSuffixesCount()).toEqual(0);
});
it('should render a single icon', async () => {
const icon = [<ChevronDown />];
const { driver } = render(<InputWithLabel suffix={icon} />);
expect(await driver.getSuffixesCount()).toEqual(1);
});
it('should render two icons', async () => {
const icons = [<ChevronDown />, <ChevronDown />];
const { driver } = render(<InputWithLabel suffix={icons} />);
expect(await driver.getSuffixesCount()).toEqual(2);
});
it('should render an error message', async () => {
const { driver } = render(
<InputWithLabel status={Input.StatusError} statusMessage="a message" />,
);
expect(await driver.getErrorMessage()).toEqual('a message');
});
it('should not render a message without a status', async () => {
const { driver } = render(<InputWithLabel statusMessage="a message" />);
expect(await driver.hasErrorMessage()).toEqual(false);
});
it('should trigger onChange if provided', async () => {
const onChange = jest.fn();
const { driver } = render(
<InputWithLabel label="my autocomplete" onChange={onChange} />,
);
await driver.enterText('a');
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
target: expect.objectContaining({ value: 'a' }),
}),
);
});
it('should render Input with customInput', async () => {
const customInputWithRef = React.forwardRef((props, ref) => (
<input {...props} ref={ref} maxLength={3} />
));
const { driver } = render(
<InputWithLabel customInput={customInputWithRef} />,
);
expect(await driver.isCustomInput()).toEqual(true);
});
});
|
src/Lookup.js | OCMC-Translation-Projects/ioc-liturgical-react | import React from 'react';
import PropTypes from 'prop-types';
import server from "./helpers/Server";
let cellStyle = {
padding: '2em'
};
class Lookup extends React.Component {
constructor(props) {
super(props);
this.state = {
dataLoaded: false
, value: ""
};
this.fetchData = this.fetchData.bind(this);
this.handleRestCallback = this.handleRestCallback.bind(this);
this.getContent = this.getContent.bind(this);
};
componentDidMount = () => {
this.fetchData();
};
componentWillReceiveProps = (nextProps) => {
};
// if we need to do something after setState, do it here...
handleStateChange = (parm) => {
// call a function if needed
};
handleRestCallback = (restCallResult) => {
if (restCallResult && restCallResult.data) {
console.log(restCallResult);
let value = restCallResult.data.values[0].value;
this.setState({
dataLoaded: true
, data: value
});
}
};
fetchData() {
console.log("fetching data");
server.getLookupResult(
this.props.session.restServer
, this.props.idDomain
, this.props.idTopic
, this.props.idKey
, this.handleRestCallback
)
}
getContent = () => {
if (this.state.dataLoaded) {
return (
<div className="App-New-Component-Template">
<table>
<tbody>
<tr>
<td style={cellStyle}>{this.props.idDomain}~{this.props.idTopic}~{this.props.idKey}</td> <td style={cellStyle}>{this.state.data}</td>
</tr>
</tbody>
</table>
</div>
)
} else {
if (this.props && this.props.idDomain) {
return (
<div className="App-New-Component-Template">
<table>
<tbody>
<tr>
<td style={cellStyle}>{this.props.idDomain}~{this.props.idTopic}~{this.props.idKey}</td> <td style={cellStyle}> </td>
</tr>
</tbody>
</table>
</div>
)
} else {
return (
<div className="App-New-Component-Template">
</div>
)
}
}
};
render() {
return (
<div>
{this.getContent()}
</div>
)
}
};
Lookup.propTypes = {
session: PropTypes.object.isRequired
, idDomain: PropTypes.string
, idTopic: PropTypes.string.isRequired
, idKey: PropTypes.string
};
// set default values for props here
Lookup.defaultProps = {
};
export default Lookup;
|
examples/Pagination.js | chris-gooley/react-materialize | import React from 'react';
import Pagination from '../src/Pagination';
export default <Pagination items={10} activePage={2} maxButtons={8} />;
|
ajax/libs/cellx/1.6.73/cellx.js | menuka94/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.cellx = factory());
}(this, (function () { 'use strict';
var ErrorLogger = {
_handler: null,
/**
* @typesign (handler: (...msg));
*/
setHandler: function setHandler(handler) {
this._handler = handler;
},
/**
* @typesign (...msg);
*/
log: function log() {
this._handler.apply(this, arguments);
}
};
var uidCounter = 0;
/**
* @typesign () -> string;
*/
function nextUID() {
return String(++uidCounter);
}
var Symbol = Function('return this;')().Symbol;
if (!Symbol) {
Symbol = function Symbol(key) {
return '__' + key + '_' + Math.floor(Math.random() * 1e9) + '_' + nextUID() + '__';
};
Symbol.iterator = Symbol('Symbol.iterator');
}
var Symbol$1 = Symbol;
var UID = Symbol$1('cellx.uid');
var CELLS = Symbol$1('cellx.cells');
var global$1 = Function('return this;')();
/**
* @typesign (a, b) -> boolean;
*/
var is = Object.is || function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a == 1 / b;
}
return a === b || (a != a && b != b);
};
var hasOwn = Object.prototype.hasOwnProperty;
/**
* @typesign (target: Object, source: Object) -> Object;
*/
function mixin(target, source) {
var names = Object.getOwnPropertyNames(source);
for (var i = 0, l = names.length; i < l; i++) {
var name = names[i];
Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(source, name));
}
return target;
}
var extend;
/**
* @typesign (description: {
* Extends?: Function,
* Implements?: Array<Object|Function>,
* Static?: Object,
* constructor?: Function,
* [key: string]
* }) -> Function;
*/
function createClass(description) {
var parent;
if (description.Extends) {
parent = description.Extends;
delete description.Extends;
} else {
parent = Object;
}
var constr;
if (hasOwn.call(description, 'constructor')) {
constr = description.constructor;
delete description.constructor;
} else {
constr = parent == Object ?
function() {} :
function() {
return parent.apply(this, arguments);
};
}
var proto = constr.prototype = Object.create(parent.prototype);
if (description.Implements) {
description.Implements.forEach((function(implementation) {
if (typeof implementation == 'function') {
Object.keys(implementation).forEach((function(name) {
Object.defineProperty(constr, name, Object.getOwnPropertyDescriptor(implementation, name));
}));
mixin(proto, implementation.prototype);
} else {
mixin(proto, implementation);
}
}));
delete description.Implements;
}
Object.keys(parent).forEach((function(name) {
Object.defineProperty(constr, name, Object.getOwnPropertyDescriptor(parent, name));
}));
if (description.Static) {
mixin(constr, description.Static);
delete description.Static;
}
if (constr.extend === void 0) {
constr.extend = extend;
}
mixin(proto, description);
Object.defineProperty(proto, 'constructor', {
configurable: true,
writable: true,
value: constr
});
return constr;
}
/**
* @this {Function}
*
* @typesign (description: {
* Implements?: Array<Object|Function>,
* Static?: Object,
* constructor?: Function,
* [key: string]
* }) -> Function;
*/
extend = function extend(description) {
description.Extends = this;
return createClass(description);
};
var Map = global$1.Map;
if (!Map) {
var entryStub = {
value: void 0
};
Map = createClass({
constructor: function Map(entries) {
this._entries = Object.create(null);
this._objectStamps = {};
this._first = null;
this._last = null;
this.size = 0;
if (entries) {
for (var i = 0, l = entries.length; i < l; i++) {
this.set(entries[i][0], entries[i][1]);
}
}
},
has: function has(key) {
return !!this._entries[this._getValueStamp(key)];
},
get: function get(key) {
return (this._entries[this._getValueStamp(key)] || entryStub).value;
},
set: function set(key, value) {
var entries = this._entries;
var keyStamp = this._getValueStamp(key);
if (entries[keyStamp]) {
entries[keyStamp].value = value;
} else {
var entry = entries[keyStamp] = {
key: key,
keyStamp: keyStamp,
value: value,
prev: this._last,
next: null
};
if (this.size++) {
this._last.next = entry;
} else {
this._first = entry;
}
this._last = entry;
}
return this;
},
delete: function delete_(key) {
var keyStamp = this._getValueStamp(key);
var entry = this._entries[keyStamp];
if (!entry) {
return false;
}
if (--this.size) {
var prev = entry.prev;
var next = entry.next;
if (prev) {
prev.next = next;
} else {
this._first = next;
}
if (next) {
next.prev = prev;
} else {
this._last = prev;
}
} else {
this._first = null;
this._last = null;
}
delete this._entries[keyStamp];
delete this._objectStamps[keyStamp];
return true;
},
clear: function clear() {
var entries = this._entries;
for (var stamp in entries) {
delete entries[stamp];
}
this._objectStamps = {};
this._first = null;
this._last = null;
this.size = 0;
},
_getValueStamp: function _getValueStamp(value) {
switch (typeof value) {
case 'undefined': {
return 'undefined';
}
case 'object': {
if (value === null) {
return 'null';
}
break;
}
case 'boolean': {
return '?' + value;
}
case 'number': {
return '+' + value;
}
case 'string': {
return ',' + value;
}
}
return this._getObjectStamp(value);
},
_getObjectStamp: function _getObjectStamp(obj) {
if (!hasOwn.call(obj, UID)) {
if (!Object.isExtensible(obj)) {
var stamps = this._objectStamps;
var stamp;
for (stamp in stamps) {
if (hasOwn.call(stamps, stamp) && stamps[stamp] == obj) {
return stamp;
}
}
stamp = nextUID();
stamps[stamp] = obj;
return stamp;
}
Object.defineProperty(obj, UID, {
value: nextUID()
});
}
return obj[UID];
},
forEach: function forEach(cb, context) {
var entry = this._first;
while (entry) {
cb.call(context, entry.value, entry.key, this);
do {
entry = entry.next;
} while (entry && !this._entries[entry.keyStamp]);
}
},
toString: function toString() {
return '[object Map]';
}
});
[
['keys', function keys(entry) {
return entry.key;
}],
['values', function values(entry) {
return entry.value;
}],
['entries', function entries(entry) {
return [entry.key, entry.value];
}]
].forEach((function(settings) {
var getStepValue = settings[1];
Map.prototype[settings[0]] = function() {
var entries = this._entries;
var entry;
var done = false;
var map = this;
return {
next: function() {
if (!done) {
if (entry) {
do {
entry = entry.next;
} while (entry && !entries[entry.keyStamp]);
} else {
entry = map._first;
}
if (entry) {
return {
value: getStepValue(entry),
done: false
};
}
done = true;
}
return {
value: void 0,
done: true
};
}
};
};
}));
}
if (!Map.prototype[Symbol$1.iterator]) {
Map.prototype[Symbol$1.iterator] = Map.prototype.entries;
}
var Map$1 = Map;
var KEY_IS_EMITTER_EVENT = Symbol$1('cellx.EventEmitter~isEmitterEvent');
var KEY_INNER = Symbol$1('cellx.EventEmitter.inner');
/**
* @typedef {{
* target?: Object,
* type: string,
* bubbles?: boolean,
* isPropagationStopped?: boolean
* }} cellx~Event
*/
/**
* @class cellx.EventEmitter
* @extends {Object}
* @typesign new EventEmitter() -> cellx.EventEmitter;
*/
var EventEmitter = createClass({
Static: {
KEY_INNER: KEY_INNER
},
constructor: function EventEmitter() {
/**
* @type {Object<Array<{
* listener: (evt: cellx~Event) -> ?boolean,
* context
* }>>}
*/
this._events = new Map$1();
},
/**
* @typesign (type?: string) -> Array<{ listener: (evt: cellx~Event) -> ?boolean, context }> |
* Object<Array<{ listener: (evt: cellx~Event) -> ?boolean, context }>>;
*/
getEvents: function getEvents(type) {
if (type) {
var events = this._events && this._events.get(type);
if (!events) {
return [];
}
return events._isEmitterEvent === KEY_IS_EMITTER_EVENT ? [events] : events;
}
var resultEvents = Object.create(null);
this._events.forEach((function(events, type) {
resultEvents[type] = events._isEmitterEvent === KEY_IS_EMITTER_EVENT ? [events] : events;
}));
return resultEvents;
},
/**
* @typesign (
* type: string,
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.EventEmitter;
*
* @typesign (
* listeners: Object<(evt: cellx~Event) -> ?boolean>,
* context?
* ) -> cellx.EventEmitter;
*/
on: function on(type, listener, context) {
if (typeof type == 'object') {
context = arguments.length >= 2 ? listener : this;
var listeners = type;
for (type in listeners) {
this._on(type, listeners[type], context);
}
} else {
this._on(type, listener, arguments.length >= 3 ? context : this);
}
return this;
},
/**
* @typesign (
* type: string,
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.EventEmitter;
*
* @typesign (
* listeners: Object<(evt: cellx~Event) -> ?boolean>,
* context?
* ) -> cellx.EventEmitter;
*
* @typesign () -> cellx.EventEmitter;
*/
off: function off(type, listener, context) {
var argCount = arguments.length;
if (argCount) {
if (typeof type == 'object') {
context = argCount >= 2 ? listener : this;
var listeners = type;
for (type in listeners) {
this._off(type, listeners[type], context);
}
} else {
this._off(type, listener, argCount >= 3 ? context : this);
}
} else if (this._events) {
this._events.clear();
}
return this;
},
/**
* @typesign (
* type: string,
* listener: (evt: cellx~Event) -> ?boolean,
* context
* );
*/
_on: function _on(type, listener, context) {
var index = type.indexOf(':');
if (index != -1) {
this['_' + type.slice(index + 1)].on(type.slice(0, index), listener, context);
} else {
var events = (this._events || (this._events = new Map$1())).get(type);
var evt = {
_isEmitterEvent: KEY_IS_EMITTER_EVENT,
listener: listener,
context: context
};
if (!events) {
this._events.set(type, evt);
} else if (events._isEmitterEvent === KEY_IS_EMITTER_EVENT) {
this._events.set(type, [events, evt]);
} else {
events.push(evt);
}
}
},
/**
* @typesign (
* type: string,
* listener: (evt: cellx~Event) -> ?boolean,
* context
* );
*/
_off: function _off(type, listener, context) {
var index = type.indexOf(':');
if (index != -1) {
this['_' + type.slice(index + 1)].off(type.slice(0, index), listener, context);
} else {
var events = this._events && this._events.get(type);
if (!events) {
return;
}
if (events._isEmitterEvent === KEY_IS_EMITTER_EVENT) {
if (
(events.listener == listener || events.listener[KEY_INNER] === listener) &&
events.context === context
) {
this._events.delete(type);
}
} else {
var eventCount = events.length;
if (eventCount == 1) {
var evt = events[0];
if ((evt.listener == listener || evt.listener[KEY_INNER] === listener) && evt.context === context) {
this._events.delete(type);
}
} else {
for (var i = eventCount; i;) {
var evt2 = events[--i];
if (
(evt2.listener == listener || evt2.listener[KEY_INNER] === listener) &&
evt2.context === context
) {
events.splice(i, 1);
break;
}
}
}
}
}
},
/**
* @typesign (
* type: string,
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.EventEmitter;
*/
once: function once(type, listener, context) {
if (arguments.length < 3) {
context = this;
}
function wrapper() {
this._off(type, wrapper, context);
return listener.apply(this, arguments);
}
wrapper[KEY_INNER] = listener;
this._on(type, wrapper, context);
return this;
},
/**
* @typesign (evt: cellx~Event) -> cellx~Event;
* @typesign (type: string) -> cellx~Event;
*/
emit: function emit(evt) {
if (typeof evt == 'string') {
evt = {
target: this,
type: evt
};
} else if (!evt.target) {
evt.target = this;
} else if (evt.target != this) {
throw new TypeError('Event cannot be emitted on this object');
}
this._handleEvent(evt);
return evt;
},
/**
* @typesign (evt: cellx~Event);
*
* For override:
* @example
* function View(el) {
* this.element = el;
* el._view = this;
* }
*
* View.prototype = Object.create(EventEmitter.prototype);
* View.prototype.constructor = View;
*
* View.prototype.getParent = function() {
* var node = this.element;
*
* while (node = node.parentNode) {
* if (node._view) {
* return node._view;
* }
* }
*
* return null;
* };
*
* View.prototype._handleEvent = function(evt) {
* EventEmitter.prototype._handleEvent.call(this, evt);
*
* if (evt.bubbles !== false && !evt.isPropagationStopped) {
* var parent = this.getParent();
*
* if (parent) {
* parent._handleEvent(evt);
* }
* }
* };
*/
_handleEvent: function _handleEvent(evt) {
var events = this._events && this._events.get(evt.type);
if (!events) {
return;
}
if (events._isEmitterEvent === KEY_IS_EMITTER_EVENT) {
if (this._tryEventListener(events, evt) === false) {
evt.isPropagationStopped = true;
}
} else {
var eventCount = events.length;
if (eventCount == 1) {
if (this._tryEventListener(events[0], evt) === false) {
evt.isPropagationStopped = true;
}
} else {
events = events.slice();
for (var i = 0; i < eventCount; i++) {
if (this._tryEventListener(events[i], evt) === false) {
evt.isPropagationStopped = true;
}
}
}
}
},
_tryEventListener: function _tryEventListener(emEvt, evt) {
try {
return emEvt.listener.call(emEvt.context, evt);
} catch (err) {
this._logError(err);
}
},
/**
* @typesign (...msg);
*/
_logError: function _logError() {
ErrorLogger.log.apply(ErrorLogger, arguments);
}
});
var ObservableCollectionMixin = EventEmitter.extend({
constructor: function ObservableCollectionMixin() {
/**
* @type {Map<*, uint>}
*/
this._valueCounts = new Map$1();
},
/**
* @typesign (evt: cellx~Event);
*/
_onItemChange: function _onItemChange(evt) {
this._handleEvent(evt);
},
/**
* @typesign (value);
*/
_registerValue: function _registerValue(value) {
var valueCounts = this._valueCounts;
var valueCount = valueCounts.get(value);
if (valueCount) {
valueCounts.set(value, valueCount + 1);
} else {
valueCounts.set(value, 1);
if (this.adoptsValueChanges && value instanceof EventEmitter) {
value.on('change', this._onItemChange, this);
}
}
},
/**
* @typesign (value);
*/
_unregisterValue: function _unregisterValue(value) {
var valueCounts = this._valueCounts;
var valueCount = valueCounts.get(value);
if (valueCount > 1) {
valueCounts.set(value, valueCount - 1);
} else {
valueCounts.delete(value);
if (this.adoptsValueChanges && value instanceof EventEmitter) {
value.off('change', this._onItemChange, this);
}
}
}
});
/**
* @class cellx.ObservableMap
* @extends {cellx.EventEmitter}
* @implements {cellx.ObservableCollectionMixin}
*
* @typesign new ObservableMap(entries?: Object|cellx.ObservableMap|Map|Array<{ 0, 1 }>, opts?: {
* adoptsValueChanges?: boolean
* }) -> cellx.ObservableMap;
*/
var ObservableMap = EventEmitter.extend({
Implements: [ObservableCollectionMixin],
constructor: function ObservableMap(entries, opts) {
EventEmitter.call(this);
ObservableCollectionMixin.call(this);
this._entries = new Map$1();
this.size = 0;
/**
* @type {boolean}
*/
this.adoptsValueChanges = !!(opts && opts.adoptsValueChanges);
if (entries) {
var mapEntries = this._entries;
if (entries instanceof ObservableMap || entries instanceof Map$1) {
entries._entries.forEach((function(value, key) {
this._registerValue(value);
mapEntries.set(key, value);
}), this);
} else if (Array.isArray(entries)) {
for (var i = 0, l = entries.length; i < l; i++) {
var entry = entries[i];
this._registerValue(entry[1]);
mapEntries.set(entry[0], entry[1]);
}
} else {
for (var key in entries) {
this._registerValue(entries[key]);
mapEntries.set(key, entries[key]);
}
}
this.size = mapEntries.size;
}
},
/**
* @typesign (key) -> boolean;
*/
has: function has(key) {
return this._entries.has(key);
},
/**
* @typesign (value) -> boolean;
*/
contains: function contains(value) {
return this._valueCounts.has(value);
},
/**
* @typesign (key) -> *;
*/
get: function get(key) {
return this._entries.get(key);
},
/**
* @typesign (key, value) -> cellx.ObservableMap;
*/
set: function set(key, value) {
var entries = this._entries;
var hasKey = entries.has(key);
var oldValue;
if (hasKey) {
oldValue = entries.get(key);
if (is(value, oldValue)) {
return this;
}
this._unregisterValue(oldValue);
}
this._registerValue(value);
entries.set(key, value);
if (!hasKey) {
this.size++;
}
this.emit({
type: 'change',
subtype: hasKey ? 'update' : 'add',
key: key,
oldValue: oldValue,
value: value
});
return this;
},
/**
* @typesign (key) -> boolean;
*/
delete: function delete_(key) {
var entries = this._entries;
if (!entries.has(key)) {
return false;
}
var value = entries.get(key);
this._unregisterValue(value);
entries.delete(key);
this.size--;
this.emit({
type: 'change',
subtype: 'delete',
key: key,
oldValue: value,
value: void 0
});
return true;
},
/**
* @typesign () -> cellx.ObservableMap;
*/
clear: function clear() {
if (!this.size) {
return this;
}
if (this.adoptsValueChanges) {
this._valueCounts.forEach((function(value) {
if (value instanceof EventEmitter) {
value.off('change', this._onItemChange, this);
}
}), this);
}
this._entries.clear();
this._valueCounts.clear();
this.size = 0;
this.emit({
type: 'change',
subtype: 'clear'
});
return this;
},
/**
* @typesign (
* cb: (value, key, map: cellx.ObservableMap),
* context?
* );
*/
forEach: function forEach(cb, context) {
this._entries.forEach((function(value, key) {
cb.call(context, value, key, this);
}), this);
},
/**
* @typesign () -> { next: () -> { value, done: boolean } };
*/
keys: function keys() {
return this._entries.keys();
},
/**
* @typesign () -> { next: () -> { value, done: boolean } };
*/
values: function values() {
return this._entries.values();
},
/**
* @typesign () -> { next: () -> { value: { 0, 1 }, done: boolean } };
*/
entries: function entries() {
return this._entries.entries();
},
/**
* @typesign () -> cellx.ObservableMap;
*/
clone: function clone() {
return new this.constructor(this, {
adoptsValueChanges: this.adoptsValueChanges
});
}
});
ObservableMap.prototype[Symbol$1.iterator] = ObservableMap.prototype.entries;
var slice = Array.prototype.slice;
var push$1 = Array.prototype.push;
var splice = Array.prototype.splice;
var map$1 = Array.prototype.map;
/**
* @typesign (a, b) -> -1|1|0;
*/
function defaultComparator(a, b) {
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
}
/**
* @class cellx.ObservableList
* @extends {cellx.EventEmitter}
* @implements {cellx.ObservableCollectionMixin}
*
* @typesign new ObservableList(items?: Array|cellx.ObservableList, opts?: {
* adoptsValueChanges?: boolean,
* comparator?: (a, b) -> int,
* sorted?: boolean
* }) -> cellx.ObservableList;
*/
var ObservableList = EventEmitter.extend({
Implements: [ObservableCollectionMixin],
constructor: function ObservableList(items, opts) {
EventEmitter.call(this);
ObservableCollectionMixin.call(this);
if (!opts) {
opts = {};
}
this._items = [];
this.length = 0;
/**
* @type {boolean}
*/
this.adoptsValueChanges = !!opts.adoptsValueChanges;
/**
* @type {?(a, b) -> int}
*/
this.comparator = null;
this.sorted = false;
if (opts.sorted || (opts.comparator && opts.sorted !== false)) {
this.comparator = opts.comparator || defaultComparator;
this.sorted = true;
}
if (items) {
this._addRange(items);
}
},
/**
* @typesign (index: ?int, allowedEndIndex?: boolean) -> ?uint;
*/
_validateIndex: function _validateIndex(index, allowedEndIndex) {
if (index === void 0) {
return index;
}
if (index < 0) {
index += this.length;
if (index < 0) {
throw new RangeError('Index out of valid range');
}
} else if (index >= (this.length + (allowedEndIndex ? 1 : 0))) {
throw new RangeError('Index out of valid range');
}
return index;
},
/**
* @typesign (value) -> boolean;
*/
contains: function contains(value) {
return this._valueCounts.has(value);
},
/**
* @typesign (value, fromIndex?: int) -> int;
*/
indexOf: function indexOf(value, fromIndex) {
return this._items.indexOf(value, this._validateIndex(fromIndex));
},
/**
* @typesign (value, fromIndex?: int) -> int;
*/
lastIndexOf: function lastIndexOf(value, fromIndex) {
return this._items.lastIndexOf(value, fromIndex === void 0 ? -1 : this._validateIndex(fromIndex));
},
/**
* @typesign (index: int) -> *;
*/
get: function get(index) {
return this._items[this._validateIndex(index, true)];
},
/**
* @typesign (index: int, count?: uint) -> Array;
*/
getRange: function getRange(index, count) {
index = this._validateIndex(index, true);
var items = this._items;
if (count === void 0) {
return items.slice(index);
}
if (index + count > items.length) {
throw new RangeError('Sum of "index" and "count" out of valid range');
}
return items.slice(index, index + count);
},
/**
* @typesign (index: int, value) -> cellx.ObservableList;
*/
set: function set(index, value) {
if (this.sorted) {
throw new TypeError('Cannot set to sorted list');
}
index = this._validateIndex(index);
var items = this._items;
if (is(value, items[index])) {
return this;
}
this._unregisterValue(items[index]);
this._registerValue(value);
items[index] = value;
this.emit('change');
return this;
},
/**
* @typesign (index: int, values: Array|cellx.ObservableList) -> cellx.ObservableList;
*/
setRange: function setRange(index, values) {
if (this.sorted) {
throw new TypeError('Cannot set to sorted list');
}
index = this._validateIndex(index);
if (values instanceof ObservableList) {
values = values._items;
}
var valueCount = values.length;
if (!valueCount) {
return this;
}
if (index + valueCount > this.length) {
throw new RangeError('Sum of "index" and "values.length" out of valid range');
}
var items = this._items;
var changed = false;
for (var i = index + valueCount; i > index;) {
var value = values[--i - index];
if (!is(value, items[i])) {
this._unregisterValue(items[i]);
this._registerValue(value);
items[i] = value;
changed = true;
}
}
if (changed) {
this.emit('change');
}
return this;
},
/**
* @typesign (value) -> cellx.ObservableList;
*/
add: function add(value) {
if (this.sorted) {
this._insertValue(value);
} else {
this._registerValue(value);
this._items.push(value);
}
this.length++;
this.emit('change');
return this;
},
/**
* @typesign (values: Array|cellx.ObservableList) -> cellx.ObservableList;
*/
addRange: function addRange(values) {
if (values.length) {
this._addRange(values);
this.emit('change');
}
return this;
},
/**
* @typesign (values: Array|cellx.ObservableList);
*/
_addRange: function _addRange(values) {
if (values instanceof ObservableList) {
values = values._items;
}
if (this.sorted) {
for (var i = 0, l = values.length; i < l; i++) {
this._insertValue(values[i]);
}
this.length += values.length;
} else {
for (var j = values.length; j;) {
this._registerValue(values[--j]);
}
this.length = push$1.apply(this._items, values);
}
},
/**
* @typesign (value);
*/
_insertValue: function _insertValue(value) {
this._registerValue(value);
var items = this._items;
var comparator = this.comparator;
var low = 0;
var high = items.length;
while (low != high) {
var mid = (low + high) >> 1;
if (comparator(value, items[mid]) < 0) {
high = mid;
} else {
low = mid + 1;
}
}
items.splice(low, 0, value);
},
/**
* @typesign (index: int, value) -> cellx.ObservableList;
*/
insert: function insert(index, value) {
if (this.sorted) {
throw new TypeError('Cannot insert to sorted list');
}
index = this._validateIndex(index, true);
this._registerValue(value);
this._items.splice(index, 0, value);
this.length++;
this.emit('change');
return this;
},
/**
* @typesign (index: int, values: Array|cellx.ObservableList) -> cellx.ObservableList;
*/
insertRange: function insertRange(index, values) {
if (this.sorted) {
throw new TypeError('Cannot insert to sorted list');
}
index = this._validateIndex(index, true);
if (values instanceof ObservableList) {
values = values._items;
}
var valueCount = values.length;
if (!valueCount) {
return this;
}
for (var i = valueCount; i;) {
this._registerValue(values[--i]);
}
splice.apply(this._items, [index, 0].concat(values));
this.length += valueCount;
this.emit('change');
return this;
},
/**
* @typesign (value, fromIndex?: int) -> boolean;
*/
remove: function remove(value, fromIndex) {
var index = this._items.indexOf(value, this._validateIndex(fromIndex));
if (index == -1) {
return false;
}
this._unregisterValue(value);
this._items.splice(index, 1);
this.length--;
this.emit('change');
return true;
},
/**
* @typesign (value, fromIndex?: int) -> boolean;
*/
removeAll: function removeAll(value, fromIndex) {
var index = this._validateIndex(fromIndex);
var items = this._items;
var changed = false;
while ((index = items.indexOf(value, index)) != -1) {
this._unregisterValue(value);
items.splice(index, 1);
changed = true;
}
if (changed) {
this.length = items.length;
this.emit('change');
}
return changed;
},
/**
* @typesign (values: Array|cellx.ObservableList, fromIndex?: int) -> boolean;
*/
removeEach: function removeEach(values, fromIndex) {
fromIndex = this._validateIndex(fromIndex);
if (values instanceof ObservableList) {
values = values._items;
}
var items = this._items;
var changed = false;
for (var i = 0, l = values.length; i < l; i++) {
var value = values[i];
var index = items.indexOf(value, fromIndex);
if (index != -1) {
this._unregisterValue(value);
items.splice(index, 1);
changed = true;
}
}
if (changed) {
this.length = items.length;
this.emit('change');
}
return changed;
},
/**
* @typesign (values: Array|cellx.ObservableList, fromIndex?: int) -> boolean;
*/
removeAllEach: function removeAllEach(values, fromIndex) {
fromIndex = this._validateIndex(fromIndex);
if (values instanceof ObservableList) {
values = values._items;
}
var items = this._items;
var changed = false;
for (var i = 0, l = values.length; i < l; i++) {
var value = values[i];
for (var index = fromIndex; (index = items.indexOf(value, index)) != -1;) {
this._unregisterValue(value);
items.splice(index, 1);
changed = true;
}
}
if (changed) {
this.length = items.length;
this.emit('change');
}
return changed;
},
/**
* @typesign (index: int) -> *;
*/
removeAt: function removeAt(index) {
var value = this._items.splice(this._validateIndex(index), 1)[0];
this._unregisterValue(value);
this.length--;
this.emit('change');
return value;
},
/**
* @typesign (index: int, count?: uint) -> Array;
*/
removeRange: function removeRange(index, count) {
index = this._validateIndex(index, true);
var items = this._items;
if (count === void 0) {
count = items.length - index;
} else if (index + count > items.length) {
throw new RangeError('Sum of "index" and "count" out of valid range');
}
if (!count) {
return [];
}
for (var i = index + count; i > index;) {
this._unregisterValue(items[--i]);
}
var values = items.splice(index, count);
this.length -= count;
this.emit('change');
return values;
},
/**
* @typesign () -> cellx.ObservableList;
*/
clear: function clear() {
if (!this.length) {
return this;
}
if (this.adoptsValueChanges) {
this._valueCounts.forEach((function(value) {
if (value instanceof EventEmitter) {
value.off('change', this._onItemChange, this);
}
}), this);
}
this._items.length = 0;
this._valueCounts.clear();
this.length = 0;
this.emit({
type: 'change',
subtype: 'clear'
});
return this;
},
/**
* @typesign (separator?: string) -> string;
*/
join: function join(separator) {
return this._items.join(separator);
},
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList),
* context?
* );
*/
forEach: null,
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> *,
* context?
* ) -> Array;
*/
map: null,
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean,
* context?
* ) -> Array;
*/
filter: null,
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean,
* context?
* ) -> *;
*/
find: function(cb, context) {
var items = this._items;
for (var i = 0, l = items.length; i < l; i++) {
var item = items[i];
if (cb.call(context, item, i, this)) {
return item;
}
}
},
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean,
* context?
* ) -> int;
*/
findIndex: function(cb, context) {
var items = this._items;
for (var i = 0, l = items.length; i < l; i++) {
if (cb.call(context, items[i], i, this)) {
return i;
}
}
return -1;
},
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean,
* context?
* ) -> boolean;
*/
every: null,
/**
* @typesign (
* cb: (item, index: uint, list: cellx.ObservableList) -> ?boolean,
* context?
* ) -> boolean;
*/
some: null,
/**
* @typesign (
* cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *,
* initialValue?
* ) -> *;
*/
reduce: null,
/**
* @typesign (
* cb: (accumulator, item, index: uint, list: cellx.ObservableList) -> *,
* initialValue?
* ) -> *;
*/
reduceRight: null,
/**
* @typesign () -> cellx.ObservableList;
*/
clone: function clone() {
return new this.constructor(this, {
adoptsValueChanges: this.adoptsValueChanges,
comparator: this.comparator,
sorted: this.sorted
});
},
/**
* @typesign () -> Array;
*/
toArray: function toArray() {
return this._items.slice();
},
/**
* @typesign () -> string;
*/
toString: function toString() {
return this._items.join();
}
});
['forEach', 'map', 'filter', 'every', 'some'].forEach((function(name) {
ObservableList.prototype[name] = function(cb, context) {
return this._items[name]((function(item, index) {
return cb.call(context, item, index, this);
}), this);
};
}));
['reduce', 'reduceRight'].forEach((function(name) {
ObservableList.prototype[name] = function(cb, initialValue) {
var items = this._items;
var list = this;
function wrapper(accumulator, item, index) {
return cb(accumulator, item, index, list);
}
return arguments.length >= 2 ? items[name](wrapper, initialValue) : items[name](wrapper);
};
}));
[
['keys', function keys(index) {
return index;
}],
['values', function values(index, item) {
return item;
}],
['entries', function entries(index, item) {
return [index, item];
}]
].forEach((function(settings) {
var getStepValue = settings[1];
ObservableList.prototype[settings[0]] = function() {
var items = this._items;
var index = 0;
var done = false;
return {
next: function() {
if (!done) {
if (index < items.length) {
return {
value: getStepValue(index, items[index++]),
done: false
};
}
done = true;
}
return {
value: void 0,
done: true
};
}
};
};
}));
ObservableList.prototype[Symbol$1.iterator] = ObservableList.prototype.values;
/**
* @typesign (cb: ());
*/
var nextTick;
/* istanbul ignore next */
if (global$1.process && process.toString() == '[object process]' && process.nextTick) {
nextTick = process.nextTick;
} else if (global$1.setImmediate) {
nextTick = function nextTick(cb) {
setImmediate(cb);
};
} else if (global$1.Promise && Promise.toString().indexOf('[native code]') != -1) {
var prm = Promise.resolve();
nextTick = function nextTick(cb) {
prm.then((function() {
cb();
}));
};
} else {
var queue;
global$1.addEventListener('message', (function() {
if (queue) {
var track = queue;
queue = null;
for (var i = 0, l = track.length; i < l; i++) {
try {
track[i]();
} catch (err) {
ErrorLogger.log(err);
}
}
}
}));
nextTick = function nextTick(cb) {
if (queue) {
queue.push(cb);
} else {
queue = [cb];
postMessage('__tic__', '*');
}
};
}
var nextTick$1 = nextTick;
function noop() {}
var EventEmitterProto = EventEmitter.prototype;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 0x1fffffffffffff;
var KEY_INNER$1 = EventEmitter.KEY_INNER;
var errorIndexCounter = 0;
var pushingIndexCounter = 0;
var releasePlan = new Map$1();
var releasePlanIndex = MAX_SAFE_INTEGER;
var releasePlanToIndex = -1;
var releasePlanned = false;
var currentlyRelease = false;
var currentCell = null;
var error = { original: null };
var releaseVersion = 1;
var transactionLevel = 0;
var pendingReactions = [];
var afterReleaseCallbacks;
function release() {
if (!releasePlanned) {
return;
}
releasePlanned = false;
currentlyRelease = true;
var queue = releasePlan.get(releasePlanIndex);
for (;;) {
var cell = queue && queue.shift();
if (!cell) {
if (releasePlanIndex == releasePlanToIndex) {
break;
}
queue = releasePlan.get(++releasePlanIndex);
continue;
}
var level = cell._level;
var changeEvent = cell._changeEvent;
if (!changeEvent) {
if (level > releasePlanIndex || cell._levelInRelease == -1) {
if (!queue.length) {
if (releasePlanIndex == releasePlanToIndex) {
break;
}
queue = releasePlan.get(++releasePlanIndex);
}
continue;
}
cell.pull();
level = cell._level;
changeEvent = cell._changeEvent;
if (level > releasePlanIndex) {
if (!queue.length) {
queue = releasePlan.get(++releasePlanIndex);
}
continue;
}
}
cell._levelInRelease = -1;
if (changeEvent) {
var oldReleasePlanIndex = releasePlanIndex;
cell._fixedValue = cell._value;
cell._changeEvent = null;
cell._handleEvent(changeEvent);
var pushingIndex = cell._pushingIndex;
var slaves = cell._slaves;
for (var i = 0, l = slaves.length; i < l; i++) {
var slave = slaves[i];
if (slave._level <= level) {
slave._level = level + 1;
}
if (pushingIndex >= slave._pushingIndex) {
slave._pushingIndex = pushingIndex;
slave._changeEvent = null;
slave._addToRelease();
}
}
if (releasePlanIndex != oldReleasePlanIndex) {
queue = releasePlan.get(releasePlanIndex);
continue;
}
}
if (!queue.length) {
if (releasePlanIndex == releasePlanToIndex) {
break;
}
queue = releasePlan.get(++releasePlanIndex);
}
}
releasePlanIndex = MAX_SAFE_INTEGER;
releasePlanToIndex = -1;
currentlyRelease = false;
releaseVersion++;
if (afterReleaseCallbacks) {
var callbacks = afterReleaseCallbacks;
afterReleaseCallbacks = null;
for (var j = 0, m = callbacks.length; j < m; j++) {
callbacks[j]();
}
}
}
/**
* @typesign (value);
*/
function defaultPut(value, push$$1) {
push$$1(value);
}
var config = {
asynchronous: true
};
/**
* @class cellx.Cell
* @extends {cellx.EventEmitter}
*
* @example
* var a = new Cell(1);
* var b = new Cell(2);
* var c = new Cell(function() {
* return a.get() + b.get();
* });
*
* c.on('change', function() {
* console.log('c = ' + c.get());
* });
*
* console.log(c.get());
* // => 3
*
* a.set(5);
* b.set(10);
* // => 'c = 15'
*
* @typesign new Cell(value?, opts?: {
* debugKey?: string,
* owner?: Object,
* get?: (value) -> *,
* validate?: (value, oldValue),
* merge: (value, oldValue) -> *,
* put?: (value, push: (value), fail: (err), oldValue),
* reap?: (),
* onChange?: (evt: cellx~Event) -> ?boolean,
* onError?: (evt: cellx~Event) -> ?boolean
* }) -> cellx.Cell;
*
* @typesign new Cell(pull: (push: (value), fail: (err), next) -> *, opts?: {
* debugKey?: string,
* owner?: Object,
* get?: (value) -> *,
* validate?: (value, oldValue),
* merge: (value, oldValue) -> *,
* put?: (value, push: (value), fail: (err), oldValue),
* reap?: (),
* onChange?: (evt: cellx~Event) -> ?boolean,
* onError?: (evt: cellx~Event) -> ?boolean
* }) -> cellx.Cell;
*/
var Cell = EventEmitter.extend({
Static: {
_nextTick: nextTick$1,
/**
* @typesign (cnfg: { asynchronous?: boolean });
*/
configure: function configure(cnfg) {
if (cnfg.asynchronous !== void 0) {
if (releasePlanned) {
release();
}
config.asynchronous = cnfg.asynchronous;
}
},
/**
* @typesign (cb: (), context?) -> ();
*/
autorun: function autorun(cb, context) {
var cell = new Cell(function() {
if (transactionLevel) {
var index = pendingReactions.indexOf(this);
if (index > -1) {
pendingReactions.splice(index, 1);
}
pendingReactions.push(this);
} else {
cb.call(context);
}
}, { onChange: noop });
return function disposer() {
cell.dispose();
};
},
/**
* @typesign ();
*/
forceRelease: function forceRelease() {
if (releasePlanned) {
release();
}
},
/**
* @typesign (cb: ());
*/
transaction: function transaction(cb) {
if (!transactionLevel++ && releasePlanned) {
release();
}
var success;
try {
cb();
success = true;
} catch (err) {
ErrorLogger.log(err);
for (var iterator = releasePlan.values(), step; !(step = iterator.next()).done;) {
var queue = step.value;
for (var i = queue.length; i;) {
var cell = queue[--i];
cell._value = cell._fixedValue;
cell._levelInRelease = -1;
cell._changeEvent = null;
}
}
releasePlan.clear();
releasePlanIndex = MAX_SAFE_INTEGER;
releasePlanToIndex = -1;
releasePlanned = false;
pendingReactions.length = 0;
success = false;
}
if (!--transactionLevel && success) {
for (var i = 0, l = pendingReactions.length; i < l; i++) {
var reaction = pendingReactions[i];
if (reaction instanceof Cell) {
reaction.pull();
} else {
EventEmitterProto._handleEvent.call(reaction[1], reaction[0]);
}
}
pendingReactions.length = 0;
if (releasePlanned) {
release();
}
}
},
/**
* @typesign (cb: ());
*/
afterRelease: function afterRelease(cb) {
(afterReleaseCallbacks || (afterReleaseCallbacks = [])).push(cb);
}
},
constructor: function Cell(value, opts) {
EventEmitter.call(this);
if (!opts) {
opts = {};
}
var cell = this;
this.debugKey = opts.debugKey;
this.owner = opts.owner || this;
this._pull = typeof value == 'function' ? value : null;
this._get = opts.get || null;
this._validate = opts.validate || null;
this._merge = opts.merge || null;
this._put = opts.put || defaultPut;
var push$$1 = this.push;
var fail = this.fail;
this.push = function(value) { push$$1.call(cell, value); };
this.fail = function(err) { fail.call(cell, err); };
this._onFulfilled = this._onRejected = null;
this._reap = opts.reap || null;
if (this._pull) {
this._fixedValue = this._value = void 0;
} else {
if (this._validate) {
this._validate(value, void 0);
}
if (this._merge) {
value = this._merge(value, void 0);
}
this._fixedValue = this._value = value;
if (value instanceof EventEmitter) {
value.on('change', this._onValueChange, this);
}
}
this._inited = false;
this._currentlyPulling = false;
this._active = false;
this._hasFollowers = false;
this._errorIndex = 0;
this._pushingIndex = 0;
this._version = 0;
/**
* Ведущие ячейки.
* @type {?Array<cellx.Cell>}
*/
this._masters = void 0;
/**
* Ведомые ячейки.
* @type {Array<cellx.Cell>}
*/
this._slaves = [];
this._level = 0;
this._levelInRelease = -1;
this._pending = false;
this._selfPendingStatusCell = null;
this._pendingStatusCell = null;
this._error = null;
this._selfErrorCell = null;
this._errorCell = null;
this._fulfilled = false;
this._rejected = false;
this._changeEvent = null;
this._canCancelChange = true;
this._lastErrorEvent = null;
if (opts.onChange) {
this.on('change', opts.onChange);
}
if (opts.onError) {
this.on('error', opts.onError);
}
},
_handleEvent: function _handleEvent(evt) {
if (transactionLevel) {
pendingReactions.push([evt, this]);
} else {
EventEmitterProto._handleEvent.call(this, evt);
}
},
/**
* @override
*/
on: function on(type, listener, context) {
if (releasePlanned) {
release();
}
this._activate();
if (typeof type == 'object') {
EventEmitterProto.on.call(this, type, arguments.length >= 2 ? listener : this.owner);
} else {
EventEmitterProto.on.call(this, type, listener, arguments.length >= 3 ? context : this.owner);
}
this._hasFollowers = true;
return this;
},
/**
* @override
*/
off: function off(type, listener, context) {
if (releasePlanned) {
release();
}
var argCount = arguments.length;
if (argCount) {
if (typeof type == 'object') {
EventEmitterProto.off.call(this, type, argCount >= 2 ? listener : this.owner);
} else {
EventEmitterProto.off.call(this, type, listener, argCount >= 3 ? context : this.owner);
}
} else {
EventEmitterProto.off.call(this);
}
if (!this._slaves.length && !this._events.has('change') && !this._events.has('error') && this._hasFollowers) {
this._hasFollowers = false;
this._deactivate();
if (this._reap) {
this._reap.call(this.owner);
}
}
return this;
},
/**
* @typesign (
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
addChangeListener: function addChangeListener(listener, context) {
return this.on('change', listener, arguments.length >= 2 ? context : this.owner);
},
/**
* @typesign (
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
removeChangeListener: function removeChangeListener(listener, context) {
return this.off('change', listener, arguments.length >= 2 ? context : this.owner);
},
/**
* @typesign (
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
addErrorListener: function addErrorListener(listener, context) {
return this.on('error', listener, arguments.length >= 2 ? context : this.owner);
},
/**
* @typesign (
* listener: (evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
removeErrorListener: function removeErrorListener(listener, context) {
return this.off('error', listener, arguments.length >= 2 ? context : this.owner);
},
/**
* @typesign (
* listener: (err: ?Error, evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
subscribe: function subscribe(listener, context) {
function wrapper(evt) {
return listener.call(this, evt.error || null, evt);
}
wrapper[KEY_INNER$1] = listener;
if (arguments.length < 2) {
context = this.owner;
}
return this
.on('change', wrapper, context)
.on('error', wrapper, context);
},
/**
* @typesign (
* listener: (err: ?Error, evt: cellx~Event) -> ?boolean,
* context?
* ) -> cellx.Cell;
*/
unsubscribe: function unsubscribe(listener, context) {
if (arguments.length < 2) {
context = this.owner;
}
return this
.off('change', listener, context)
.off('error', listener, context);
},
/**
* @typesign (slave: cellx.Cell);
*/
_registerSlave: function _registerSlave(slave) {
this._activate();
this._slaves.push(slave);
this._hasFollowers = true;
},
/**
* @typesign (slave: cellx.Cell);
*/
_unregisterSlave: function _unregisterSlave(slave) {
this._slaves.splice(this._slaves.indexOf(slave), 1);
if (!this._slaves.length && !this._events.has('change') && !this._events.has('error')) {
this._hasFollowers = false;
this._deactivate();
if (this._reap) {
this._reap.call(this.owner);
}
}
},
/**
* @typesign ();
*/
_activate: function _activate() {
if (!this._pull || this._active || this._masters === null) {
return;
}
var masters = this._masters;
if (this._version < releaseVersion) {
var value = this._tryPull();
if (masters || this._masters || !this._inited) {
if (value === error) {
this._fail(error.original, false);
} else {
this._push(value, false, false);
}
}
masters = this._masters;
}
if (masters) {
var i = masters.length;
do {
masters[--i]._registerSlave(this);
} while (i);
this._active = true;
}
},
/**
* @typesign ();
*/
_deactivate: function _deactivate() {
if (!this._active) {
return;
}
var masters = this._masters;
var i = masters.length;
do {
masters[--i]._unregisterSlave(this);
} while (i);
if (this._levelInRelease != -1 && !this._changeEvent) {
this._levelInRelease = -1;
}
this._active = false;
},
/**
* @typesign ();
*/
_addToRelease: function _addToRelease() {
var level = this._level;
if (level <= this._levelInRelease) {
return;
}
var queue;
(releasePlan.get(level) || (releasePlan.set(level, (queue = [])), queue)).push(this);
if (releasePlanIndex > level) {
releasePlanIndex = level;
}
if (releasePlanToIndex < level) {
releasePlanToIndex = level;
}
this._levelInRelease = level;
if (!releasePlanned && !currentlyRelease) {
releasePlanned = true;
if (!transactionLevel && !config.asynchronous) {
release();
} else {
Cell._nextTick(release);
}
}
},
/**
* @typesign (evt: cellx~Event);
*/
_onValueChange: function _onValueChange(evt) {
this._pushingIndex = ++pushingIndexCounter;
if (this._changeEvent) {
evt.prev = this._changeEvent;
this._changeEvent = evt;
if (this._value === this._fixedValue) {
this._canCancelChange = false;
}
} else {
evt.prev = null;
this._changeEvent = evt;
this._canCancelChange = false;
this._addToRelease();
}
},
/**
* @typesign () -> *;
*/
get: function get() {
if (releasePlanned && this._pull) {
release();
}
if (this._pull && !this._active && this._version < releaseVersion && this._masters !== null) {
var oldMasters = this._masters;
var value = this._tryPull();
var masters = this._masters;
if (oldMasters || masters || !this._inited) {
if (masters && this._hasFollowers) {
var i = masters.length;
do {
masters[--i]._registerSlave(this);
} while (i);
this._active = true;
}
if (value === error) {
this._fail(error.original, false);
} else {
this._push(value, false, false);
}
}
}
if (currentCell) {
var currentCellMasters = currentCell._masters;
var level = this._level;
if (currentCellMasters) {
if (currentCellMasters.indexOf(this) == -1) {
currentCellMasters.push(this);
if (currentCell._level <= level) {
currentCell._level = level + 1;
}
}
} else {
currentCell._masters = [this];
currentCell._level = level + 1;
}
}
return this._get ? this._get(this._value) : this._value;
},
/**
* @typesign () -> boolean;
*/
pull: function pull() {
if (!this._pull) {
return false;
}
if (releasePlanned) {
release();
}
var hasFollowers = this._hasFollowers;
var oldMasters;
var oldLevel;
if (hasFollowers) {
oldMasters = this._masters;
oldLevel = this._level;
}
var value = this._tryPull();
if (hasFollowers) {
var masters = this._masters;
var newMasterCount = 0;
if (masters) {
var i = masters.length;
do {
var master = masters[--i];
if (!oldMasters || oldMasters.indexOf(master) == -1) {
master._registerSlave(this);
newMasterCount++;
}
} while (i);
}
if (oldMasters && (masters ? masters.length - newMasterCount : 0) < oldMasters.length) {
for (var j = oldMasters.length; j;) {
var oldMaster = oldMasters[--j];
if (!masters || masters.indexOf(oldMaster) == -1) {
oldMaster._unregisterSlave(this);
}
}
}
this._active = !!(masters && masters.length);
if (currentlyRelease && this._level > oldLevel) {
this._addToRelease();
return false;
}
}
if (value === error) {
this._fail(error.original, false);
return true;
}
return this._push(value, false, true);
},
/**
* @typesign () -> *;
*/
_tryPull: function _tryPull() {
if (this._currentlyPulling) {
throw new TypeError('Circular pulling detected');
}
this._pending = true;
this._fulfilled = this._rejected = false;
if (this._selfPendingStatusCell) {
this._selfPendingStatusCell.set(true);
}
var prevCell = currentCell;
currentCell = this;
this._currentlyPulling = true;
this._masters = null;
this._level = 0;
try {
return this._pull.call(this.owner, this.push, this.fail, this._value);
} catch (err) {
error.original = err;
return error;
} finally {
currentCell = prevCell;
this._version = releaseVersion + currentlyRelease;
var pendingStatusCell = this._pendingStatusCell;
if (pendingStatusCell && pendingStatusCell._active) {
pendingStatusCell.pull();
}
var errorCell = this._errorCell;
if (errorCell && errorCell._active) {
errorCell.pull();
}
this._currentlyPulling = false;
}
},
/**
* @typesign () -> ?Error;
*/
getError: function getError() {
if (!this._errorCell) {
var debugKey = this.debugKey;
this._selfErrorCell = new Cell(this._error, debugKey ? { debugKey: debugKey + '._selfErrorCell' } : null);
this._errorCell = new Cell(function() {
this.get();
var err = this._selfErrorCell.get();
var index;
if (err) {
index = this._errorIndex;
if (index == errorIndexCounter) {
return err;
}
}
var masters = this._masters;
if (masters) {
var i = masters.length;
do {
var master = masters[--i];
var masterError = master.getError();
if (masterError) {
var masterErrorIndex = master._errorIndex;
if (masterErrorIndex == errorIndexCounter) {
return masterError;
}
if (!err || index < masterErrorIndex) {
err = masterError;
index = masterErrorIndex;
}
}
} while (i);
}
return err;
}, debugKey ? { debugKey: debugKey + '._errorCell', owner: this } : { owner: this });
}
return this._errorCell.get();
},
/**
* @typesign (value) -> cellx.Cell;
*/
set: function set(value) {
var oldValue = this._value;
if (this._validate) {
this._validate(value, oldValue);
}
if (this._merge) {
value = this._merge(value, oldValue);
}
this._put.call(this.owner, value, this.push, this.fail, oldValue);
return this;
},
/**
* @typesign (value) -> cellx.Cell;
*/
push: function push(value) {
this._push(value, true, false);
return this;
},
/**
* @typesign (value, external: boolean, pulling: boolean) -> boolean;
*/
_push: function _push(value, external, pulling) {
this._inited = true;
var oldValue = this._value;
if (external && currentlyRelease) {
if (is(value, oldValue)) {
this._setError(null);
this._fulfill(value);
return false;
}
var cell = this;
(afterReleaseCallbacks || (afterReleaseCallbacks = [])).push((function() {
cell._push(value, true, false);
}));
return true;
}
if (external || !currentlyRelease && pulling) {
this._pushingIndex = ++pushingIndexCounter;
}
this._setError(null);
if (is(value, oldValue)) {
if (external) {
this._fulfill(value);
}
return false;
}
this._value = value;
if (oldValue instanceof EventEmitter) {
oldValue.off('change', this._onValueChange, this);
}
if (value instanceof EventEmitter) {
value.on('change', this._onValueChange, this);
}
if (this._hasFollowers || transactionLevel) {
if (this._changeEvent) {
if (is(value, this._fixedValue) && this._canCancelChange) {
this._levelInRelease = -1;
this._changeEvent = null;
} else {
this._changeEvent = {
target: this,
type: 'change',
oldValue: oldValue,
value: value,
prev: this._changeEvent
};
}
} else {
this._changeEvent = {
target: this,
type: 'change',
oldValue: oldValue,
value: value,
prev: null
};
this._canCancelChange = true;
this._addToRelease();
}
} else {
if (external || !currentlyRelease && pulling) {
releaseVersion++;
}
this._fixedValue = value;
this._version = releaseVersion + currentlyRelease;
}
if (external) {
this._fulfill(value);
}
return true;
},
_fulfill: function _fulfill(value) {
if (!this._pending) {
return;
}
this._pending = false;
this._fulfilled = true;
if (this._selfPendingStatusCell) {
this._selfPendingStatusCell.set(false);
}
if (this._onFulfilled) {
this._onFulfilled(value);
}
},
/**
* @typesign (err) -> cellx.Cell;
*/
fail: function fail(err) {
this._fail(err, true);
return this;
},
/**
* @typesign (err, external: boolean);
*/
_fail: function _fail(err, external) {
this._logError(err);
if (!(err instanceof Error)) {
err = new Error(String(err));
}
this._setError(err);
if (external) {
this._reject(err);
}
},
/**
* @typesign (err: ?Error);
*/
_setError: function _setError(err) {
if (!err && !this._error) {
return;
}
this._error = err;
if (this._selfErrorCell) {
this._selfErrorCell.set(err);
}
if (err) {
this._errorIndex = ++errorIndexCounter;
this._handleErrorEvent({
type: 'error',
error: err
});
}
},
/**
* @typesign (evt: cellx~Event{ error: Error });
*/
_handleErrorEvent: function _handleErrorEvent(evt) {
if (this._lastErrorEvent === evt) {
return;
}
this._lastErrorEvent = evt;
this._handleEvent(evt);
var slaves = this._slaves;
for (var i = 0, l = slaves.length; i < l; i++) {
slaves[i]._handleErrorEvent(evt);
}
},
_reject: function _reject(err) {
if (!this._pending) {
return;
}
this._pending = false;
this._rejected = true;
if (this._selfPendingStatusCell) {
this._selfPendingStatusCell.set(false);
}
if (this._onRejected) {
this._onRejected(err);
}
},
/**
* @typesign () -> boolean;
*/
isPending: function isPending() {
if (!this._pendingStatusCell) {
var debugKey = this.debugKey;
if (this._pull && this._pull.length) {
this._selfPendingStatusCell = new Cell(
this._pending,
debugKey ? { debugKey: debugKey + '._selfPendingStatusCell' } : null
);
}
this._pendingStatusCell = new Cell(function() {
if (this._selfPendingStatusCell && this._selfPendingStatusCell.get()) {
return true;
}
this.get();
var masters = this._masters;
if (masters) {
var i = masters.length;
do {
if (masters[--i].isPending()) {
return true;
}
} while (i);
}
return false;
}, debugKey ? { debugKey: debugKey + '._pendingStatusCell', owner: this } : { owner: this });
}
return this._pendingStatusCell.get();
},
/**
* @typesign (onFulfilled: ?(value) -> *, onRejected?: (err) -> *) -> Promise;
*/
then: function then(onFulfilled, onRejected) {
if (releasePlanned) {
release();
}
if (!this._pull || this._fulfilled) {
return Promise.resolve(this._get ? this._get(this._value) : this._value).then(onFulfilled);
}
if (this._rejected) {
return Promise.reject(this._error).catch(onRejected);
}
var cell = this;
var promise = new Promise(function(resolve, reject) {
cell._onFulfilled = function onFulfilled(value) {
cell._onFulfilled = cell._onRejected = null;
resolve(cell._get ? cell._get(value) : value);
};
cell._onRejected = function onRejected(err) {
cell._onFulfilled = cell._onRejected = null;
reject(err);
};
}).then(onFulfilled, onRejected);
if (!this._pending) {
this.pull();
}
return promise;
},
/**
* @typesign (onRejected: (err) -> *) -> Promise;
*/
catch: function catch_(onRejected) {
return this.then(null, onRejected);
},
/**
* @override
*/
_logError: function _logError() {
var msg = slice.call(arguments);
if (this.debugKey) {
msg.unshift('[' + this.debugKey + ']');
}
EventEmitterProto._logError.apply(this, msg);
},
/**
* @typesign () -> cellx.Cell;
*/
dispose: function dispose() {
var slaves = this._slaves;
for (var i = 0, l = slaves.length; i < l; i++) {
slaves[i].dispose();
}
return this.off();
}
});
Cell.prototype[Symbol$1.iterator] = function() {
return this._value[Symbol$1.iterator]();
};
/**
* @typesign (...msg);
*/
function logError() {
var console = global$1.console;
(console && console.error || noop).call(console || global$1, map$1.call(arguments, (function(arg) {
return arg === Object(arg) && arg.stack || arg;
})).join(' '));
}
ErrorLogger.setHandler(logError);
/**
* @typesign (value?, opts?: {
* debugKey?: string,
* owner?: Object,
* validate?: (value, oldValue),
* put?: (value, push: (value), fail: (err), oldValue),
* reap?: (),
* onChange?: (evt: cellx~Event) -> ?boolean,
* onError?: (evt: cellx~Event) -> ?boolean
* }) -> cellx;
*
* @typesign (pull: (push: (value), fail: (err), next) -> *, opts?: {
* debugKey?: string
* owner?: Object,
* validate?: (value, oldValue),
* put?: (value, push: (value), fail: (err), oldValue),
* reap?: (),
* onChange?: (evt: cellx~Event) -> ?boolean,
* onError?: (evt: cellx~Event) -> ?boolean
* }) -> cellx;
*/
function cellx(value, opts) {
if (!opts) {
opts = {};
}
var initialValue = value;
function cx(value) {
var owner = this;
if (!owner || owner == global$1) {
owner = cx;
}
if (!hasOwn.call(owner, CELLS)) {
Object.defineProperty(owner, CELLS, {
value: new Map$1()
});
}
var cell = owner[CELLS].get(cx);
if (!cell) {
if (value === 'dispose' && arguments.length >= 2) {
return;
}
opts = Object.create(opts);
opts.owner = owner;
cell = new Cell(initialValue, opts);
owner[CELLS].set(cx, cell);
}
switch (arguments.length) {
case 0: {
return cell.get();
}
case 1: {
cell.set(value);
return value;
}
default: {
var method = value;
switch (method) {
case 'bind': {
cx = cx.bind(owner);
cx.constructor = cellx;
return cx;
}
case 'unwrap': {
return cell;
}
default: {
var result = Cell.prototype[method].apply(cell, slice.call(arguments, 1));
return result === cell ? cx : result;
}
}
}
}
}
cx.constructor = cellx;
if (opts.onChange || opts.onError) {
cx.call(opts.owner || global$1);
}
return cx;
}
cellx.configure = function(config) {
Cell.configure(config);
};
cellx.ErrorLogger = ErrorLogger;
cellx.EventEmitter = EventEmitter;
cellx.ObservableCollectionMixin = ObservableCollectionMixin;
cellx.ObservableMap = ObservableMap;
cellx.ObservableList = ObservableList;
cellx.Cell = Cell;
cellx.autorun = Cell.autorun;
cellx.transact = cellx.transaction = Cell.transaction;
cellx.KEY_UID = UID;
cellx.KEY_CELLS = CELLS;
/**
* @typesign (
* entries?: Object|Array<{ 0, 1 }>|cellx.ObservableMap,
* opts?: { adoptsValueChanges?: boolean }
* ) -> cellx.ObservableMap;
*
* @typesign (
* entries?: Object|Array<{ 0, 1 }>|cellx.ObservableMap,
* adoptsValueChanges?: boolean
* ) -> cellx.ObservableMap;
*/
function map$$1(entries, opts) {
return new ObservableMap(entries, typeof opts == 'boolean' ? { adoptsValueChanges: opts } : opts);
}
cellx.map = map$$1;
/**
* @typesign (items?: Array|cellx.ObservableList, opts?: {
* adoptsValueChanges?: boolean,
* comparator?: (a, b) -> int,
* sorted?: boolean
* }) -> cellx.ObservableList;
*
* @typesign (items?: Array|cellx.ObservableList, adoptsValueChanges?: boolean) -> cellx.ObservableList;
*/
function list(items, opts) {
return new ObservableList(items, typeof opts == 'boolean' ? { adoptsValueChanges: opts } : opts);
}
cellx.list = list;
/**
* @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter;
*/
function defineObservableProperty(obj, name, value) {
var privateName = '_' + name;
obj[privateName] = value instanceof Cell ? value : new Cell(value, { owner: obj });
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get: function() {
return this[privateName].get();
},
set: function(value) {
this[privateName].set(value);
}
});
return obj;
}
cellx.defineObservableProperty = defineObservableProperty;
/**
* @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter;
*/
function defineObservableProperties(obj, props) {
Object.keys(props).forEach((function(name) {
defineObservableProperty(obj, name, props[name]);
}));
return obj;
}
cellx.defineObservableProperties = defineObservableProperties;
/**
* @typesign (obj: cellx.EventEmitter, name: string, value) -> cellx.EventEmitter;
* @typesign (obj: cellx.EventEmitter, props: Object) -> cellx.EventEmitter;
*/
function define(obj, name, value) {
if (arguments.length == 3) {
defineObservableProperty(obj, name, value);
} else {
defineObservableProperties(obj, name);
}
return obj;
}
cellx.define = define;
cellx.JS = cellx.js = {
is: is,
Symbol: Symbol$1,
Map: Map$1
};
cellx.Utils = cellx.utils = {
logError: logError,
nextUID: nextUID,
mixin: mixin,
createClass: createClass,
nextTick: nextTick$1,
noop: noop
};
cellx.cellx = cellx; // for destructuring
return cellx;
})));
|
ajax/libs/js-data/1.1.0/js-data.js | sympmarc/cdnjs | /**
* @author Jason Dobry <[email protected]>
* @file dist/js-data.js
* @version 1.1.0 - Homepage <http://www.js-data.io/>
* @copyright (c) 2014 Jason Dobry
* @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE>
*
* @overview Data store.
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSData=e()}}(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(require,module,exports){
// Copyright 2012 Google 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.
// Modifications
// Copyright 2014-2015 Jason Dobry
//
// Summary of modifications:
// Fixed use of "delete" keyword for IE8 compatibility
// Exposed diffObjectFromOldObject on the exported object
// Added the "equals" argument to diffObjectFromOldObject to be used to check equality
// Added a way to to define a default equality operator for diffObjectFromOldObject
// Added a way in diffObjectFromOldObject to ignore changes to certain properties
// Removed all code related to:
// - ArrayObserver
// - ArraySplice
// - PathObserver
// - CompoundObserver
// - Path
// - ObserverTransform
(function(global) {
'use strict';
var equalityFn = function (a, b) {
return a === b;
};
var blacklist = [];
// Detect and do basic sanity checking on Object/Array.observe.
function detectObjectObserve() {
if (typeof Object.observe !== 'function' ||
typeof Array.observe !== 'function') {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var test = {};
var arr = [];
Object.observe(test, callback);
Array.observe(arr, callback);
test.id = 1;
test.id = 2;
delete test.id;
arr.push(1, 2);
arr.length = 0;
Object.deliverChangeRecords(callback);
if (records.length !== 5)
return false;
if (records[0].type != 'add' ||
records[1].type != 'update' ||
records[2].type != 'delete' ||
records[3].type != 'splice' ||
records[4].type != 'splice') {
return false;
}
Object.unobserve(test, callback);
Array.unobserve(arr, callback);
return true;
}
var hasObserve = detectObjectObserve();
function detectEval() {
// Don't test for eval if we're running in a Chrome App environment.
// We check for APIs set that only exist in a Chrome App context.
if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) {
return false;
}
try {
var f = new Function('', 'return true;');
return f();
} catch (ex) {
return false;
}
}
var hasEval = detectEval();
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var MAX_DIRTY_CHECK_CYCLES = 1000;
function dirtyCheck(observer) {
var cycles = 0;
while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) {
cycles++;
}
if (global.testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
return cycles > 0;
}
function objectIsEmpty(object) {
for (var prop in object)
return false;
return true;
}
function diffIsEmpty(diff) {
return objectIsEmpty(diff.added) &&
objectIsEmpty(diff.removed) &&
objectIsEmpty(diff.changed);
}
function isBlacklisted(prop, bl) {
if (!bl || !bl.length) {
return false;
}
var matches;
for (var i = 0; i < bl.length; i++) {
if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) {
return matches = prop;
}
}
return !!matches;
}
function diffObjectFromOldObject(object, oldObject, equals, bl) {
var added = {};
var removed = {};
var changed = {};
for (var prop in oldObject) {
var newValue = object[prop];
if (isBlacklisted(prop, bl))
continue;
if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop]))
continue;
if (!(prop in object)) {
removed[prop] = undefined;
continue;
}
if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop])
changed[prop] = newValue;
}
for (var prop in object) {
if (prop in oldObject)
continue;
if (isBlacklisted(prop, bl))
continue;
added[prop] = object[prop];
}
if (Array.isArray(object) && object.length !== oldObject.length)
changed.length = object.length;
return {
added: added,
removed: removed,
changed: changed
};
}
var eomTasks = [];
function runEOMTasks() {
if (!eomTasks.length)
return false;
for (var i = 0; i < eomTasks.length; i++) {
eomTasks[i]();
}
eomTasks.length = 0;
return true;
}
var runEOM = hasObserve ? (function(){
var eomObj = { pingPong: true };
var eomRunScheduled = false;
Object.observe(eomObj, function() {
runEOMTasks();
eomRunScheduled = false;
});
return function(fn) {
eomTasks.push(fn);
if (!eomRunScheduled) {
eomRunScheduled = true;
eomObj.pingPong = !eomObj.pingPong;
}
};
})() :
(function() {
return function(fn) {
eomTasks.push(fn);
};
})();
var observedObjectCache = [];
function newObservedObject() {
var observer;
var object;
var discardRecords = false;
var first = true;
function callback(records) {
if (observer && observer.state_ === OPENED && !discardRecords)
observer.check_(records);
}
return {
open: function(obs) {
if (observer)
throw Error('ObservedObject in use');
if (!first)
Object.deliverChangeRecords(callback);
observer = obs;
first = false;
},
observe: function(obj, arrayObserve) {
object = obj;
if (arrayObserve)
Array.observe(object, callback);
else
Object.observe(object, callback);
},
deliver: function(discard) {
discardRecords = discard;
Object.deliverChangeRecords(callback);
discardRecords = false;
},
close: function() {
observer = undefined;
Object.unobserve(object, callback);
observedObjectCache.push(this);
}
};
}
/*
* The observedSet abstraction is a perf optimization which reduces the total
* number of Object.observe observations of a set of objects. The idea is that
* groups of Observers will have some object dependencies in common and this
* observed set ensures that each object in the transitive closure of
* dependencies is only observed once. The observedSet acts as a write barrier
* such that whenever any change comes through, all Observers are checked for
* changed values.
*
* Note that this optimization is explicitly moving work from setup-time to
* change-time.
*
* TODO(rafaelw): Implement "garbage collection". In order to move work off
* the critical path, when Observers are closed, their observed objects are
* not Object.unobserve(d). As a result, it's possible that if the observedSet
* is kept open, but some Observers have been closed, it could cause "leaks"
* (prevent otherwise collectable objects from being collected). At some
* point, we should implement incremental "gc" which keeps a list of
* observedSets which may need clean-up and does small amounts of cleanup on a
* timeout until all is clean.
*/
function getObservedObject(observer, object, arrayObserve) {
var dir = observedObjectCache.pop() || newObservedObject();
dir.open(observer);
dir.observe(object, arrayObserve);
return dir;
}
var UNOPENED = 0;
var OPENED = 1;
var CLOSED = 2;
var nextObserverId = 1;
function Observer() {
this.state_ = UNOPENED;
this.callback_ = undefined;
this.target_ = undefined; // TODO(rafaelw): Should be WeakRef
this.directObserver_ = undefined;
this.value_ = undefined;
this.id_ = nextObserverId++;
}
Observer.prototype = {
open: function(callback, target) {
if (this.state_ != UNOPENED)
throw Error('Observer has already been opened.');
addToAll(this);
this.callback_ = callback;
this.target_ = target;
this.connect_();
this.state_ = OPENED;
return this.value_;
},
close: function() {
if (this.state_ != OPENED)
return;
removeFromAll(this);
this.disconnect_();
this.value_ = undefined;
this.callback_ = undefined;
this.target_ = undefined;
this.state_ = CLOSED;
},
deliver: function() {
if (this.state_ != OPENED)
return;
dirtyCheck(this);
},
report_: function(changes) {
try {
this.callback_.apply(this.target_, changes);
} catch (ex) {
Observer._errorThrownDuringCallback = true;
console.error('Exception caught during observer callback: ' +
(ex.stack || ex));
}
},
discardChanges: function() {
this.check_(undefined, true);
return this.value_;
}
}
var collectObservers = !hasObserve;
var allObservers;
Observer._allObserversCount = 0;
if (collectObservers) {
allObservers = [];
}
function addToAll(observer) {
Observer._allObserversCount++;
if (!collectObservers)
return;
allObservers.push(observer);
}
function removeFromAll(observer) {
Observer._allObserversCount--;
}
var runningMicrotaskCheckpoint = false;
var hasDebugForceFullDelivery = hasObserve && hasEval && (function() {
try {
eval('%RunMicrotasks()');
return true;
} catch (ex) {
return false;
}
})();
global.Platform = global.Platform || {};
global.Platform.performMicrotaskCheckpoint = function() {
if (runningMicrotaskCheckpoint)
return;
if (hasDebugForceFullDelivery) {
eval('%RunMicrotasks()');
return;
}
if (!collectObservers)
return;
runningMicrotaskCheckpoint = true;
var cycles = 0;
var anyChanged, toCheck;
do {
cycles++;
toCheck = allObservers;
allObservers = [];
anyChanged = false;
for (var i = 0; i < toCheck.length; i++) {
var observer = toCheck[i];
if (observer.state_ != OPENED)
continue;
if (observer.check_())
anyChanged = true;
allObservers.push(observer);
}
if (runEOMTasks())
anyChanged = true;
} while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged);
if (global.testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
runningMicrotaskCheckpoint = false;
};
if (collectObservers) {
global.Platform.clearObservers = function() {
allObservers = [];
};
}
function ObjectObserver(object) {
Observer.call(this);
this.value_ = object;
this.oldObject_ = undefined;
}
ObjectObserver.prototype = createObject({
__proto__: Observer.prototype,
arrayObserve: false,
connect_: function(callback, target) {
if (hasObserve) {
this.directObserver_ = getObservedObject(this, this.value_,
this.arrayObserve);
} else {
this.oldObject_ = this.copyObject(this.value_);
}
},
copyObject: function(object) {
var copy = Array.isArray(object) ? [] : {};
for (var prop in object) {
copy[prop] = object[prop];
};
if (Array.isArray(object))
copy.length = object.length;
return copy;
},
check_: function(changeRecords, skipChanges) {
var diff;
var oldValues;
if (hasObserve) {
if (!changeRecords)
return false;
oldValues = {};
diff = diffObjectFromChangeRecords(this.value_, changeRecords,
oldValues);
} else {
oldValues = this.oldObject_;
diff = diffObjectFromOldObject(this.value_, this.oldObject_);
}
if (diffIsEmpty(diff))
return false;
if (!hasObserve)
this.oldObject_ = this.copyObject(this.value_);
this.report_([
diff.added || {},
diff.removed || {},
diff.changed || {},
function(property) {
return oldValues[property];
}
]);
return true;
},
disconnect_: function() {
if (hasObserve) {
this.directObserver_.close();
this.directObserver_ = undefined;
} else {
this.oldObject_ = undefined;
}
},
deliver: function() {
if (this.state_ != OPENED)
return;
if (hasObserve)
this.directObserver_.deliver(false);
else
dirtyCheck(this);
},
discardChanges: function() {
if (this.directObserver_)
this.directObserver_.deliver(true);
else
this.oldObject_ = this.copyObject(this.value_);
return this.value_;
}
});
var observerSentinel = {};
var expectedRecordTypes = {
add: true,
update: true,
delete: true
};
function diffObjectFromChangeRecords(object, changeRecords, oldValues) {
var added = {};
var removed = {};
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
if (!expectedRecordTypes[record.type]) {
console.error('Unknown changeRecord type: ' + record.type);
console.error(record);
continue;
}
if (!(record.name in oldValues))
oldValues[record.name] = record.oldValue;
if (record.type == 'update')
continue;
if (record.type == 'add') {
if (record.name in removed)
delete removed[record.name];
else
added[record.name] = true;
continue;
}
// type = 'delete'
if (record.name in added) {
delete added[record.name];
delete oldValues[record.name];
} else {
removed[record.name] = true;
}
}
for (var prop in added)
added[prop] = object[prop];
for (var prop in removed)
removed[prop] = undefined;
var changed = {};
for (var prop in oldValues) {
if (prop in added || prop in removed)
continue;
var newValue = object[prop];
if (oldValues[prop] !== newValue)
changed[prop] = newValue;
}
return {
added: added,
removed: removed,
changed: changed
};
}
global.Observer = Observer;
global.diffObjectFromOldObject = diffObjectFromOldObject;
global.setEqualityFn = function (fn) {
equalityFn = fn;
};
global.setBlacklist = function (bl) {
blacklist = bl;
};
global.Observer.runEOM_ = runEOM;
global.Observer.observerSentinel_ = observerSentinel; // for testing.
global.Observer.hasObjectObserve = hasObserve;
global.ObjectObserver = ObjectObserver;
})(exports);
},{}],2:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 2.0.1
*/
(function() {
"use strict";
function $$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function $$utils$$isFunction(x) {
return typeof x === 'function';
}
function $$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var $$utils$$_isArray;
if (!Array.isArray) {
$$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
$$utils$$_isArray = Array.isArray;
}
var $$utils$$isArray = $$utils$$_isArray;
var $$utils$$now = Date.now || function() { return new Date().getTime(); };
function $$utils$$F() { }
var $$utils$$o_create = (Object.create || function (o) {
if (arguments.length > 1) {
throw new Error('Second argument not supported');
}
if (typeof o !== 'object') {
throw new TypeError('Argument must be an object');
}
$$utils$$F.prototype = o;
return new $$utils$$F();
});
var $$asap$$len = 0;
var $$asap$$default = function asap(callback, arg) {
$$asap$$queue[$$asap$$len] = callback;
$$asap$$queue[$$asap$$len + 1] = arg;
$$asap$$len += 2;
if ($$asap$$len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
$$asap$$scheduleFlush();
}
};
var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver;
// test for web worker but not in IE10
var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function $$asap$$useNextTick() {
return function() {
process.nextTick($$asap$$flush);
};
}
function $$asap$$useMutationObserver() {
var iterations = 0;
var observer = new $$asap$$BrowserMutationObserver($$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function $$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = $$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function $$asap$$useSetTimeout() {
return function() {
setTimeout($$asap$$flush, 1);
};
}
var $$asap$$queue = new Array(1000);
function $$asap$$flush() {
for (var i = 0; i < $$asap$$len; i+=2) {
var callback = $$asap$$queue[i];
var arg = $$asap$$queue[i+1];
callback(arg);
$$asap$$queue[i] = undefined;
$$asap$$queue[i+1] = undefined;
}
$$asap$$len = 0;
}
var $$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
$$asap$$scheduleFlush = $$asap$$useNextTick();
} else if ($$asap$$BrowserMutationObserver) {
$$asap$$scheduleFlush = $$asap$$useMutationObserver();
} else if ($$asap$$isWorker) {
$$asap$$scheduleFlush = $$asap$$useMessageChannel();
} else {
$$asap$$scheduleFlush = $$asap$$useSetTimeout();
}
function $$$internal$$noop() {}
var $$$internal$$PENDING = void 0;
var $$$internal$$FULFILLED = 1;
var $$$internal$$REJECTED = 2;
var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$selfFullfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function $$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.')
}
function $$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
$$$internal$$GET_THEN_ERROR.error = error;
return $$$internal$$GET_THEN_ERROR;
}
}
function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function $$$internal$$handleForeignThenable(promise, thenable, then) {
$$asap$$default(function(promise) {
var sealed = false;
var error = $$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
$$$internal$$resolve(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
$$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
$$$internal$$reject(promise, error);
}
}, promise);
}
function $$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, thenable._result);
} else if (promise._state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, thenable._result);
} else {
$$$internal$$subscribe(thenable, undefined, function(value) {
$$$internal$$resolve(promise, value);
}, function(reason) {
$$$internal$$reject(promise, reason);
});
}
}
function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
$$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
var then = $$$internal$$getThen(maybeThenable);
if (then === $$$internal$$GET_THEN_ERROR) {
$$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
$$$internal$$fulfill(promise, maybeThenable);
} else if ($$utils$$isFunction(then)) {
$$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
$$$internal$$fulfill(promise, maybeThenable);
}
}
}
function $$$internal$$resolve(promise, value) {
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$selfFullfillment());
} else if ($$utils$$objectOrFunction(value)) {
$$$internal$$handleMaybeThenable(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}
function $$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
$$$internal$$publish(promise);
}
function $$$internal$$fulfill(promise, value) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._result = value;
promise._state = $$$internal$$FULFILLED;
if (promise._subscribers.length === 0) {
} else {
$$asap$$default($$$internal$$publish, promise);
}
}
function $$$internal$$reject(promise, reason) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._state = $$$internal$$REJECTED;
promise._result = reason;
$$asap$$default($$$internal$$publishRejection, promise);
}
function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
subscribers[length + $$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
$$asap$$default($$$internal$$publish, parent);
}
}
function $$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
$$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function $$$internal$$ErrorObject() {
this.error = null;
}
var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
$$$internal$$TRY_CATCH_ERROR.error = e;
return $$$internal$$TRY_CATCH_ERROR;
}
}
function $$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = $$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = $$$internal$$tryCatch(callback, detail);
if (value === $$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== $$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
$$$internal$$resolve(promise, value);
} else if (failed) {
$$$internal$$reject(promise, error);
} else if (settled === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, value);
} else if (settled === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
}
}
function $$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
$$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
$$$internal$$reject(promise, reason);
});
} catch(e) {
$$$internal$$reject(promise, e);
}
}
function $$$enumerator$$makeSettledResult(state, position, value) {
if (state === $$$internal$$FULFILLED) {
return {
state: 'fulfilled',
value: value
};
} else {
return {
state: 'rejected',
reason: value
};
}
}
function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor($$$internal$$noop, label);
this._abortOnReject = abortOnReject;
if (this._validateInput(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._init();
if (this.length === 0) {
$$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
$$$internal$$fulfill(this.promise, this._result);
}
}
} else {
$$$internal$$reject(this.promise, this._validationError());
}
}
$$$enumerator$$Enumerator.prototype._validateInput = function(input) {
return $$utils$$isArray(input);
};
$$$enumerator$$Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
$$$enumerator$$Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
var $$$enumerator$$default = $$$enumerator$$Enumerator;
$$$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var promise = this.promise;
var input = this._input;
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
$$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
if ($$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
entry._onerror = null;
this._settledAt(entry._state, i, entry._result);
} else {
this._willSettleAt(c.resolve(entry), i);
}
} else {
this._remaining--;
this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
}
};
$$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === $$$internal$$PENDING) {
this._remaining--;
if (this._abortOnReject && state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
} else {
this._result[i] = this._makeResult(state, i, value);
}
}
if (this._remaining === 0) {
$$$internal$$fulfill(promise, this._result);
}
};
$$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
return value;
};
$$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
$$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt($$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt($$$internal$$REJECTED, i, reason);
});
};
var $$promise$all$$default = function all(entries, label) {
return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
};
var $$promise$race$$default = function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
if (!$$utils$$isArray(entries)) {
$$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
$$$internal$$resolve(promise, value);
}
function onRejection(reason) {
$$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
$$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
};
var $$promise$resolve$$default = function resolve(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$resolve(promise, object);
return promise;
};
var $$promise$reject$$default = function reject(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$reject(promise, reason);
return promise;
};
var $$es6$promise$promise$$counter = 0;
function $$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function $$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise’s eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function $$es6$promise$promise$$Promise(resolver) {
this._id = $$es6$promise$promise$$counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if ($$$internal$$noop !== resolver) {
if (!$$utils$$isFunction(resolver)) {
$$es6$promise$promise$$needsResolver();
}
if (!(this instanceof $$es6$promise$promise$$Promise)) {
$$es6$promise$promise$$needsNew();
}
$$$internal$$initializePromise(this, resolver);
}
}
$$es6$promise$promise$$Promise.all = $$promise$all$$default;
$$es6$promise$promise$$Promise.race = $$promise$race$$default;
$$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default;
$$es6$promise$promise$$Promise.reject = $$promise$reject$$default;
$$es6$promise$promise$$Promise.prototype = {
constructor: $$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
return this;
}
var child = new this.constructor($$$internal$$noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
$$asap$$default(function(){
$$$internal$$invokeCallback(state, child, callback, result);
});
} else {
$$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
var $$es6$promise$polyfill$$default = function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return $$utils$$isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = $$es6$promise$promise$$default;
}
};
var es6$promise$umd$$ES6Promise = {
'Promise': $$es6$promise$promise$$default,
'polyfill': $$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = es6$promise$umd$$ES6Promise;
}
}).call(this);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":3}],3:[function(require,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
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; };
},{}],4:[function(require,module,exports){
var indexOf = require('./indexOf');
/**
* If array contains values.
*/
function contains(arr, val) {
return indexOf(arr, val) !== -1;
}
module.exports = contains;
},{"./indexOf":6}],5:[function(require,module,exports){
/**
* Array forEach
*/
function forEach(arr, callback, thisObj) {
if (arr == null) {
return;
}
var i = -1,
len = arr.length;
while (++i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if ( callback.call(thisObj, arr[i], i, arr) === false ) {
break;
}
}
}
module.exports = forEach;
},{}],6:[function(require,module,exports){
/**
* Array.indexOf
*/
function indexOf(arr, item, fromIndex) {
fromIndex = fromIndex || 0;
if (arr == null) {
return -1;
}
var len = arr.length,
i = fromIndex < 0 ? len + fromIndex : fromIndex;
while (i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if (arr[i] === item) {
return i;
}
i++;
}
return -1;
}
module.exports = indexOf;
},{}],7:[function(require,module,exports){
var indexOf = require('./indexOf');
/**
* Remove a single item from the array.
* (it won't remove duplicates, just a single item)
*/
function remove(arr, item){
var idx = indexOf(arr, item);
if (idx !== -1) arr.splice(idx, 1);
}
module.exports = remove;
},{"./indexOf":6}],8:[function(require,module,exports){
/**
* Create slice of source array or array-like object
*/
function slice(arr, start, end){
var len = arr.length;
if (start == null) {
start = 0;
} else if (start < 0) {
start = Math.max(len + start, 0);
} else {
start = Math.min(start, len);
}
if (end == null) {
end = len;
} else if (end < 0) {
end = Math.max(len + end, 0);
} else {
end = Math.min(end, len);
}
var result = [];
while (start < end) {
result.push(arr[start++]);
}
return result;
}
module.exports = slice;
},{}],9:[function(require,module,exports){
/**
* Merge sort (http://en.wikipedia.org/wiki/Merge_sort)
*/
function mergeSort(arr, compareFn) {
if (arr == null) {
return [];
} else if (arr.length < 2) {
return arr;
}
if (compareFn == null) {
compareFn = defaultCompare;
}
var mid, left, right;
mid = ~~(arr.length / 2);
left = mergeSort( arr.slice(0, mid), compareFn );
right = mergeSort( arr.slice(mid, arr.length), compareFn );
return merge(left, right, compareFn);
}
function defaultCompare(a, b) {
return a < b ? -1 : (a > b? 1 : 0);
}
function merge(left, right, compareFn) {
var result = [];
while (left.length && right.length) {
if (compareFn(left[0], right[0]) <= 0) {
// if 0 it should preserve same order (stable)
result.push(left.shift());
} else {
result.push(right.shift());
}
}
if (left.length) {
result.push.apply(result, left);
}
if (right.length) {
result.push.apply(result, right);
}
return result;
}
module.exports = mergeSort;
},{}],10:[function(require,module,exports){
/**
* Checks if the value is created by the `Object` constructor.
*/
function isPlainObject(value) {
return (!!value && typeof value === 'object' &&
value.constructor === Object);
}
module.exports = isPlainObject;
},{}],11:[function(require,module,exports){
/**
* Checks if the object is a primitive
*/
function isPrimitive(value) {
// Using switch fallthrough because it's simple to read and is
// generally fast: http://jsperf.com/testing-value-is-primitive/5
switch (typeof value) {
case "string":
case "number":
case "boolean":
return true;
}
return value == null;
}
module.exports = isPrimitive;
},{}],12:[function(require,module,exports){
/**
* Typecast a value to a String, using an empty string value for null or
* undefined.
*/
function toString(val){
return val == null ? '' : val.toString();
}
module.exports = toString;
},{}],13:[function(require,module,exports){
var forOwn = require('./forOwn');
var isPlainObject = require('../lang/isPlainObject');
/**
* Mixes objects into the target object, recursively mixing existing child
* objects.
*/
function deepMixIn(target, objects) {
var i = 0,
n = arguments.length,
obj;
while(++i < n){
obj = arguments[i];
if (obj) {
forOwn(obj, copyProp, target);
}
}
return target;
}
function copyProp(val, key) {
var existing = this[key];
if (isPlainObject(val) && isPlainObject(existing)) {
deepMixIn(existing, val);
} else {
this[key] = val;
}
}
module.exports = deepMixIn;
},{"../lang/isPlainObject":10,"./forOwn":15}],14:[function(require,module,exports){
var hasOwn = require('./hasOwn');
var _hasDontEnumBug,
_dontEnums;
function checkDontEnum(){
_dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
_hasDontEnumBug = true;
for (var key in {'toString': null}) {
_hasDontEnumBug = false;
}
}
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forIn(obj, fn, thisObj){
var key, i = 0;
// no need to check if argument is a real object that way we can use
// it for arrays, functions, date, etc.
//post-pone check till needed
if (_hasDontEnumBug == null) checkDontEnum();
for (key in obj) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
if (_hasDontEnumBug) {
var ctor = obj.constructor,
isProto = !!ctor && obj === ctor.prototype;
while (key = _dontEnums[i++]) {
// For constructor, if it is a prototype object the constructor
// is always non-enumerable unless defined otherwise (and
// enumerated above). For non-prototype objects, it will have
// to be defined on this object, since it cannot be defined on
// any prototype objects.
//
// For other [[DontEnum]] properties, check if the value is
// different than Object prototype value.
if (
(key !== 'constructor' ||
(!isProto && hasOwn(obj, key))) &&
obj[key] !== Object.prototype[key]
) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
}
}
}
function exec(fn, obj, key, thisObj){
return fn.call(thisObj, obj[key], key, obj);
}
module.exports = forIn;
},{"./hasOwn":17}],15:[function(require,module,exports){
var hasOwn = require('./hasOwn');
var forIn = require('./forIn');
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forOwn(obj, fn, thisObj){
forIn(obj, function(val, key){
if (hasOwn(obj, key)) {
return fn.call(thisObj, obj[key], key, obj);
}
});
}
module.exports = forOwn;
},{"./forIn":14,"./hasOwn":17}],16:[function(require,module,exports){
var isPrimitive = require('../lang/isPrimitive');
/**
* get "nested" object property
*/
function get(obj, prop){
var parts = prop.split('.'),
last = parts.pop();
while (prop = parts.shift()) {
obj = obj[prop];
if (obj == null) return;
}
return obj[last];
}
module.exports = get;
},{"../lang/isPrimitive":11}],17:[function(require,module,exports){
/**
* Safer Object.hasOwnProperty
*/
function hasOwn(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = hasOwn;
},{}],18:[function(require,module,exports){
var forEach = require('../array/forEach');
/**
* Create nested object if non-existent
*/
function namespace(obj, path){
if (!path) return obj;
forEach(path.split('.'), function(key){
if (!obj[key]) {
obj[key] = {};
}
obj = obj[key];
});
return obj;
}
module.exports = namespace;
},{"../array/forEach":5}],19:[function(require,module,exports){
var slice = require('../array/slice');
/**
* Return a copy of the object, filtered to only have values for the whitelisted keys.
*/
function pick(obj, var_keys){
var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1),
out = {},
i = 0, key;
while (key = keys[i++]) {
out[key] = obj[key];
}
return out;
}
module.exports = pick;
},{"../array/slice":8}],20:[function(require,module,exports){
var namespace = require('./namespace');
/**
* set "nested" object property
*/
function set(obj, prop, val){
var parts = (/^(.+)\.(.+)$/).exec(prop);
if (parts){
namespace(obj, parts[1])[parts[2]] = val;
} else {
obj[prop] = val;
}
}
module.exports = set;
},{"./namespace":18}],21:[function(require,module,exports){
var toString = require('../lang/toString');
var replaceAccents = require('./replaceAccents');
var removeNonWord = require('./removeNonWord');
var upperCase = require('./upperCase');
var lowerCase = require('./lowerCase');
/**
* Convert string to camelCase text.
*/
function camelCase(str){
str = toString(str);
str = replaceAccents(str);
str = removeNonWord(str)
.replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces
.replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE
.replace(/\s+/g, '') //remove spaces
.replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase
return str;
}
module.exports = camelCase;
},{"../lang/toString":12,"./lowerCase":22,"./removeNonWord":24,"./replaceAccents":25,"./upperCase":26}],22:[function(require,module,exports){
var toString = require('../lang/toString');
/**
* "Safer" String.toLowerCase()
*/
function lowerCase(str){
str = toString(str);
return str.toLowerCase();
}
module.exports = lowerCase;
},{"../lang/toString":12}],23:[function(require,module,exports){
var toString = require('../lang/toString');
var camelCase = require('./camelCase');
var upperCase = require('./upperCase');
/**
* camelCase + UPPERCASE first char
*/
function pascalCase(str){
str = toString(str);
return camelCase(str).replace(/^[a-z]/, upperCase);
}
module.exports = pascalCase;
},{"../lang/toString":12,"./camelCase":21,"./upperCase":26}],24:[function(require,module,exports){
var toString = require('../lang/toString');
// This pattern is generated by the _build/pattern-removeNonWord.js script
var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;
/**
* Remove non-word chars.
*/
function removeNonWord(str){
str = toString(str);
return str.replace(PATTERN, '');
}
module.exports = removeNonWord;
},{"../lang/toString":12}],25:[function(require,module,exports){
var toString = require('../lang/toString');
/**
* Replaces all accented chars with regular ones
*/
function replaceAccents(str){
str = toString(str);
// verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
}
module.exports = replaceAccents;
},{"../lang/toString":12}],26:[function(require,module,exports){
var toString = require('../lang/toString');
/**
* "Safer" String.toUpperCase()
*/
function upperCase(str){
str = toString(str);
return str.toUpperCase();
}
module.exports = upperCase;
},{"../lang/toString":12}],27:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function create(resourceName, attrs, options) {
var _this = this;
var definition = _this.definitions[resourceName];
options = options || {};
attrs = attrs || {};
var rejectionError;
if (!definition) {
rejectionError = new DSErrors.NER(resourceName);
} else if (!DSUtils.isObject(attrs)) {
rejectionError = new DSErrors.IA('"attrs" must be an object!');
} else {
options = DSUtils._(definition, options);
if (options.upsert && (DSUtils.isString(attrs[definition.idAttribute]) || DSUtils.isNumber(attrs[definition.idAttribute]))) {
return _this.update(resourceName, attrs[definition.idAttribute], attrs, options);
}
}
return new DSUtils.Promise(function (resolve, reject) {
if (rejectionError) {
reject(rejectionError);
} else {
resolve(attrs);
}
})
.then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.validate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.beforeCreate.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'beforeCreate', DSUtils.copy(attrs));
}
return _this.getAdapter(options).create(definition, attrs, options);
})
.then(function (attrs) {
return options.afterCreate.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'afterCreate', DSUtils.copy(attrs));
}
if (options.cacheResponse) {
var created = _this.inject(definition.name, attrs, options);
var id = created[definition.idAttribute];
_this.store[resourceName].completedQueries[id] = new Date().getTime();
return created;
} else {
return _this.createInstance(resourceName, attrs, options);
}
});
}
module.exports = create;
},{"../../errors":48,"../../utils":50}],28:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function destroy(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var item;
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
reject(new DSErrors.IA('"id" must be a string or a number!'));
} else {
item = _this.get(resourceName, id) || { id: id };
options = DSUtils._(definition, options);
resolve(item);
}
})
.then(function (attrs) {
return options.beforeDestroy.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'beforeDestroy', DSUtils.copy(attrs));
}
if (options.eagerEject) {
_this.eject(resourceName, id);
}
return _this.getAdapter(options).destroy(definition, id, options);
})
.then(function () {
return options.afterDestroy.call(item, options, item);
})
.then(function (item) {
if (options.notify) {
_this.emit(options, 'afterDestroy', DSUtils.copy(item));
}
_this.eject(resourceName, id);
return id;
})['catch'](function (err) {
if (options && options.eagerEject && item) {
_this.inject(resourceName, item, { notify: false });
}
throw err;
});
}
module.exports = destroy;
},{"../../errors":48,"../../utils":50}],29:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function destroyAll(resourceName, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var ejected, toEject;
params = params || {};
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isObject(params)) {
reject(new DSErrors.IA('"params" must be an object!'));
} else {
options = DSUtils._(definition, options);
resolve();
}
}).then(function () {
toEject = _this.defaults.defaultFilter.call(_this, resourceName, params);
return options.beforeDestroy(options, toEject);
}).then(function () {
if (options.notify) {
_this.emit(options, 'beforeDestroy', DSUtils.copy(toEject));
}
if (options.eagerEject) {
ejected = _this.ejectAll(resourceName, params);
}
return _this.getAdapter(options).destroyAll(definition, params, options);
}).then(function () {
return options.afterDestroy(options, toEject);
}).then(function () {
if (options.notify) {
_this.emit(options, 'afterDestroy', DSUtils.copy(toEject));
}
return ejected || _this.ejectAll(resourceName, params);
})['catch'](function (err) {
if (options && options.eagerEject && ejected) {
_this.inject(resourceName, ejected, { notify: false });
}
throw err;
});
}
module.exports = destroyAll;
},{"../../errors":48,"../../utils":50}],30:[function(require,module,exports){
/* jshint -W082 */
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function find(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
reject(new DSErrors.IA('"id" must be a string or a number!'));
} else {
options = DSUtils._(definition, options);
if (options.params) {
options.params = DSUtils.copy(options.params);
}
if (options.bypassCache || !options.cacheResponse) {
delete resource.completedQueries[id];
}
if (id in resource.completedQueries) {
resolve(_this.get(resourceName, id));
} else {
resolve();
}
}
}).then(function (item) {
if (!(id in resource.completedQueries)) {
if (!(id in resource.pendingQueries)) {
var promise;
var strategy = options.findStrategy || options.strategy;
if (strategy === 'fallback') {
function makeFallbackCall(index) {
return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)['catch'](function (err) {
index++;
if (index < options.fallbackAdapters.length) {
return makeFallbackCall(index);
} else {
return Promise.reject(err);
}
});
}
promise = makeFallbackCall(0);
} else {
promise = _this.getAdapter(options).find(definition, id, options);
}
resource.pendingQueries[id] = promise.then(function (data) {
// Query is no longer pending
delete resource.pendingQueries[id];
if (options.cacheResponse) {
resource.completedQueries[id] = new Date().getTime();
return _this.inject(resourceName, data, options);
} else {
return _this.createInstance(resourceName, data, options);
}
});
}
return resource.pendingQueries[id];
} else {
return item;
}
})['catch'](function (err) {
if (resource) {
delete resource.pendingQueries[id];
}
throw err;
});
}
module.exports = find;
},{"../../errors":48,"../../utils":50}],31:[function(require,module,exports){
/* jshint -W082 */
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function processResults(data, resourceName, queryHash, options) {
var _this = this;
var resource = _this.store[resourceName];
var idAttribute = _this.definitions[resourceName].idAttribute;
var date = new Date().getTime();
data = data || [];
// Query is no longer pending
delete resource.pendingQueries[queryHash];
resource.completedQueries[queryHash] = date;
// Update modified timestamp of collection
resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified);
// Merge the new values into the cache
var injected = _this.inject(resourceName, data, options);
// Make sure each object is added to completedQueries
if (DSUtils.isArray(injected)) {
DSUtils.forEach(injected, function (item) {
if (item && item[idAttribute]) {
resource.completedQueries[item[idAttribute]] = date;
}
});
} else {
options.errorFn('response is expected to be an array!');
resource.completedQueries[injected[idAttribute]] = date;
}
return injected;
}
function findAll(resourceName, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var queryHash;
return new DSUtils.Promise(function (resolve, reject) {
params = params || {};
if (!_this.definitions[resourceName]) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isObject(params)) {
reject(new DSErrors.IA('"params" must be an object!'));
} else {
options = DSUtils._(definition, options);
queryHash = DSUtils.toJson(params);
if (options.params) {
options.params = DSUtils.copy(options.params);
}
if (options.bypassCache || !options.cacheResponse) {
delete resource.completedQueries[queryHash];
delete resource.queryData[queryHash];
}
if (queryHash in resource.completedQueries) {
if (options.useFilter) {
resolve(_this.filter(resourceName, params, options));
} else {
resolve(resource.queryData[queryHash]);
}
} else {
resolve();
}
}
}).then(function (items) {
if (!(queryHash in resource.completedQueries)) {
if (!(queryHash in resource.pendingQueries)) {
var promise;
var strategy = options.findAllStrategy || options.strategy;
if (strategy === 'fallback') {
function makeFallbackCall(index) {
return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)['catch'](function (err) {
index++;
if (index < options.fallbackAdapters.length) {
return makeFallbackCall(index);
} else {
return Promise.reject(err);
}
});
}
promise = makeFallbackCall(0);
} else {
promise = _this.getAdapter(options).findAll(definition, params, options);
}
resource.pendingQueries[queryHash] = promise.then(function (data) {
delete resource.pendingQueries[queryHash];
if (options.cacheResponse) {
resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options);
resource.queryData[queryHash].$$injected = true;
return resource.queryData[queryHash];
} else {
DSUtils.forEach(data, function (item, i) {
data[i] = _this.createInstance(resourceName, item, options);
});
return data;
}
});
}
return resource.pendingQueries[queryHash];
} else {
return items;
}
})['catch'](function (err) {
if (resource) {
delete resource.pendingQueries[queryHash];
}
throw err;
});
}
module.exports = findAll;
},{"../../errors":48,"../../utils":50}],32:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function reap(resourceName, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else {
options = DSUtils._(definition, options);
if (!options.hasOwnProperty('notify')) {
options.notify = false;
}
var items = [];
var now = new Date().getTime();
var expiredItem;
while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) {
items.push(expiredItem.item);
delete expiredItem.item;
resource.expiresHeap.pop();
}
resolve(items);
}
}).then(function (items) {
if (options.isInterval || options.notify) {
definition.beforeReap(options, items);
_this.emit(options, 'beforeReap', DSUtils.copy(items));
}
if (options.reapAction === 'inject') {
DSUtils.forEach(items, function (item) {
var id = item[definition.idAttribute];
resource.expiresHeap.push({
item: item,
timestamp: resource.saved[id],
expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE
});
});
} else if (options.reapAction === 'eject') {
DSUtils.forEach(items, function (item) {
_this.eject(resourceName, item[definition.idAttribute]);
});
} else if (options.reapAction === 'refresh') {
var tasks = [];
DSUtils.forEach(items, function (item) {
tasks.push(_this.refresh(resourceName, item[definition.idAttribute]));
});
return DSUtils.Promise.all(tasks);
}
return items;
}).then(function (items) {
if (options.isInterval || options.notify) {
definition.afterReap(options, items);
_this.emit(options, 'afterReap', DSUtils.copy(items));
}
return items;
});
}
function refresh(resourceName, id, options) {
var _this = this;
return new DSUtils.Promise(function (resolve, reject) {
var definition = _this.definitions[resourceName];
id = DSUtils.resolveId(_this.definitions[resourceName], id);
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
reject(new DSErrors.IA('"id" must be a string or a number!'));
} else {
options = DSUtils._(definition, options);
options.bypassCache = true;
resolve(_this.get(resourceName, id));
}
}).then(function (item) {
if (item) {
return _this.find(resourceName, id, options);
} else {
return item;
}
});
}
module.exports = {
create: require('./create'),
destroy: require('./destroy'),
destroyAll: require('./destroyAll'),
find: require('./find'),
findAll: require('./findAll'),
loadRelations: require('./loadRelations'),
reap: reap,
refresh: refresh,
save: require('./save'),
update: require('./update'),
updateAll: require('./updateAll')
};
},{"../../errors":48,"../../utils":50,"./create":27,"./destroy":28,"./destroyAll":29,"./find":30,"./findAll":31,"./loadRelations":33,"./save":34,"./update":35,"./updateAll":36}],33:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function loadRelations(resourceName, instance, relations, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var fields = [];
return new DSUtils.Promise(function (resolve, reject) {
if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) {
instance = _this.get(resourceName, instance);
}
if (DSUtils.isString(relations)) {
relations = [relations];
}
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isObject(instance)) {
reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'));
} else if (!DSUtils.isArray(relations)) {
reject(new DSErrors.IA('"relations" must be a string or an array!'));
} else {
options = DSUtils._(definition, options);
if (!options.hasOwnProperty('findBelongsTo')) {
options.findBelongsTo = true;
}
if (!options.hasOwnProperty('findHasMany')) {
options.findHasMany = true;
}
var tasks = [];
DSUtils.forEach(definition.relationList, function (def) {
var relationName = def.relation;
if (DSUtils.contains(relations, relationName)) {
var task;
var params = {};
if (options.allowSimpleWhere) {
params[def.foreignKey] = instance[definition.idAttribute];
} else {
params.where = {};
params.where[def.foreignKey] = {
'==': instance[definition.idAttribute]
};
}
if (def.type === 'hasMany' && params[def.foreignKey]) {
task = _this.findAll(relationName, params, options);
} else if (def.type === 'hasOne') {
if (def.localKey && instance[def.localKey]) {
task = _this.find(relationName, instance[def.localKey], options);
} else if (def.foreignKey && params[def.foreignKey]) {
task = _this.findAll(relationName, params, options).then(function (hasOnes) {
return hasOnes.length ? hasOnes[0] : null;
});
}
} else if (instance[def.localKey]) {
task = _this.find(relationName, instance[def.localKey], options);
}
if (task) {
tasks.push(task);
fields.push(def.localField);
}
}
});
resolve(tasks);
}
})
.then(function (tasks) {
return DSUtils.Promise.all(tasks);
})
.then(function (loadedRelations) {
DSUtils.forEach(fields, function (field, index) {
instance[field] = loadedRelations[index];
});
return instance;
});
}
module.exports = loadRelations;
},{"../../errors":48,"../../utils":50}],34:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function save(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var item;
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
reject(new DSErrors.IA('"id" must be a string or a number!'));
} else if (!_this.get(resourceName, id)) {
reject(new DSErrors.R('id "' + id + '" not found in cache!'));
} else {
item = _this.get(resourceName, id);
options = DSUtils._(definition, options);
resolve(item);
}
}).then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.validate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'beforeUpdate', DSUtils.copy(attrs));
}
if (options.changesOnly) {
var resource = _this.store[resourceName];
if (DSUtils.w) {
resource.observers[id].deliver();
}
var toKeep = [];
var changes = _this.changes(resourceName, id);
for (var key in changes.added) {
toKeep.push(key);
}
for (key in changes.changed) {
toKeep.push(key);
}
changes = DSUtils.pick(attrs, toKeep);
if (DSUtils.isEmpty(changes)) {
// no changes, return
return attrs;
} else {
attrs = changes;
}
}
return _this.getAdapter(options).update(definition, id, attrs, options);
})
.then(function (data) {
return options.afterUpdate.call(data, options, data);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'afterUpdate', DSUtils.copy(attrs));
}
if (options.cacheResponse) {
return _this.inject(definition.name, attrs, options);
} else {
return _this.createInstance(resourceName, attrs, options);
}
});
}
module.exports = save;
},{"../../errors":48,"../../utils":50}],35:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function update(resourceName, id, attrs, options) {
var _this = this;
var definition = _this.definitions[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
reject(new DSErrors.IA('"id" must be a string or a number!'));
} else {
options = DSUtils._(definition, options);
resolve(attrs);
}
}).then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.validate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'beforeUpdate', DSUtils.copy(attrs));
}
return _this.getAdapter(options).update(definition, id, attrs, options);
})
.then(function (data) {
return options.afterUpdate.call(data, options, data);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'afterUpdate', DSUtils.copy(attrs));
}
if (options.cacheResponse) {
return _this.inject(definition.name, attrs, options);
} else {
return _this.createInstance(resourceName, attrs, options);
}
});
}
module.exports = update;
},{"../../errors":48,"../../utils":50}],36:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function updateAll(resourceName, attrs, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else {
options = DSUtils._(definition, options);
resolve(attrs);
}
}).then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.validate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
})
.then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
})
.then(function (attrs) {
if (options.notify) {
_this.emit(options, 'beforeUpdate', DSUtils.copy(attrs));
}
return _this.getAdapter(options).updateAll(definition, attrs, params, options);
})
.then(function (data) {
return options.afterUpdate.call(data, options, data);
})
.then(function (data) {
if (options.notify) {
_this.emit(options, 'afterUpdate', DSUtils.copy(attrs));
}
if (options.cacheResponse) {
return _this.inject(definition.name, data, options);
} else {
var instances = [];
DSUtils.forEach(data, function (item) {
instances.push(_this.createInstance(resourceName, item, options));
});
return instances;
}
});
}
module.exports = updateAll;
},{"../../errors":48,"../../utils":50}],37:[function(require,module,exports){
var DSUtils = require('../utils');
var DSErrors = require('../errors');
var syncMethods = require('./sync_methods');
var asyncMethods = require('./async_methods');
var Schemator;
function lifecycleNoopCb(resource, attrs, cb) {
cb(null, attrs);
}
function lifecycleNoop(resource, attrs) {
return attrs;
}
function compare(orderBy, index, a, b) {
var def = orderBy[index];
var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]);
if (DSUtils.isString(cA)) {
cA = DSUtils.upperCase(cA);
}
if (DSUtils.isString(cB)) {
cB = DSUtils.upperCase(cB);
}
if (def[1] === 'DESC') {
if (cB < cA) {
return -1;
} else if (cB > cA) {
return 1;
} else {
if (index < orderBy.length - 1) {
return compare(orderBy, index + 1, a, b);
} else {
return 0;
}
}
} else {
if (cA < cB) {
return -1;
} else if (cA > cB) {
return 1;
} else {
if (index < orderBy.length - 1) {
return compare(orderBy, index + 1, a, b);
} else {
return 0;
}
}
}
}
function Defaults() {
}
var defaultsPrototype = Defaults.prototype;
defaultsPrototype.actions = {};
defaultsPrototype.afterCreate = lifecycleNoopCb;
defaultsPrototype.afterCreateInstance = lifecycleNoop;
defaultsPrototype.afterDestroy = lifecycleNoopCb;
defaultsPrototype.afterEject = lifecycleNoop;
defaultsPrototype.afterInject = lifecycleNoop;
defaultsPrototype.afterReap = lifecycleNoop;
defaultsPrototype.afterUpdate = lifecycleNoopCb;
defaultsPrototype.afterValidate = lifecycleNoopCb;
defaultsPrototype.allowSimpleWhere = true;
defaultsPrototype.basePath = '';
defaultsPrototype.beforeCreate = lifecycleNoopCb;
defaultsPrototype.beforeCreateInstance = lifecycleNoop;
defaultsPrototype.beforeDestroy = lifecycleNoopCb;
defaultsPrototype.beforeEject = lifecycleNoop;
defaultsPrototype.beforeInject = lifecycleNoop;
defaultsPrototype.beforeReap = lifecycleNoop;
defaultsPrototype.beforeUpdate = lifecycleNoopCb;
defaultsPrototype.beforeValidate = lifecycleNoopCb;
defaultsPrototype.bypassCache = false;
defaultsPrototype.cacheResponse = !!DSUtils.w;
defaultsPrototype.defaultAdapter = 'http';
defaultsPrototype.debug = true;
defaultsPrototype.eagerEject = false;
// TODO: Implement eagerInject in DS#create
defaultsPrototype.eagerInject = false;
defaultsPrototype.endpoint = '';
defaultsPrototype.error = console ? function (a, b, c) {
console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c);
} : false;
defaultsPrototype.errorFn = function (a, b) {
if (this.error && typeof this.error === 'function') {
try {
if (typeof a === 'string') {
throw new Error(a);
} else {
throw a;
}
} catch (err) {
a = err;
}
this.error(this.name || null, a || null, b || null);
}
};
defaultsPrototype.fallbackAdapters = ['http'];
defaultsPrototype.findBelongsTo = true;
defaultsPrototype.findHasOne = true;
defaultsPrototype.findHasMany = true;
defaultsPrototype.findInverseLinks = true;
defaultsPrototype.idAttribute = 'id';
defaultsPrototype.ignoredChanges = [/\$/];
defaultsPrototype.ignoreMissing = false;
defaultsPrototype.keepChangeHistory = false;
defaultsPrototype.loadFromServer = false;
defaultsPrototype.log = console ? function (a, b, c, d, e) {
console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e);
} : false;
defaultsPrototype.logFn = function (a, b, c, d) {
if (this.debug && this.log && typeof this.log === 'function') {
this.log(this.name || null, a || null, b || null, c || null, d || null);
}
};
defaultsPrototype.maxAge = false;
defaultsPrototype.notify = !!DSUtils.w;
defaultsPrototype.reapAction = !!DSUtils.w ? 'inject' : 'none';
defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false;
defaultsPrototype.resetHistoryOnInject = true;
defaultsPrototype.strategy = 'single';
defaultsPrototype.upsert = !!DSUtils.w;
defaultsPrototype.useClass = true;
defaultsPrototype.useFilter = false;
defaultsPrototype.validate = lifecycleNoopCb;
defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) {
var _this = this;
var filtered = collection;
var where = null;
var reserved = {
skip: '',
offset: '',
where: '',
limit: '',
orderBy: '',
sort: ''
};
params = params || {};
options = options || {};
if (DSUtils.isObject(params.where)) {
where = params.where;
} else {
where = {};
}
if (options.allowSimpleWhere) {
DSUtils.forOwn(params, function (value, key) {
if (!(key in reserved) && !(key in where)) {
where[key] = {
'==': value
};
}
});
}
if (DSUtils.isEmpty(where)) {
where = null;
}
if (where) {
filtered = DSUtils.filter(filtered, function (attrs) {
var first = true;
var keep = true;
DSUtils.forOwn(where, function (clause, field) {
if (DSUtils.isString(clause)) {
clause = {
'===': clause
};
} else if (DSUtils.isNumber(clause) || DSUtils.isBoolean(clause)) {
clause = {
'==': clause
};
}
if (DSUtils.isObject(clause)) {
DSUtils.forOwn(clause, function (term, op) {
var expr;
var isOr = op[0] === '|';
var val = attrs[field];
op = isOr ? op.substr(1) : op;
if (op === '==') {
expr = val == term;
} else if (op === '===') {
expr = val === term;
} else if (op === '!=') {
expr = val != term;
} else if (op === '!==') {
expr = val !== term;
} else if (op === '>') {
expr = val > term;
} else if (op === '>=') {
expr = val >= term;
} else if (op === '<') {
expr = val < term;
} else if (op === '<=') {
expr = val <= term;
} else if (op === 'isectEmpty') {
expr = !DSUtils.intersection((val || []), (term || [])).length;
} else if (op === 'isectNotEmpty') {
expr = DSUtils.intersection((val || []), (term || [])).length;
} else if (op === 'in') {
if (DSUtils.isString(term)) {
expr = term.indexOf(val) !== -1;
} else {
expr = DSUtils.contains(term, val);
}
} else if (op === 'notIn') {
if (DSUtils.isString(term)) {
expr = term.indexOf(val) === -1;
} else {
expr = !DSUtils.contains(term, val);
}
} else if (op === 'contains') {
if (DSUtils.isString(val)) {
expr = val.indexOf(term) !== -1;
} else {
expr = DSUtils.contains(val, term);
}
} else if (op === 'notContains') {
if (DSUtils.isString(val)) {
expr = val.indexOf(term) === -1;
} else {
expr = !DSUtils.contains(val, term);
}
}
if (expr !== undefined) {
keep = first ? expr : (isOr ? keep || expr : keep && expr);
}
first = false;
});
}
});
return keep;
});
}
var orderBy = null;
if (DSUtils.isString(params.orderBy)) {
orderBy = [
[params.orderBy, 'ASC']
];
} else if (DSUtils.isArray(params.orderBy)) {
orderBy = params.orderBy;
}
if (!orderBy && DSUtils.isString(params.sort)) {
orderBy = [
[params.sort, 'ASC']
];
} else if (!orderBy && DSUtils.isArray(params.sort)) {
orderBy = params.sort;
}
// Apply 'orderBy'
if (orderBy) {
var index = 0;
DSUtils.forEach(orderBy, function (def, i) {
if (DSUtils.isString(def)) {
orderBy[i] = [def, 'ASC'];
} else if (!DSUtils.isArray(def)) {
throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + DSUtils.toJson(def) + ': Must be a string or an array!', {
params: {
'orderBy[i]': {
actual: typeof def,
expected: 'string|array'
}
}
});
}
});
filtered = DSUtils.sort(filtered, function (a, b) {
return compare(orderBy, index, a, b);
});
}
var limit = DSUtils.isNumber(params.limit) ? params.limit : null;
var skip = null;
if (DSUtils.isNumber(params.skip)) {
skip = params.skip;
} else if (DSUtils.isNumber(params.offset)) {
skip = params.offset;
}
// Apply 'limit' and 'skip'
if (limit && skip) {
filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit));
} else if (DSUtils.isNumber(limit)) {
filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit));
} else if (DSUtils.isNumber(skip)) {
if (skip < filtered.length) {
filtered = DSUtils.slice(filtered, skip);
} else {
filtered = [];
}
}
return filtered;
};
function DS(options) {
var _this = this;
options = options || {};
try {
Schemator = require('js-data-schema');
} catch (e) {
}
if (!Schemator) {
try {
Schemator = window.Schemator;
} catch (e) {
}
}
if (Schemator || options.schemator) {
_this.schemator = options.schemator || new Schemator();
}
_this.store = {};
_this.definitions = {};
_this.adapters = {};
_this.defaults = new Defaults();
_this.observe = DSUtils.observe;
DSUtils.forOwn(options, function (v, k) {
_this.defaults[k] = v;
});
}
var dsPrototype = DS.prototype;
dsPrototype.getAdapter = function (options) {
var errorIfNotExist = false;
options = options || {};
if (DSUtils.isString(options)) {
errorIfNotExist = true;
options = {
adapter: options
};
}
var adapter = this.adapters[options.adapter];
if (adapter) {
return adapter;
} else if (errorIfNotExist) {
throw new Error(options.adapter + ' is not a registered adapter!');
} else {
return this.adapters[options.defaultAdapter];
}
};
dsPrototype.registerAdapter = function (name, Adapter, options) {
var _this = this;
options = options || {};
if (DSUtils.isFunction(Adapter)) {
_this.adapters[name] = new Adapter(options);
} else {
_this.adapters[name] = Adapter;
}
if (options.default) {
_this.defaults.defaultAdapter = name;
}
};
dsPrototype.emit = function (definition, event) {
var args = Array.prototype.slice.call(arguments, 2);
args.unshift(definition.name);
args.unshift('DS.' + event);
definition.emit.apply(definition, args);
};
dsPrototype.errors = require('../errors');
dsPrototype.utils = DSUtils;
DSUtils.deepMixIn(dsPrototype, syncMethods);
DSUtils.deepMixIn(dsPrototype, asyncMethods);
module.exports = DS;
},{"../errors":48,"../utils":50,"./async_methods":32,"./sync_methods":42,"js-data-schema":"js-data-schema"}],38:[function(require,module,exports){
/*jshint evil:true, loopfunc:true*/
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function Resource(options) {
DSUtils.deepMixIn(this, options);
if ('endpoint' in options) {
this.endpoint = options.endpoint;
} else {
this.endpoint = this.name;
}
}
var instanceMethods = [
'compute',
'refresh',
'save',
'update',
'destroy',
'loadRelations',
'changeHistory',
'changes',
'hasChanges',
'lastModified',
'lastSaved',
'link',
'linkInverse',
'previous',
'unlinkInverse'
];
function defineResource(definition) {
var _this = this;
var definitions = _this.definitions;
if (DSUtils.isString(definition)) {
definition = {
name: definition.replace(/\s/gi, '')
};
}
if (!DSUtils.isObject(definition)) {
throw new DSErrors.IA('"definition" must be an object!');
} else if (!DSUtils.isString(definition.name)) {
throw new DSErrors.IA('"name" must be a string!');
} else if (_this.store[definition.name]) {
throw new DSErrors.R(definition.name + ' is already registered!');
}
try {
// Inherit from global defaults
Resource.prototype = _this.defaults;
definitions[definition.name] = new Resource(definition);
var def = definitions[definition.name];
if (!DSUtils.isString(def.idAttribute)) {
throw new DSErrors.IA('"idAttribute" must be a string!');
}
// Setup nested parent configuration
if (def.relations) {
def.relationList = [];
def.relationFields = [];
DSUtils.forOwn(def.relations, function (relatedModels, type) {
DSUtils.forOwn(relatedModels, function (defs, relationName) {
if (!DSUtils.isArray(defs)) {
relatedModels[relationName] = [defs];
}
DSUtils.forEach(relatedModels[relationName], function (d) {
d.type = type;
d.relation = relationName;
d.name = def.name;
def.relationList.push(d);
def.relationFields.push(d.localField);
});
});
});
if (def.relations.belongsTo) {
DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) {
DSUtils.forEach(relatedModel, function (relation) {
if (relation.parent) {
def.parent = modelName;
def.parentKey = relation.localKey;
def.parentField = relation.localField;
}
});
});
}
if (typeof Object.freeze === 'function') {
Object.freeze(def.relations);
Object.freeze(def.relationList);
}
}
def.getEndpoint = function (id, options) {
options.params = options.params || {};
var item;
var parentKey = def.parentKey;
var endpoint = options.hasOwnProperty('endpoint') ? options.endpoint : def.endpoint;
var parentField = def.parentField;
var parentDef = definitions[def.parent];
var parentId = options.params[parentKey];
if (parentId === false || !parentKey || !parentDef) {
if (parentId === false) {
delete options.params[parentKey];
}
return endpoint;
} else {
delete options.params[parentKey];
if (DSUtils.isNumber(id) || DSUtils.isString(id)) {
item = def.get(id);
} else if (DSUtils.isObject(id)) {
item = id;
}
if (item) {
parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null);
}
if (parentId) {
delete options.endpoint;
var _options = {};
DSUtils.forOwn(options, function (value, key) {
_options[key] = value;
});
return DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint);
} else {
return endpoint;
}
}
};
// Remove this in v0.11.0 and make a breaking change notice
// the the `filter` option has been renamed to `defaultFilter`
if (def.filter) {
def.defaultFilter = def.filter;
delete def.filter;
}
// Create the wrapper class for the new resource
def['class'] = DSUtils.pascalCase(definition.name);
try {
eval('function ' + def['class'] + '() {}');
def[def['class']] = eval(def['class']);
} catch (e) {
def[def['class']] = function () {
};
}
// Apply developer-defined methods
if (def.methods) {
DSUtils.deepMixIn(def[def['class']].prototype, def.methods);
}
def[def['class']].prototype.set = function (key, value) {
DSUtils.set(this, key, value);
var observer = _this.store[def.name].observers[this[def.idAttribute]];
if (observer && !DSUtils.observe.hasObjectObserve) {
observer.deliver();
} else {
_this.compute(def.name, this);
}
return this;
};
def[def['class']].prototype.get = function (key) {
return DSUtils.get(this, key);
};
// Prepare for computed properties
if (def.computed) {
DSUtils.forOwn(def.computed, function (fn, field) {
if (DSUtils.isFunction(fn)) {
def.computed[field] = [fn];
fn = def.computed[field];
}
if (def.methods && field in def.methods) {
def.errorFn('Computed property "' + field + '" conflicts with previously defined prototype method!');
}
var deps;
if (fn.length === 1) {
var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);
deps = match[1].split(',');
def.computed[field] = deps.concat(fn);
fn = def.computed[field];
if (deps.length) {
def.errorFn('Use the computed property array syntax for compatibility with minified code!');
}
}
deps = fn.slice(0, fn.length - 1);
DSUtils.forEach(deps, function (val, index) {
deps[index] = val.trim();
});
fn.deps = DSUtils.filter(deps, function (dep) {
return !!dep;
});
});
}
if (definition.schema && _this.schemator) {
def.schema = _this.schemator.defineSchema(def.name, definition.schema);
if (!definition.hasOwnProperty('validate')) {
def.validate = function (resourceName, attrs, cb) {
def.schema.validate(attrs, {
ignoreMissing: def.ignoreMissing
}, function (err) {
if (err) {
return cb(err);
} else {
return cb(null, attrs);
}
});
};
}
}
DSUtils.forEach(instanceMethods, function (name) {
def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(this[def.idAttribute] || this);
args.unshift(def.name);
return _this[name].apply(_this, args);
};
});
def[def['class']].prototype.DSCreate = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
args.unshift(def.name);
return _this.create.apply(_this, args);
};
// Initialize store data for the new resource
_this.store[def.name] = {
collection: [],
expiresHeap: new DSUtils.DSBinaryHeap(function (x) {
return x.expires;
}, function (x, y) {
return x.item === y;
}),
completedQueries: {},
queryData: {},
pendingQueries: {},
index: {},
modified: {},
saved: {},
previousAttributes: {},
observers: {},
changeHistories: {},
changeHistory: [],
collectionModified: 0
};
if (def.reapInterval) {
setInterval(function () {
_this.reap(def.name, { isInterval: true });
}, def.reapInterval);
}
// Proxy DS methods with shorthand ones
for (var key in _this) {
if (typeof _this[key] === 'function' && key !== 'defineResource') {
(function (k) {
def[k] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(def.name);
return _this[k].apply(_this, args);
};
})(key);
}
}
def.beforeValidate = DSUtils.promisify(def.beforeValidate);
def.validate = DSUtils.promisify(def.validate);
def.afterValidate = DSUtils.promisify(def.afterValidate);
def.beforeCreate = DSUtils.promisify(def.beforeCreate);
def.afterCreate = DSUtils.promisify(def.afterCreate);
def.beforeUpdate = DSUtils.promisify(def.beforeUpdate);
def.afterUpdate = DSUtils.promisify(def.afterUpdate);
def.beforeDestroy = DSUtils.promisify(def.beforeDestroy);
def.afterDestroy = DSUtils.promisify(def.afterDestroy);
DSUtils.forOwn(def.actions, function addAction(action, name) {
if (def[name]) {
throw new Error('Cannot override existing method "' + name + '"!');
}
def[name] = function (options) {
options = options || {};
var config = DSUtils.deepMixIn({}, action);
if (!options.hasOwnProperty('endpoint') && config.endpoint) {
options.endpoint = config.endpoint;
}
if (typeof options.getEndpoint === 'function') {
config.url = options.getEndpoint(def, options);
} else {
config.url = DSUtils.makePath(def.getEndpoint(null, options), name);
}
config.method = config.method || 'GET';
DSUtils.deepMixIn(config, options);
return _this.getAdapter(action.adapter || 'http').HTTP(config);
};
});
// Mix-in events
DSUtils.Events(def);
return def;
} catch (err) {
delete definitions[definition.name];
delete _this.store[definition.name];
throw err;
}
}
module.exports = defineResource;
},{"../../errors":48,"../../utils":50}],39:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function eject(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var item;
var found = false;
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new DSErrors.IA('"id" must be a string or a number!');
}
options = DSUtils._(definition, options);
for (var i = 0; i < resource.collection.length; i++) {
if (resource.collection[i][definition.idAttribute] == id) {
item = resource.collection[i];
resource.expiresHeap.remove(item);
found = true;
break;
}
}
if (found) {
if (options.notify) {
definition.beforeEject(options, item);
_this.emit(options, 'beforeEject', DSUtils.copy(item));
}
_this.unlinkInverse(definition.name, id);
resource.collection.splice(i, 1);
if (DSUtils.w) {
resource.observers[id].close();
}
delete resource.observers[id];
delete resource.index[id];
delete resource.previousAttributes[id];
delete resource.completedQueries[id];
delete resource.pendingQueries[id];
DSUtils.forEach(resource.changeHistories[id], function (changeRecord) {
DSUtils.remove(resource.changeHistory, changeRecord);
});
DSUtils.forOwn(resource.queryData, function (items) {
if (items.$$injected) {
DSUtils.remove(items, item);
}
});
delete resource.changeHistories[id];
delete resource.modified[id];
delete resource.saved[id];
resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified);
if (options.notify) {
definition.afterEject(options, item);
_this.emit(options, 'afterEject', DSUtils.copy(item));
}
return item;
}
}
module.exports = eject;
},{"../../errors":48,"../../utils":50}],40:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function ejectAll(resourceName, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
params = params || {};
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isObject(params)) {
throw new DSErrors.IA('"params" must be an object!');
}
var resource = _this.store[resourceName];
if (DSUtils.isEmpty(params)) {
resource.completedQueries = {};
}
var queryHash = DSUtils.toJson(params);
var items = _this.filter(definition.name, params);
var ids = [];
DSUtils.forEach(items, function (item) {
if (item && item[definition.idAttribute]) {
ids.push(item[definition.idAttribute]);
}
});
DSUtils.forEach(ids, function (id) {
_this.eject(definition.name, id, options);
});
delete resource.completedQueries[queryHash];
resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified);
return items;
}
module.exports = ejectAll;
},{"../../errors":48,"../../utils":50}],41:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function filter(resourceName, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (params && !DSUtils.isObject(params)) {
throw new DSErrors.IA('"params" must be an object!');
}
options = DSUtils._(definition, options);
// Protect against null
params = params || {};
var queryHash = DSUtils.toJson(params);
if (!(queryHash in resource.completedQueries) && options.loadFromServer) {
// This particular query has never been completed
if (!resource.pendingQueries[queryHash]) {
// This particular query has never even been started
_this.findAll(resourceName, params, options);
}
}
return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options);
}
module.exports = filter;
},{"../../errors":48,"../../utils":50}],42:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
var NER = DSErrors.NER;
var IA = DSErrors.IA;
var R = DSErrors.R;
function changes(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
options = options || {};
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new IA('"id" must be a string or a number!');
}
options = DSUtils._(definition, options);
var item = _this.get(resourceName, id);
if (item) {
if (DSUtils.w) {
_this.store[resourceName].observers[id].deliver();
}
var diff = DSUtils.diffObjectFromOldObject(item, _this.store[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges);
DSUtils.forOwn(diff, function (changeset, name) {
var toKeep = [];
DSUtils.forOwn(changeset, function (value, field) {
if (!DSUtils.isFunction(value)) {
toKeep.push(field);
}
});
diff[name] = DSUtils.pick(diff[name], toKeep);
});
DSUtils.forEach(definition.relationFields, function (field) {
delete diff.added[field];
delete diff.removed[field];
delete diff.changed[field];
});
return diff;
}
}
function changeHistory(resourceName, id) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
id = DSUtils.resolveId(definition, id);
if (resourceName && !_this.definitions[resourceName]) {
throw new NER(resourceName);
} else if (id && !DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new IA('"id" must be a string or a number!');
}
if (!definition.keepChangeHistory) {
definition.errorFn('changeHistory is disabled for this resource!');
} else {
if (resourceName) {
var item = _this.get(resourceName, id);
if (item) {
return resource.changeHistories[id];
}
} else {
return resource.changeHistory;
}
}
}
function compute(resourceName, instance) {
var _this = this;
var definition = _this.definitions[resourceName];
instance = DSUtils.resolveItem(_this.store[resourceName], instance);
if (!definition) {
throw new NER(resourceName);
} else if (!instance) {
throw new R('Item not in the store!');
} else if (!DSUtils.isObject(instance) && !DSUtils.isString(instance) && !DSUtils.isNumber(instance)) {
throw new IA('"instance" must be an object, string or number!');
}
DSUtils.forOwn(definition.computed, function (fn, field) {
DSUtils.compute.call(instance, fn, field);
});
return instance;
}
function createInstance(resourceName, attrs, options) {
var definition = this.definitions[resourceName];
var item;
attrs = attrs || {};
if (!definition) {
throw new NER(resourceName);
} else if (attrs && !DSUtils.isObject(attrs)) {
throw new IA('"attrs" must be an object!');
}
options = DSUtils._(definition, options);
if (options.notify) {
options.beforeCreateInstance(options, attrs);
}
if (options.useClass) {
var Constructor = definition[definition.class];
item = new Constructor();
} else {
item = {};
}
DSUtils.deepMixIn(item, attrs);
if (options.notify) {
options.afterCreateInstance(options, attrs);
}
return item;
}
function diffIsEmpty(diff) {
return !(DSUtils.isEmpty(diff.added) &&
DSUtils.isEmpty(diff.removed) &&
DSUtils.isEmpty(diff.changed));
}
function digest() {
this.observe.Platform.performMicrotaskCheckpoint();
}
function get(resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
if (!definition) {
throw new NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new IA('"id" must be a string or a number!');
}
options = DSUtils._(definition, options);
// cache miss, request resource from server
var item = _this.store[resourceName].index[id];
if (!item && options.loadFromServer) {
_this.find(resourceName, id, options);
}
// return resource from cache
return item;
}
function getAll(resourceName, ids) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var collection = [];
if (!definition) {
throw new NER(resourceName);
} else if (ids && !DSUtils.isArray(ids)) {
throw new IA('"ids" must be an array!');
}
if (DSUtils.isArray(ids)) {
var length = ids.length;
for (var i = 0; i < length; i++) {
if (resource.index[ids[i]]) {
collection.push(resource.index[ids[i]]);
}
}
} else {
collection = resource.collection.slice();
}
return collection;
}
function hasChanges(resourceName, id) {
var _this = this;
var definition = _this.definitions[resourceName];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new IA('"id" must be a string or a number!');
}
// return resource from cache
if (_this.get(resourceName, id)) {
return diffIsEmpty(_this.changes(resourceName, id));
} else {
return false;
}
}
function lastModified(resourceName, id) {
var definition = this.definitions[resourceName];
var resource = this.store[resourceName];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
}
if (id) {
if (!(id in resource.modified)) {
resource.modified[id] = 0;
}
return resource.modified[id];
}
return resource.collectionModified;
}
function lastSaved(resourceName, id) {
var definition = this.definitions[resourceName];
var resource = this.store[resourceName];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
}
if (!(id in resource.saved)) {
resource.saved[id] = 0;
}
return resource.saved[id];
}
function previous(resourceName, id) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new IA('"id" must be a string or a number!');
}
// return resource from cache
return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined;
}
module.exports = {
changes: changes,
changeHistory: changeHistory,
compute: compute,
createInstance: createInstance,
defineResource: require('./defineResource'),
digest: digest,
eject: require('./eject'),
ejectAll: require('./ejectAll'),
filter: require('./filter'),
get: get,
getAll: getAll,
hasChanges: hasChanges,
inject: require('./inject'),
lastModified: lastModified,
lastSaved: lastSaved,
link: require('./link'),
linkAll: require('./linkAll'),
linkInverse: require('./linkInverse'),
previous: previous,
unlinkInverse: require('./unlinkInverse')
};
},{"../../errors":48,"../../utils":50,"./defineResource":38,"./eject":39,"./ejectAll":40,"./filter":41,"./inject":43,"./link":44,"./linkAll":45,"./linkInverse":46,"./unlinkInverse":47}],43:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function _getReactFunction(DS, definition, resource) {
var name = definition.name;
return function _react(added, removed, changed, oldValueFn, firstTime) {
var target = this;
var item;
var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute];
DSUtils.forEach(definition.relationFields, function (field) {
delete added[field];
delete removed[field];
delete changed[field];
});
if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) {
item = DS.get(name, innerId);
resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]);
resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified);
if (definition.keepChangeHistory) {
var changeRecord = {
resourceName: name,
target: item,
added: added,
removed: removed,
changed: changed,
timestamp: resource.modified[innerId]
};
resource.changeHistories[innerId].push(changeRecord);
resource.changeHistory.push(changeRecord);
}
}
if (definition.computed) {
item = item || DS.get(name, innerId);
DSUtils.forOwn(definition.computed, function (fn, field) {
var compute = false;
// check if required fields changed
DSUtils.forEach(fn.deps, function (dep) {
if (dep in added || dep in removed || dep in changed || !(field in item)) {
compute = true;
}
});
compute = compute || !fn.deps.length;
if (compute) {
DSUtils.compute.call(item, fn, field);
}
});
}
if (definition.relations) {
item = item || DS.get(name, innerId);
DSUtils.forEach(definition.relationList, function (def) {
if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) {
DS.link(name, item[definition.idAttribute], [def.relation]);
}
});
}
if (definition.idAttribute in changed) {
definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "' + name +
'" resource is now in an undefined (probably broken) state.');
}
};
}
function _inject(definition, resource, attrs, options) {
var _this = this;
var _react = _getReactFunction(_this, definition, resource, attrs, options);
var injected;
if (DSUtils.isArray(attrs)) {
injected = [];
for (var i = 0; i < attrs.length; i++) {
injected.push(_inject.call(_this, definition, resource, attrs[i], options));
}
} else {
// check if "idAttribute" is a computed property
var c = definition.computed;
var idA = definition.idAttribute;
if (c && c[idA]) {
var args = [];
DSUtils.forEach(c[idA].deps, function (dep) {
args.push(attrs[dep]);
});
attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args);
}
if (!(idA in attrs)) {
var error = new DSErrors.R(definition.name + '.inject: "attrs" must contain the property specified by `idAttribute`!');
options.errorFn(error);
throw error;
} else {
try {
DSUtils.forEach(definition.relationList, function (def) {
var relationName = def.relation;
var relationDef = _this.definitions[relationName];
var toInject = attrs[def.localField];
if (toInject) {
if (!relationDef) {
throw new DSErrors.R(definition.name + ' relation is defined but the resource is not!');
}
if (DSUtils.isArray(toInject)) {
var items = [];
DSUtils.forEach(toInject, function (toInjectItem) {
if (toInjectItem !== _this.store[relationName][toInjectItem[relationDef.idAttribute]]) {
try {
var injectedItem = _this.inject(relationName, toInjectItem, options);
if (def.foreignKey) {
injectedItem[def.foreignKey] = attrs[definition.idAttribute];
}
items.push(injectedItem);
} catch (err) {
options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!');
}
}
});
attrs[def.localField] = items;
} else {
if (toInject !== _this.store[relationName][toInject[relationDef.idAttribute]]) {
try {
attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options);
if (def.foreignKey) {
attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute];
}
} catch (err) {
options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!');
}
}
}
}
});
var id = attrs[idA];
var item = _this.get(definition.name, id);
var initialLastModified = item ? resource.modified[id] : 0;
if (!item) {
if (options.useClass) {
if (attrs instanceof definition[definition['class']]) {
item = attrs;
} else {
item = new definition[definition['class']]();
}
} else {
item = {};
}
resource.previousAttributes[id] = DSUtils.copy(attrs);
DSUtils.deepMixIn(item, attrs);
resource.collection.push(item);
resource.changeHistories[id] = [];
if (DSUtils.w) {
resource.observers[id] = new _this.observe.ObjectObserver(item);
resource.observers[id].open(_react, item);
}
resource.index[id] = item;
_react.call(item, {}, {}, {}, null, true);
} else {
DSUtils.deepMixIn(item, attrs);
if (definition.resetHistoryOnInject) {
resource.previousAttributes[id] = {};
DSUtils.deepMixIn(resource.previousAttributes[id], attrs);
if (resource.changeHistories[id].length) {
DSUtils.forEach(resource.changeHistories[id], function (changeRecord) {
DSUtils.remove(resource.changeHistory, changeRecord);
});
resource.changeHistories[id].splice(0, resource.changeHistories[id].length);
}
}
if (DSUtils.w) {
resource.observers[id].deliver();
}
}
resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]);
resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id];
resource.expiresHeap.remove(item);
resource.expiresHeap.push({
item: item,
timestamp: resource.saved[id],
expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE
});
injected = item;
} catch (err) {
options.errorFn(err, attrs);
}
}
}
return injected;
}
function _link(definition, injected, options) {
var _this = this;
DSUtils.forEach(definition.relationList, function (def) {
if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) {
_this.link(definition.name, injected[definition.idAttribute], [def.relation]);
} else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) {
_this.link(definition.name, injected[definition.idAttribute], [def.relation]);
}
});
}
function inject(resourceName, attrs, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var injected;
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isObject(attrs) && !DSUtils.isArray(attrs)) {
throw new DSErrors.IA(resourceName + '.inject: "attrs" must be an object or an array!');
}
var name = definition.name;
options = DSUtils._(definition, options);
if (options.notify) {
options.beforeInject(options, attrs);
_this.emit(options, 'beforeInject', DSUtils.copy(attrs));
}
injected = _inject.call(_this, definition, resource, attrs, options);
resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified);
if (options.findInverseLinks) {
if (DSUtils.isArray(injected)) {
if (injected.length) {
_this.linkInverse(name, injected[0][definition.idAttribute]);
}
} else {
_this.linkInverse(name, injected[definition.idAttribute]);
}
}
if (DSUtils.isArray(injected)) {
DSUtils.forEach(injected, function (injectedI) {
_link.call(_this, definition, injectedI, options);
});
} else {
_link.call(_this, definition, injected, options);
}
if (options.notify) {
options.afterInject(options, injected);
_this.emit(options, 'afterInject', DSUtils.copy(injected));
}
return injected;
}
module.exports = inject;
},{"../../errors":48,"../../utils":50}],44:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function link(resourceName, id, relations) {
var _this = this;
var definition = _this.definitions[resourceName];
relations = relations || [];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new DSErrors.IA('"id" must be a string or a number!');
} else if (!DSUtils.isArray(relations)) {
throw new DSErrors.IA('"relations" must be an array!');
}
var linked = _this.get(resourceName, id);
if (linked) {
DSUtils.forEach(definition.relationList, function (def) {
var relationName = def.relation;
if (relations.length && !DSUtils.contains(relations, relationName)) {
return;
}
var params = {};
if (def.type === 'belongsTo') {
var parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null;
if (parent) {
linked[def.localField] = parent;
}
} else if (def.type === 'hasMany') {
params[def.foreignKey] = linked[definition.idAttribute];
linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true });
} else if (def.type === 'hasOne') {
params[def.foreignKey] = linked[definition.idAttribute];
var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true });
if (children.length) {
linked[def.localField] = children[0];
}
}
});
}
return linked;
}
module.exports = link;
},{"../../errors":48,"../../utils":50}],45:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function linkAll(resourceName, params, relations) {
var _this = this;
var definition = _this.definitions[resourceName];
relations = relations || [];
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isArray(relations)) {
throw new DSErrors.IA('"relations" must be an array!');
}
var linked = _this.filter(resourceName, params);
if (linked) {
DSUtils.forEach(definition.relationList, function (def) {
var relationName = def.relation;
if (relations.length && !DSUtils.contains(relations, relationName)) {
return;
}
if (def.type === 'belongsTo') {
DSUtils.forEach(linked, function (injectedItem) {
var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null;
if (parent) {
injectedItem[def.localField] = parent;
}
});
} else if (def.type === 'hasMany') {
DSUtils.forEach(linked, function (injectedItem) {
var params = {};
params[def.foreignKey] = injectedItem[definition.idAttribute];
injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true });
});
} else if (def.type === 'hasOne') {
DSUtils.forEach(linked, function (injectedItem) {
var params = {};
params[def.foreignKey] = injectedItem[definition.idAttribute];
var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true });
if (children.length) {
injectedItem[def.localField] = children[0];
}
});
}
});
}
return linked;
}
module.exports = linkAll;
},{"../../errors":48,"../../utils":50}],46:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function linkInverse(resourceName, id, relations) {
var _this = this;
var definition = _this.definitions[resourceName];
relations = relations || [];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new DSErrors.IA('"id" must be a string or a number!');
} else if (!DSUtils.isArray(relations)) {
throw new DSErrors.IA('"relations" must be an array!');
}
var linked = _this.get(resourceName, id);
if (linked) {
DSUtils.forOwn(_this.definitions, function (d) {
DSUtils.forOwn(d.relations, function (relatedModels) {
DSUtils.forOwn(relatedModels, function (defs, relationName) {
if (relations.length && !DSUtils.contains(relations, d.name)) {
return;
}
if (definition.name === relationName) {
_this.linkAll(d.name, {}, [definition.name]);
}
});
});
});
}
return linked;
}
module.exports = linkInverse;
},{"../../errors":48,"../../utils":50}],47:[function(require,module,exports){
var DSUtils = require('../../utils');
var DSErrors = require('../../errors');
function unlinkInverse(resourceName, id, relations) {
var _this = this;
var definition = _this.definitions[resourceName];
relations = relations || [];
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new DSErrors.NER(resourceName);
} else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) {
throw new DSErrors.IA('"id" must be a string or a number!');
} else if (!DSUtils.isArray(relations)) {
throw new DSErrors.IA('"relations" must be an array!');
}
var linked = _this.get(resourceName, id);
if (linked) {
DSUtils.forOwn(_this.definitions, function (d) {
DSUtils.forOwn(d.relations, function (relatedModels) {
DSUtils.forOwn(relatedModels, function (defs, relationName) {
if (definition.name === relationName) {
DSUtils.forEach(defs, function (def) {
DSUtils.forEach(_this.store[def.name].collection, function (item) {
if (def.type === 'hasMany' && item[def.localField]) {
var index;
DSUtils.forEach(item[def.localField], function (subItem, i) {
if (subItem === linked) {
index = i;
}
});
item[def.localField].splice(index, 1);
} else if (item[def.localField] === linked) {
delete item[def.localField];
}
});
});
}
});
});
});
}
return linked;
}
module.exports = unlinkInverse;
},{"../../errors":48,"../../utils":50}],48:[function(require,module,exports){
function IllegalArgumentError(message) {
Error.call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = message || 'Illegal Argument!';
}
IllegalArgumentError.prototype = new Error();
IllegalArgumentError.prototype.constructor = IllegalArgumentError;
function RuntimeError(message) {
Error.call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = message || 'RuntimeError Error!';
}
RuntimeError.prototype = new Error();
RuntimeError.prototype.constructor = RuntimeError;
function NonexistentResourceError(resourceName) {
Error.call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = (resourceName || '') + ' is not a registered resource!';
}
NonexistentResourceError.prototype = new Error();
NonexistentResourceError.prototype.constructor = NonexistentResourceError;
module.exports = {
IllegalArgumentError: IllegalArgumentError,
IA: IllegalArgumentError,
RuntimeError: RuntimeError,
R: RuntimeError,
NonexistentResourceError: NonexistentResourceError,
NER: NonexistentResourceError
};
},{}],49:[function(require,module,exports){
var DS = require('./datastore');
module.exports = {
DS: DS,
createStore: function (options) {
return new DS(options);
},
DSUtils: require('./utils'),
DSErrors: require('./errors'),
version: {
full: '1.1.0',
major: parseInt('1', 10),
minor: parseInt('1', 10),
patch: parseInt('0', 10),
alpha: 'false' !== 'false' ? 'false' : false,
beta: 'false' !== 'false' ? 'false' : false
}
};
},{"./datastore":37,"./errors":48,"./utils":50}],50:[function(require,module,exports){
/* jshint -W041 */
var w, _Promise;
var objectProto = Object.prototype;
var toString = objectProto.toString;
var DSErrors = require('./errors');
var forEach = require('mout/array/forEach');
var slice = require('mout/array/slice');
var forOwn = require('mout/object/forOwn');
var observe = require('../lib/observe-js/observe-js');
var es6Promise = require('es6-promise');
es6Promise.polyfill();
var isArray = Array.isArray || function isArray(value) {
return toString.call(value) == '[object Array]' || false;
};
function isRegExp(value) {
return toString.call(value) == '[object RegExp]' || false;
}
// adapted from lodash.isBoolean
function isBoolean(value) {
return (value === true || value === false || value && typeof value == 'object' && toString.call(value) == '[object Boolean]') || false;
}
// adapted from lodash.isString
function isString(value) {
return typeof value == 'string' || (value && typeof value == 'object' && toString.call(value) == '[object String]') || false;
}
function isObject(value) {
return toString.call(value) == '[object Object]' || false;
}
// adapted from lodash.isDate
function isDate(value) {
return (value && typeof value == 'object' && toString.call(value) == '[object Date]') || false;
}
// adapted from lodash.isNumber
function isNumber(value) {
var type = typeof value;
return type == 'number' || (value && type == 'object' && toString.call(value) == '[object Number]') || false;
}
// adapted from lodash.isFunction
function isFunction(value) {
return typeof value == 'function' || (value && toString.call(value) === '[object Function]') || false;
}
// adapted from mout.isEmpty
function isEmpty(val) {
if (val == null) {
// typeof null == 'object' so we check it first
return true;
} else if (typeof val === 'string' || isArray(val)) {
return !val.length;
} else if (typeof val === 'object') {
var result = true;
forOwn(val, function () {
result = false;
return false; // break loop
});
return result;
} else {
return true;
}
}
function intersection(array1, array2) {
if (!array1 || !array2) {
return [];
}
var result = [];
var item;
for (var i = 0, length = array1.length; i < length; i++) {
item = array1[i];
if (DSUtils.contains(result, item)) {
continue;
}
if (DSUtils.contains(array2, item)) {
result.push(item);
}
}
return result;
}
function filter(array, cb, thisObj) {
var results = [];
forEach(array, function (value, key, arr) {
if (cb(value, key, arr)) {
results.push(value);
}
}, thisObj);
return results;
}
function finallyPolyfill(cb) {
var constructor = this.constructor;
return this.then(function (value) {
return constructor.resolve(cb()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(cb()).then(function () {
throw reason;
});
});
}
try {
w = window;
if (!w.Promise.prototype['finally']) {
w.Promise.prototype['finally'] = finallyPolyfill;
}
_Promise = w.Promise;
w = {};
} catch (e) {
w = null;
_Promise = require('bluebird');
}
function updateTimestamp(timestamp) {
var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime();
if (timestamp && newTimestamp <= timestamp) {
return timestamp + 1;
} else {
return newTimestamp;
}
}
function Events(target) {
var events = {};
target = target || this;
target.on = function (type, func, ctx) {
events[type] = events[type] || [];
events[type].push({
f: func,
c: ctx
});
};
target.off = function (type, func) {
var listeners = events[type];
if (!listeners) {
events = {};
} else if (func) {
for (var i = 0; i < listeners.length; i++) {
if (listeners[i] === func) {
listeners.splice(i, 1);
break;
}
}
} else {
listeners.splice(0, listeners.length);
}
};
target.emit = function () {
var args = Array.prototype.slice.call(arguments);
var listeners = events[args.shift()] || [];
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
}
};
}
/**
* @method bubbleUp
* @param {array} heap The heap.
* @param {function} weightFunc The weight function.
* @param {number} n The index of the element to bubble up.
*/
function bubbleUp(heap, weightFunc, n) {
var element = heap[n];
var weight = weightFunc(element);
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1;
var parent = heap[parentN];
// If the parent has a lesser weight, things are in order and we
// are done.
if (weight >= weightFunc(parent)) {
break;
} else {
heap[parentN] = element;
heap[n] = parent;
n = parentN;
}
}
}
/**
* @method bubbleDown
* @param {array} heap The heap.
* @param {function} weightFunc The weight function.
* @param {number} n The index of the element to sink down.
*/
function bubbleDown(heap, weightFunc, n) {
var length = heap.length;
var node = heap[n];
var nodeWeight = weightFunc(node);
while (true) {
var child2N = (n + 1) * 2,
child1N = child2N - 1;
var swap = null;
if (child1N < length) {
var child1 = heap[child1N],
child1Weight = weightFunc(child1);
// If the score is less than our node's, we need to swap.
if (child1Weight < nodeWeight) {
swap = child1N;
}
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = heap[child2N],
child2Weight = weightFunc(child2);
if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) {
swap = child2N;
}
}
if (swap === null) {
break;
} else {
heap[n] = heap[swap];
heap[swap] = node;
n = swap;
}
}
}
function DSBinaryHeap(weightFunc, compareFunc) {
if (weightFunc && !isFunction(weightFunc)) {
throw new Error('DSBinaryHeap(weightFunc): weightFunc: must be a function!');
}
weightFunc = weightFunc || function (x) {
return x;
};
compareFunc = compareFunc || function (x, y) {
return x === y;
};
this.weightFunc = weightFunc;
this.compareFunc = compareFunc;
this.heap = [];
}
var dsp = DSBinaryHeap.prototype;
dsp.push = function (node) {
this.heap.push(node);
bubbleUp(this.heap, this.weightFunc, this.heap.length - 1);
};
dsp.peek = function () {
return this.heap[0];
};
dsp.pop = function () {
var front = this.heap[0],
end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
bubbleDown(this.heap, this.weightFunc, 0);
}
return front;
};
dsp.remove = function (node) {
var length = this.heap.length;
for (var i = 0; i < length; i++) {
if (this.compareFunc(this.heap[i], node)) {
var removed = this.heap[i];
var end = this.heap.pop();
if (i !== length - 1) {
this.heap[i] = end;
bubbleUp(this.heap, this.weightFunc, i);
bubbleDown(this.heap, this.weightFunc, i);
}
return removed;
}
}
return null;
};
dsp.removeAll = function () {
this.heap = [];
};
dsp.size = function () {
return this.heap.length;
};
var toPromisify = [
'beforeValidate',
'validate',
'afterValidate',
'beforeCreate',
'afterCreate',
'beforeUpdate',
'afterUpdate',
'beforeDestroy',
'afterDestroy'
];
// adapted from angular.copy
function copy(source, destination, stackSource, stackDest) {
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, [], stackSource, stackDest);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else if (isObject(source)) {
var emptyObject = Object.create(Object.getPrototypeOf(source));
destination = copy(source, emptyObject, stackSource, stackDest);
}
}
} else {
if (source === destination) {
throw new Error('Cannot copy! Source and destination are identical.');
}
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
var index = stackSource.indexOf(source);
if (index !== -1) return stackDest[index];
stackSource.push(source);
stackDest.push(destination);
}
var result;
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
result = copy(source[i], null, stackSource, stackDest);
if (isObject(source[i])) {
stackSource.push(source[i]);
stackDest.push(result);
}
destination.push(result);
}
} else {
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function (value, key) {
delete destination[key];
});
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
result = copy(source[key], null, stackSource, stackDest);
if (isObject(source[key])) {
stackSource.push(source[key]);
stackDest.push(result);
}
destination[key] = result;
}
}
}
}
return destination;
}
// adapted from angular.equals
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return equals(o1.getTime(), o2.getTime());
} else if (isRegExp(o1) && isRegExp(o2)) {
return o1.toString() == o2.toString();
} else {
if (isArray(o2)) return false;
keySet = {};
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!keySet.hasOwnProperty(key) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined && !isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function resolveId(definition, idOrInstance) {
if (this.isString(idOrInstance) || isNumber(idOrInstance)) {
return idOrInstance;
} else if (idOrInstance && definition) {
return idOrInstance[definition.idAttribute] || idOrInstance;
} else {
return idOrInstance;
}
}
function resolveItem(resource, idOrInstance) {
if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) {
return resource.index[idOrInstance] || idOrInstance;
} else {
return idOrInstance;
}
}
function isValidString(val) {
return (val != null && val !== '');
}
function join(items, separator) {
separator = separator || '';
return filter(items, isValidString).join(separator);
}
function makePath(var_args) {
var result = join(slice(arguments), '/');
return result.replace(/([^:\/]|^)\/{2,}/g, '$1/');
}
observe.setEqualityFn(equals);
var DSUtils = {
// Options that inherit from defaults
_: function (parent, options) {
var _this = this;
options = options || {};
if (options && options.constructor === parent.constructor) {
return options;
} else if (!isObject(options)) {
throw new DSErrors.IA('"options" must be an object!');
}
forEach(toPromisify, function (name) {
if (typeof options[name] === 'function' && options[name].toString().indexOf('var args = Array') === -1) {
options[name] = _this.promisify(options[name]);
}
});
var O = function Options(attrs) {
var self = this;
forOwn(attrs, function (value, key) {
self[key] = value;
});
};
O.prototype = parent;
return new O(options);
},
compute: function (fn, field) {
var _this = this;
var args = [];
forEach(fn.deps, function (dep) {
args.push(_this[dep]);
});
// compute property
_this[field] = fn[fn.length - 1].apply(_this, args);
},
contains: require('mout/array/contains'),
copy: copy,
deepMixIn: require('mout/object/deepMixIn'),
diffObjectFromOldObject: observe.diffObjectFromOldObject,
DSBinaryHeap: DSBinaryHeap,
equals: equals,
Events: Events,
filter: filter,
forEach: forEach,
forOwn: forOwn,
fromJson: function (json) {
return isString(json) ? JSON.parse(json) : json;
},
get: require('mout/object/get'),
intersection: intersection,
isArray: isArray,
isBoolean: isBoolean,
isDate: isDate,
isEmpty: isEmpty,
isFunction: isFunction,
isObject: isObject,
isNumber: isNumber,
isRegExp: isRegExp,
isString: isString,
makePath: makePath,
observe: observe,
pascalCase: require('mout/string/pascalCase'),
pick: require('mout/object/pick'),
Promise: _Promise,
promisify: function (fn, target) {
var Promise = this.Promise;
if (!fn) {
return;
} else if (typeof fn !== 'function') {
throw new Error('Can only promisify functions!');
}
return function () {
var args = Array.prototype.slice.apply(arguments);
return new Promise(function (resolve, reject) {
args.push(function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
try {
var promise = fn.apply(target || this, args);
if (promise && promise.then) {
promise.then(resolve, reject);
}
} catch (err) {
reject(err);
}
});
};
},
remove: require('mout/array/remove'),
set: require('mout/object/set'),
slice: slice,
sort: require('mout/array/sort'),
toJson: JSON.stringify,
updateTimestamp: updateTimestamp,
upperCase: require('mout/string/upperCase'),
removeCircular: function (object) {
var objects = [];
return (function rmCirc(value) {
var i;
var nu;
if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) {
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return undefined;
}
}
objects.push(value);
if (DSUtils.isArray(value)) {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = rmCirc(value[i]);
}
} else {
nu = {};
forOwn(value, function (v, k) {
nu[k] = rmCirc(value[k]);
});
}
return nu;
}
return value;
}(object));
},
resolveItem: resolveItem,
resolveId: resolveId,
w: w
};
module.exports = DSUtils;
},{"../lib/observe-js/observe-js":1,"./errors":48,"bluebird":"bluebird","es6-promise":2,"mout/array/contains":4,"mout/array/forEach":5,"mout/array/remove":7,"mout/array/slice":8,"mout/array/sort":9,"mout/object/deepMixIn":13,"mout/object/forOwn":15,"mout/object/get":16,"mout/object/pick":19,"mout/object/set":20,"mout/string/pascalCase":23,"mout/string/upperCase":26}]},{},[49])(49)
});
|
ajax/libs/analytics.js/1.5.7/analytics.js | calebmer/cdnjs | ;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module._resolving && !module.exports) {
var mod = {};
mod.exports = {};
mod.client = mod.component = true;
module._resolving = true;
module.call(this, mod.exports, require.relative(resolved), mod);
delete module._resolving;
module.exports = mod.exports;
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("avetisk-defaults/index.js", function(exports, require, module){
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
});
require.register("component-type/index.js", function(exports, require, module){
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Function]': return 'function';
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object String]': return 'string';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val && val.nodeType === 1) return 'element';
if (val === Object(val)) return 'object';
return typeof val;
};
});
require.register("component-clone/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
});
require.register("component-cookie/index.js", function(exports, require, module){
/**
* Encode.
*/
var encode = encodeURIComponent;
/**
* Decode.
*/
var decode = decodeURIComponent;
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toGMTString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
});
require.register("component-each/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
});
require.register("component-indexof/index.js", function(exports, require, module){
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
});
require.register("component-emitter/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
});
require.register("component-event/index.js", function(exports, require, module){
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
});
require.register("component-inherit/index.js", function(exports, require, module){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
});
require.register("component-object/index.js", function(exports, require, module){
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
});
require.register("component-trim/index.js", function(exports, require, module){
exports = module.exports = trim;
function trim(str){
if (str.trim) return str.trim();
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
if (str.trimLeft) return str.trimLeft();
return str.replace(/^\s*/, '');
};
exports.right = function(str){
if (str.trimRight) return str.trimRight();
return str.replace(/\s*$/, '');
};
});
require.register("component-querystring/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
});
require.register("component-url/index.js", function(exports, require, module){
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
port: a.port,
hash: a.hash,
hostname: a.hostname,
pathname: a.pathname,
protocol: a.protocol,
search: a.search,
query: a.search.slice(1)
}
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
if (0 == url.indexOf('//')) return true;
if (~url.indexOf('://')) return true;
return false;
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return ! exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname != location.hostname
|| url.port != location.port
|| url.protocol != location.protocol;
};
});
require.register("component-bind/index.js", function(exports, require, module){
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
});
require.register("segmentio-bind-all/index.js", function(exports, require, module){
try {
var bind = require('bind');
var type = require('type');
} catch (e) {
var bind = require('bind-component');
var type = require('type-component');
}
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
});
require.register("ianstormtaylor-bind/index.js", function(exports, require, module){
try {
var bind = require('bind');
} catch (e) {
var bind = require('bind-component');
}
var bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
});
require.register("timoxley-next-tick/index.js", function(exports, require, module){
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
});
require.register("ianstormtaylor-callback/index.js", function(exports, require, module){
var next = require('next-tick');
/**
* Expose `callback`.
*/
module.exports = callback;
/**
* Call an `fn` back synchronously if it exists.
*
* @param {Function} fn
*/
function callback (fn) {
if ('function' === typeof fn) fn();
}
/**
* Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the
* `fn` will be called on next tick.
*
* @param {Function} fn
* @param {Number} wait (optional)
*/
callback.async = function (fn, wait) {
if ('function' !== typeof fn) return;
if (!wait) return next(fn);
setTimeout(fn, wait);
};
/**
* Symmetry.
*/
callback.sync = callback;
});
require.register("ianstormtaylor-is-empty/index.js", function(exports, require, module){
/**
* Expose `isEmpty`.
*/
module.exports = isEmpty;
/**
* Has.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Test whether a value is "empty".
*
* @param {Mixed} val
* @return {Boolean}
*/
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
});
require.register("ianstormtaylor-is/index.js", function(exports, require, module){
var isEmpty = require('is-empty')
, typeOf = require('type');
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
});
require.register("segmentio-after/index.js", function(exports, require, module){
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
});
require.register("component-domify/index.js", function(exports, require, module){
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) {
if ('string' != typeof html) throw new TypeError('String expected');
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
});
require.register("component-once/index.js", function(exports, require, module){
/**
* Identifier.
*/
var n = 0;
/**
* Global.
*/
var global = (function(){ return this })();
/**
* Make `fn` callable only once.
*
* @param {Function} fn
* @return {Function}
* @api public
*/
module.exports = function(fn) {
var id = n++;
function once(){
// no receiver
if (this == global) {
if (once.called) return;
once.called = true;
return fn.apply(this, arguments);
}
// receiver
var key = '__called_' + id + '__';
if (this[key]) return;
this[key] = true;
return fn.apply(this, arguments);
}
return once;
};
});
require.register("ianstormtaylor-to-no-case/index.js", function(exports, require, module){
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasCamel = /[a-z][A-Z]/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) string = unseparate(string);
if (hasCamel.test(string)) string = uncamelize(string);
return string.toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
});
require.register("ianstormtaylor-to-space-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
});
require.register("ianstormtaylor-to-snake-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
});
require.register("segmentio-alias/index.js", function(exports, require, module){
var type = require('type');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `alias`.
*/
module.exports = alias;
/**
* Alias an `object`.
*
* @param {Object} obj
* @param {Mixed} method
*/
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
/**
* Convert the keys in an `obj` using a dictionary of `aliases`.
*
* @param {Object} obj
* @param {Object} aliases
*/
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
/**
* Convert the keys in an `obj` using a `convert` function.
*
* @param {Object} obj
* @param {Function} convert
*/
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
});
require.register("segmentio-analytics.js-integration/lib/index.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var debug = require('debug');
var defaults = require('defaults');
var protos = require('./protos');
var slug = require('slug');
var statics = require('./statics');
/**
* Expose `createIntegration`.
*/
module.exports = createIntegration;
/**
* Create a new Integration constructor.
*
* @param {String} name
*/
function createIntegration (name) {
/**
* Initialize a new `Integration`.
*
* @param {Object} options
*/
function Integration (options) {
this.debug = debug('analytics:integration:' + slug(name));
this.options = defaults(clone(options) || {}, this.defaults);
this._queue = [];
this.once('ready', bind(this, this.flush));
Integration.emit('construct', this);
this._wrapInitialize();
this._wrapLoad();
this._wrapPage();
this._wrapTrack();
}
Integration.prototype.defaults = {};
Integration.prototype.globals = [];
Integration.prototype.name = name;
for (var key in statics) Integration[key] = statics[key];
for (var key in protos) Integration.prototype[key] = protos[key];
return Integration;
}
});
require.register("segmentio-analytics.js-integration/lib/protos.js", function(exports, require, module){
/**
* Module dependencies.
*/
var normalize = require('to-no-case');
var after = require('after');
var callback = require('callback');
var Emitter = require('emitter');
var tick = require('next-tick');
var events = require('./events');
var type = require('type');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Initialize.
*/
exports.initialize = function () {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
* @api private
*/
exports.loaded = function () {
return false;
};
/**
* Load.
*
* @param {Function} cb
*/
exports.load = function (cb) {
callback.async(cb);
};
/**
* Page.
*
* @param {Page} page
*/
exports.page = function(page){};
/**
* Track.
*
* @param {Track} track
*/
exports.track = function(track){};
/**
* Get events that match `str`.
*
* Examples:
*
* events = { my_event: 'a4991b88' }
* .map(events, 'My Event');
* // => ["a4991b88"]
* .map(events, 'whatever');
* // => []
*
* events = [{ key: 'my event', value: '9b5eb1fa' }]
* .map(events, 'my_event');
* // => ["9b5eb1fa"]
* .map(events, 'whatever');
* // => []
*
* @param {String} str
* @return {Array}
* @api public
*/
exports.map = function(obj, str){
var a = normalize(str);
var ret = [];
// noop
if (!obj) return ret;
// object
if ('object' == type(obj)) {
for (var k in obj) {
var item = obj[k];
var b = normalize(k);
if (b == a) ret.push(item);
}
}
// array
if ('array' == type(obj)) {
if (!obj.length) return ret;
if (!obj[0].key) return ret;
for (var i = 0; i < obj.length; ++i) {
var item = obj[i];
var b = normalize(item.key);
if (b == a) ret.push(item.value);
}
}
return ret;
};
/**
* Invoke a `method` that may or may not exist on the prototype with `args`,
* queueing or not depending on whether the integration is "ready". Don't
* trust the method call, since it contains integration party code.
*
* @param {String} method
* @param {Mixed} args...
* @api private
*/
exports.invoke = function (method) {
if (!this[method]) return;
var args = [].slice.call(arguments, 1);
if (!this._ready) return this.queue(method, args);
var ret;
try {
this.debug('%s with %o', method, args);
ret = this[method].apply(this, args);
} catch (e) {
this.debug('error %o calling %s with %o', e, method, args);
}
return ret;
};
/**
* Queue a `method` with `args`. If the integration assumes an initial
* pageview, then let the first call to `page` pass through.
*
* @param {String} method
* @param {Array} args
* @api private
*/
exports.queue = function (method, args) {
if ('page' == method && this._assumesPageview && !this._initialized) {
return this.page.apply(this, args);
}
this._queue.push({ method: method, args: args });
};
/**
* Flush the internal queue.
*
* @api private
*/
exports.flush = function () {
this._ready = true;
var call;
while (call = this._queue.shift()) this[call.method].apply(this, call.args);
};
/**
* Reset the integration, removing its global variables.
*
* @api private
*/
exports.reset = function () {
for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;
};
/**
* Wrap the initialize method in an exists check, so we don't have to do it for
* every single integration.
*
* @api private
*/
exports._wrapInitialize = function () {
var initialize = this.initialize;
this.initialize = function () {
this.debug('initialize');
this._initialized = true;
var ret = initialize.apply(this, arguments);
this.emit('initialize');
var self = this;
if (this._readyOnInitialize) {
tick(function () {
self.emit('ready');
});
}
return ret;
};
if (this._assumesPageview) this.initialize = after(2, this.initialize);
};
/**
* Wrap the load method in `debug` calls, so every integration gets them
* automatically.
*
* @api private
*/
exports._wrapLoad = function () {
var load = this.load;
this.load = function (callback) {
var self = this;
this.debug('loading');
if (this.loaded()) {
this.debug('already loaded');
tick(function () {
if (self._readyOnLoad) self.emit('ready');
callback && callback();
});
return;
}
return load.call(this, function (err, e) {
self.debug('loaded');
self.emit('load');
if (self._readyOnLoad) self.emit('ready');
callback && callback(err, e);
});
};
};
/**
* Wrap the page method to call `initialize` instead if the integration assumes
* a pageview.
*
* @api private
*/
exports._wrapPage = function () {
var page = this.page;
this.page = function () {
if (this._assumesPageview && !this._initialized) {
return this.initialize.apply(this, arguments);
}
return page.apply(this, arguments);
};
};
/**
* Wrap the track method to call other ecommerce methods if
* available depending on the `track.event()`.
*
* @api private
*/
exports._wrapTrack = function(){
var t = this.track;
this.track = function(track){
var event = track.event();
var called;
var ret;
for (var method in events) {
var regexp = events[method];
if (!this[method]) continue;
if (!regexp.test(event)) continue;
ret = this[method].apply(this, arguments);
called = true;
break;
}
if (!called) ret = t.apply(this, arguments);
return ret;
};
};
});
require.register("segmentio-analytics.js-integration/lib/events.js", function(exports, require, module){
/**
* Expose `events`
*/
module.exports = {
removedProduct: /removed[ _]?product/i,
viewedProduct: /viewed[ _]?product/i,
addedProduct: /added[ _]?product/i,
completedOrder: /completed[ _]?order/i
};
});
require.register("segmentio-analytics.js-integration/lib/statics.js", function(exports, require, module){
var after = require('after');
var Emitter = require('emitter');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Add a new option to the integration by `key` with default `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Integration}
*/
exports.option = function (key, value) {
this.prototype.defaults[key] = value;
return this;
};
/**
* Add a new mapping option.
*
* the method will create a method `name` that will return a mapping
* for you to use.
*
* Example:
*
* Integration('My Integration')
* .mapping('events');
*
* new MyIntegration().track('My Event');
*
* .track = function(track){
* var events = this.events(track.event());
* each(events, send);
* };
*
* @param {String} name
* @return {Integration}
* @api public
*/
exports.mapping = function(name){
this.option(name, []);
this.prototype[name] = function(str){
return this.map(this.options[name], str);
};
return this;
};
/**
* Register a new global variable `key` owned by the integration, which will be
* used to test whether the integration is already on the page.
*
* @param {String} global
* @return {Integration}
*/
exports.global = function (key) {
this.prototype.globals.push(key);
return this;
};
/**
* Mark the integration as assuming an initial pageview, so to defer loading
* the script until the first `page` call, noop the first `initialize`.
*
* @return {Integration}
*/
exports.assumesPageview = function () {
this.prototype._assumesPageview = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnLoad = function () {
this.prototype._readyOnLoad = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnInitialize = function () {
this.prototype._readyOnInitialize = true;
return this;
};
});
require.register("segmentio-convert-dates/index.js", function(exports, require, module){
var is = require('is');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `convertDates`.
*/
module.exports = convertDates;
/**
* Recursively convert an `obj`'s dates to new values.
*
* @param {Object} obj
* @param {Function} convert
* @return {Object}
*/
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
});
require.register("segmentio-global-queue/index.js", function(exports, require, module){
/**
* Expose `generate`.
*/
module.exports = generate;
/**
* Generate a global queue pushing method with `name`.
*
* @param {String} name
* @param {Object} options
* @property {Boolean} wrap
* @return {Function}
*/
function generate (name, options) {
options = options || {};
return function (args) {
args = [].slice.call(arguments);
window[name] || (window[name] = []);
options.wrap === false
? window[name].push.apply(window[name], args)
: window[name].push(args);
};
}
});
require.register("segmentio-load-date/index.js", function(exports, require, module){
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
});
require.register("segmentio-load-script/index.js", function(exports, require, module){
var type = require('type');
module.exports = function loadScript (options, callback) {
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if (type(options) === 'string') options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
// If we have a callback, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if (callback && type(callback) === 'function') {
if (script.addEventListener) {
script.addEventListener('load', function (event) {
callback(null, event);
}, false);
script.addEventListener('error', function (event) {
callback(new Error('Failed to load the script.'), event);
}, false);
} else if (script.attachEvent) {
script.attachEvent('onreadystatechange', function (event) {
if (/complete|loaded/.test(script.readyState)) {
callback(null, event);
}
});
}
}
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
});
require.register("segmentio-script-onload/index.js", function(exports, require, module){
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
/**
* Invoke `fn(err)` when the given `el` script loads.
*
* @param {Element} el
* @param {Function} fn
* @api public
*/
module.exports = function(el, fn){
return el.addEventListener
? add(el, fn)
: attach(el, fn);
};
/**
* Add event listener to `el`, `fn()`.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function add(el, fn){
el.addEventListener('load', function(_, e){ fn(null, e); }, false);
el.addEventListener('error', function(e){
var err = new Error('failed to load the script "' + el.src + '"');
err.event = e;
fn(err);
}, false);
}
/**
* Attach evnet.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function attach(el, fn){
el.attachEvent('onreadystatechange', function(e){
if (!/complete|loaded/.test(el.readyState)) return;
fn(null, e);
});
}
});
require.register("segmentio-on-body/index.js", function(exports, require, module){
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
});
require.register("segmentio-on-error/index.js", function(exports, require, module){
/**
* Expose `onError`.
*/
module.exports = onError;
/**
* Callbacks.
*/
var callbacks = [];
/**
* Preserve existing handler.
*/
if ('function' == typeof window.onerror) callbacks.push(window.onerror);
/**
* Bind to `window.onerror`.
*/
window.onerror = handler;
/**
* Error handler.
*/
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
/**
* Call a `fn` on `window.onerror`.
*
* @param {Function} fn
*/
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
});
require.register("segmentio-to-iso-string/index.js", function(exports, require, module){
/**
* Expose `toIsoString`.
*/
module.exports = toIsoString;
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {String}
*/
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/**
* Pad a `number` with a ten's place zero.
*
* @param {Number} number
* @return {String}
*/
function pad (number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
});
require.register("segmentio-to-unix-timestamp/index.js", function(exports, require, module){
/**
* Expose `toUnixTimestamp`.
*/
module.exports = toUnixTimestamp;
/**
* Convert a `date` into a Unix timestamp.
*
* @param {Date}
* @return {Number}
*/
function toUnixTimestamp (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-use-https/index.js", function(exports, require, module){
/**
* Protocol.
*/
module.exports = function (url) {
switch (arguments.length) {
case 0: return check();
case 1: return transform(url);
}
};
/**
* Transform a protocol-relative `url` to the use the proper protocol.
*
* @param {String} url
* @return {String}
*/
function transform (url) {
return check() ? 'https:' + url : 'http:' + url;
}
/**
* Check whether `https:` be used for loading scripts.
*
* @return {Boolean}
*/
function check () {
return (
location.protocol == 'https:' ||
location.protocol == 'chrome-extension:'
);
}
});
require.register("segmentio-when/index.js", function(exports, require, module){
var callback = require('callback');
/**
* Expose `when`.
*/
module.exports = when;
/**
* Loop on a short interval until `condition()` is true, then call `fn`.
*
* @param {Function} condition
* @param {Function} fn
* @param {Number} interval (optional)
*/
function when (condition, fn, interval) {
if (condition()) return callback.async(fn);
var ref = setInterval(function () {
if (!condition()) return;
callback(fn);
clearInterval(ref);
}, interval || 10);
}
});
require.register("yields-slug/index.js", function(exports, require, module){
/**
* Generate a slug from the given `str`.
*
* example:
*
* generate('foo bar');
* // > foo-bar
*
* @param {String} str
* @param {Object} options
* @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g`
* @config {String} [separator] separator to insert, defaulted to `-`
* @return {String}
*/
module.exports = function (str, options) {
options || (options = {});
return str.toLowerCase()
.replace(options.replace || /[^a-z0-9]/g, ' ')
.replace(/^ +| +$/g, '')
.replace(/ +/g, options.separator || '-')
};
});
require.register("visionmedia-batch/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
try {
var EventEmitter = require('events').EventEmitter;
} catch (err) {
var Emitter = require('emitter');
}
/**
* Noop.
*/
function noop(){}
/**
* Expose `Batch`.
*/
module.exports = Batch;
/**
* Create a new Batch.
*/
function Batch() {
if (!(this instanceof Batch)) return new Batch;
this.fns = [];
this.concurrency(Infinity);
this.throws(true);
for (var i = 0, len = arguments.length; i < len; ++i) {
this.push(arguments[i]);
}
}
/**
* Inherit from `EventEmitter.prototype`.
*/
if (EventEmitter) {
Batch.prototype.__proto__ = EventEmitter.prototype;
} else {
Emitter(Batch.prototype);
}
/**
* Set concurrency to `n`.
*
* @param {Number} n
* @return {Batch}
* @api public
*/
Batch.prototype.concurrency = function(n){
this.n = n;
return this;
};
/**
* Queue a function.
*
* @param {Function} fn
* @return {Batch}
* @api public
*/
Batch.prototype.push = function(fn){
this.fns.push(fn);
return this;
};
/**
* Set wether Batch will or will not throw up.
*
* @param {Boolean} throws
* @return {Batch}
* @api public
*/
Batch.prototype.throws = function(throws) {
this.e = !!throws;
return this;
};
/**
* Execute all queued functions in parallel,
* executing `cb(err, results)`.
*
* @param {Function} cb
* @return {Batch}
* @api public
*/
Batch.prototype.end = function(cb){
var self = this
, total = this.fns.length
, pending = total
, results = []
, errors = []
, cb = cb || noop
, fns = this.fns
, max = this.n
, throws = this.e
, index = 0
, done;
// empty
if (!fns.length) return cb(null, results);
// process
function next() {
var i = index++;
var fn = fns[i];
if (!fn) return;
var start = new Date;
try {
fn(callback);
} catch (err) {
callback(err);
}
function callback(err, res){
if (done) return;
if (err && throws) return done = true, cb(err);
var complete = total - pending + 1;
var end = new Date;
results[i] = res;
errors[i] = err;
self.emit('progress', {
index: i,
value: res,
error: err,
pending: pending,
total: total,
complete: complete,
percent: complete / total * 100 | 0,
start: start,
end: end,
duration: end - start
});
if (--pending) next()
else if(!throws) cb(errors, results);
else cb(null, results);
}
}
// concurrency
for (var i = 0; i < fns.length; i++) {
if (i == max) break;
next();
}
return this;
};
});
require.register("segmentio-substitute/index.js", function(exports, require, module){
/**
* Expose `substitute`
*/
module.exports = substitute;
/**
* Substitute `:prop` with the given `obj` in `str`
*
* @param {String} str
* @param {Object} obj
* @param {RegExp} expr
* @return {String}
* @api public
*/
function substitute(str, obj, expr){
if (!obj) throw new TypeError('expected an object');
expr = expr || /:(\w+)/g;
return str.replace(expr, function(_, prop){
return null != obj[prop]
? obj[prop]
: _;
});
}
});
require.register("segmentio-load-pixel/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var stringify = require('querystring').stringify;
var sub = require('substitute');
/**
* Factory function to create a pixel loader.
*
* @param {String} path
* @return {Function}
* @api public
*/
module.exports = function(path){
return function(query, obj, fn){
if ('function' == typeof obj) fn = obj, obj = {};
obj = obj || {};
fn = fn || function(){};
var url = sub(path, obj);
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
query = stringify(query);
if (query) query = '?' + query;
img.src = url + query;
img.width = 1;
img.height = 1;
return img;
};
};
/**
* Create an error handler.
*
* @param {Fucntion} fn
* @param {String} message
* @param {Image} img
* @return {Function}
* @api private
*/
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
});
require.register("segmentio-replace-document-write/index.js", function(exports, require, module){
var domify = require('domify');
/**
* Replace document.write until a url is written matching the url fragment
*
* @param {String} match
* @param {Element} parent to appendChild onto
* @param {Function} fn optional callback function
*/
module.exports = function(match, parent, fn){
var write = document.write;
document.write = append;
if (typeof parent === 'function') fn = parent, parent = null;
if (!parent) parent = document.body;
function append(str){
var el = domify(str)
var src = el.src || '';
if (el.src.indexOf(match) === -1) return write(str);
if ('SCRIPT' == el.tagName) el = recreate(el);
parent.appendChild(el);
document.write = write;
fn && fn();
}
};
/**
* Re-create the given `script`.
*
* domify() actually adds the script to he dom
* and then immediately removes it so the script
* will never be loaded :/
*
* @param {Element} script
* @api public
*/
function recreate(script){
var ret = document.createElement('script');
ret.src = script.src;
ret.async = script.async;
ret.defer = script.defer;
return ret;
}
});
require.register("ianstormtaylor-to-camel-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toCamelCase`.
*/
module.exports = toCamelCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-capital-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toCapitalCase`.
*/
module.exports = toCapitalCase;
/**
* Convert a `string` to capital case.
*
* @param {String} string
* @return {String}
*/
function toCapitalCase (string) {
return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) {
return previous + letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-constant-case/index.js", function(exports, require, module){
var snake = require('to-snake-case');
/**
* Expose `toConstantCase`.
*/
module.exports = toConstantCase;
/**
* Convert a `string` to constant case.
*
* @param {String} string
* @return {String}
*/
function toConstantCase (string) {
return snake(string).toUpperCase();
}
});
require.register("ianstormtaylor-to-dot-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toDotCase`.
*/
module.exports = toDotCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toDotCase (string) {
return toSpace(string).replace(/\s/g, '.');
}
});
require.register("ianstormtaylor-to-pascal-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toPascalCase`.
*/
module.exports = toPascalCase;
/**
* Convert a `string` to pascal case.
*
* @param {String} string
* @return {String}
*/
function toPascalCase (string) {
return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-sentence-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSentenceCase`.
*/
module.exports = toSentenceCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toSentenceCase (string) {
return clean(string).replace(/[a-z]/i, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-slug-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSlugCase`.
*/
module.exports = toSlugCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toSlugCase (string) {
return toSpace(string).replace(/\s/g, '-');
}
});
require.register("component-escape-regexp/index.js", function(exports, require, module){
/**
* Escape regexp special characters in `str`.
*
* @param {String} str
* @return {String}
* @api public
*/
module.exports = function(str){
return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
};
});
require.register("ianstormtaylor-map/index.js", function(exports, require, module){
var each = require('each');
/**
* Map an array or object.
*
* @param {Array|Object} obj
* @param {Function} iterator
* @return {Mixed}
*/
module.exports = function map (obj, iterator) {
var arr = [];
each(obj, function (o) {
arr.push(iterator.apply(null, arguments));
});
return arr;
};
});
require.register("ianstormtaylor-title-case-minors/index.js", function(exports, require, module){
module.exports = [
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'en',
'for',
'from',
'how',
'if',
'in',
'neither',
'nor',
'of',
'on',
'only',
'onto',
'out',
'or',
'per',
'so',
'than',
'that',
'the',
'to',
'until',
'up',
'upon',
'v',
'v.',
'versus',
'vs',
'vs.',
'via',
'when',
'with',
'without',
'yet'
];
});
require.register("ianstormtaylor-to-title-case/index.js", function(exports, require, module){
var capital = require('to-capital-case')
, escape = require('escape-regexp')
, map = require('map')
, minors = require('title-case-minors');
/**
* Expose `toTitleCase`.
*/
module.exports = toTitleCase;
/**
* Minors.
*/
var escaped = map(minors, escape);
var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig');
var colonMatcher = /:\s*(\w)/g;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toTitleCase (string) {
return capital(string)
.replace(minorMatcher, function (minor) {
return minor.toLowerCase();
})
.replace(colonMatcher, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-case/lib/index.js", function(exports, require, module){
var cases = require('./cases');
/**
* Expose `determineCase`.
*/
module.exports = exports = determineCase;
/**
* Determine the case of a `string`.
*
* @param {String} string
* @return {String|Null}
*/
function determineCase (string) {
for (var key in cases) {
if (key == 'none') continue;
var convert = cases[key];
if (convert(string) == string) return key;
}
return null;
}
/**
* Define a case by `name` with a `convert` function.
*
* @param {String} name
* @param {Object} convert
*/
exports.add = function (name, convert) {
exports[name] = cases[name] = convert;
};
/**
* Add all the `cases`.
*/
for (var key in cases) {
exports.add(key, cases[key]);
}
});
require.register("ianstormtaylor-case/lib/cases.js", function(exports, require, module){
var camel = require('to-camel-case')
, capital = require('to-capital-case')
, constant = require('to-constant-case')
, dot = require('to-dot-case')
, none = require('to-no-case')
, pascal = require('to-pascal-case')
, sentence = require('to-sentence-case')
, slug = require('to-slug-case')
, snake = require('to-snake-case')
, space = require('to-space-case')
, title = require('to-title-case');
/**
* Camel.
*/
exports.camel = camel;
/**
* Pascal.
*/
exports.pascal = pascal;
/**
* Dot. Should precede lowercase.
*/
exports.dot = dot;
/**
* Slug. Should precede lowercase.
*/
exports.slug = slug;
/**
* Snake. Should precede lowercase.
*/
exports.snake = snake;
/**
* Space. Should precede lowercase.
*/
exports.space = space;
/**
* Constant. Should precede uppercase.
*/
exports.constant = constant;
/**
* Capital. Should precede sentence and title.
*/
exports.capital = capital;
/**
* Title.
*/
exports.title = title;
/**
* Sentence.
*/
exports.sentence = sentence;
/**
* Convert a `string` to lower case from camel, slug, etc. Different that the
* usual `toLowerCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.lower = function (string) {
return none(string).toLowerCase();
};
/**
* Convert a `string` to upper case from camel, slug, etc. Different that the
* usual `toUpperCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.upper = function (string) {
return none(string).toUpperCase();
};
/**
* Invert each character in a `string` from upper to lower and vice versa.
*
* @param {String} string
* @return {String}
*/
exports.inverse = function (string) {
for (var i = 0, char; char = string[i]; i++) {
if (!/[a-z]/i.test(char)) continue;
var upper = char.toUpperCase();
var lower = char.toLowerCase();
string[i] = char == upper ? lower : upper;
}
return string;
};
/**
* None.
*/
exports.none = none;
});
require.register("segmentio-obj-case/index.js", function(exports, require, module){
var Case = require('case');
var cases = [
Case.upper,
Case.lower,
Case.snake,
Case.pascal,
Case.camel,
Case.constant,
Case.title,
Case.capital,
Case.sentence
];
/**
* Module exports, export
*/
module.exports = module.exports.find = multiple(find);
/**
* Export the replacement function, return the modified object
*/
module.exports.replace = function (obj, key, val) {
multiple(replace).apply(this, arguments);
return obj;
};
/**
* Export the delete function, return the modified object
*/
module.exports.del = function (obj, key) {
multiple(del).apply(this, arguments);
return obj;
};
/**
* Compose applying the function to a nested key
*/
function multiple (fn) {
return function (obj, key, val) {
var keys = key.split('.');
if (keys.length === 0) return;
while (keys.length > 1) {
key = keys.shift();
obj = find(obj, key);
if (obj === null || obj === undefined) return;
}
key = keys.shift();
return fn(obj, key, val);
};
}
/**
* Find an object by its key
*
* find({ first_name : 'Calvin' }, 'firstName')
*/
function find (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) return obj[cased];
}
}
/**
* Delete a value for a given key
*
* del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }
*/
function del (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) delete obj[cased];
}
return obj;
}
/**
* Replace an objects existing value with a new one
*
* replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
*/
function replace (obj, key, val) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) obj[cased] = val;
}
return obj;
}
});
require.register("segmentio-analytics.js-integrations/index.js", function(exports, require, module){
var integrations = require('./lib/slugs');
var each = require('each');
/**
* Expose the integrations, using their own `name` from their `prototype`.
*/
each(integrations, function (slug) {
var plugin = require('./lib/' + slug);
var name = plugin.Integration.prototype.name;
exports[name] = plugin;
});
});
require.register("segmentio-analytics.js-integrations/lib/adroll.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(AdRoll);
user = analytics.user(); // store for later
};
/**
* Expose `AdRoll` integration.
*/
var AdRoll = exports.Integration = integration('AdRoll')
.assumesPageview()
.readyOnLoad()
.global('__adroll_loaded')
.global('adroll_adv_id')
.global('adroll_pix_id')
.global('adroll_custom_data')
.option('events', {})
.option('advId', '')
.option('pixId', '');
/**
* Initialize.
*
* http://support.adroll.com/getting-started-in-4-easy-steps/#step-one
* http://support.adroll.com/enhanced-conversion-tracking/
*
* @param {Object} page
*/
AdRoll.prototype.initialize = function (page) {
window.adroll_adv_id = this.options.advId;
window.adroll_pix_id = this.options.pixId;
window.__adroll_loaded = true;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
AdRoll.prototype.loaded = function () {
return window.__adroll;
};
/**
* Load the AdRoll library.
*
* @param {Function} callback
*/
AdRoll.prototype.load = function (callback) {
load({
http: 'http://a.adroll.com/j/roundtrip.js',
https: 'https://s.adroll.com/j/roundtrip.js'
}, callback);
};
/**
* Track.
*
* @param {Track} track
*/
AdRoll.prototype.track = function(track){
var events = this.options.events;
var total = track.revenue();
var event = track.event();
if (has.call(events, event)) event = events[event];
var data = {
adroll_conversion_value_in_dollars: total || 0,
order_id: track.orderId() || 0,
adroll_segments: event
};
if (user.id()) data.user_id = user.id();
window.__adroll.record_user(data);
};
});
require.register("segmentio-analytics.js-integrations/lib/adwords.js", function(exports, require, module){
var onbody = require('on-body');
var integration = require('integration');
var load = require('load-script');
var domify = require('domify');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(AdWords);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdWords`
*/
var AdWords = exports.Integration = integration('AdWords')
.readyOnLoad()
.option('conversionId', '')
.option('events', {});
/**
* Load
*
* @param {Function} fn
* @api public
*/
AdWords.prototype.load = function(fn){
onbody(fn);
};
/**
* Loaded.
*
* @return {Boolean}
* @api public
*/
AdWords.prototype.loaded = function(){
return !! document.body;
};
/**
* Track.
*
* @param {Track}
* @api public
*/
AdWords.prototype.track = function(track){
var id = this.options.conversionId;
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return this.conversion({
value: track.revenue() || 0,
label: events[event],
conversionId: id
});
};
/**
* Report AdWords conversion.
*
* @param {Object} globals
* @api private
*/
AdWords.prototype.conversion = function(obj, fn){
if (this.reporting) return this.wait(obj);
this.reporting = true;
this.debug('sending %o', obj);
var self = this;
var write = document.write;
document.write = append;
window.google_conversion_id = obj.conversionId;
window.google_conversion_language = 'en';
window.google_conversion_format = '3';
window.google_conversion_color = 'ffffff';
window.google_conversion_label = obj.label;
window.google_conversion_value = obj.value;
window.google_remarketing_only = false;
load('//www.googleadservices.com/pagead/conversion.js', fn);
function append(str){
var el = domify(str);
if (!el.src) return write(str);
if (!/googleadservices/.test(el.src)) return write(str);
self.debug('append %o', el);
document.body.appendChild(el);
document.write = write;
self.reporting = null;
}
};
/**
* Wait until a conversion is sent with `obj`.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
AdWords.prototype.wait = function(obj){
var self = this;
var id = setTimeout(function(){
clearTimeout(id);
self.conversion(obj);
}, 50);
};
});
require.register("segmentio-analytics.js-integrations/lib/alexa.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Alexa);
};
/**
* Expose Alexa integration.
*/
var Alexa = exports.Integration = integration('Alexa')
.assumesPageview()
.readyOnLoad()
.global('_atrk_opts')
.option('account', null)
.option('domain', '')
.option('dynamic', true);
/**
* Initialize.
*
* @param {Object} page
*/
Alexa.prototype.initialize = function (page) {
window._atrk_opts = {
atrk_acct: this.options.account,
domain: this.options.domain,
dynamic: this.options.dynamic
};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Alexa.prototype.loaded = function () {
return !! window.atrk;
};
/**
* Load the Alexa library.
*
* @param {Function} callback
*/
Alexa.prototype.load = function (callback) {
load('//d31qbv1cthcecs.cloudfront.net/atrk.js', function(err){
if (err) return callback(err);
window.atrk();
callback();
});
};
});
require.register("segmentio-analytics.js-integrations/lib/amplitude.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Amplitude);
};
/**
* Expose `Amplitude` integration.
*/
var Amplitude = exports.Integration = integration('Amplitude')
.assumesPageview()
.readyOnInitialize()
.global('amplitude')
.option('apiKey', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://github.com/amplitude/Amplitude-Javascript
*
* @param {Object} page
*/
Amplitude.prototype.initialize = function (page) {
(function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"]; for(var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document);
window.amplitude.init(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Amplitude.prototype.loaded = function () {
return !! (window.amplitude && window.amplitude.options);
};
/**
* Load the Amplitude library.
*
* @param {Function} callback
*/
Amplitude.prototype.load = function (callback) {
load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Amplitude.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Identify.
*
* @param {Facade} identify
*/
Amplitude.prototype.identify = function (identify) {
var id = identify.userId();
var traits = identify.traits();
if (id) window.amplitude.setUserId(id);
if (traits) window.amplitude.setGlobalUserProperties(traits);
};
/**
* Track.
*
* @param {Track} event
*/
Amplitude.prototype.track = function (track) {
var props = track.properties();
var event = track.event();
window.amplitude.logEvent(event, props);
};
});
require.register("segmentio-analytics.js-integrations/lib/awesm.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesm);
user = analytics.user(); // store for later
};
/**
* Expose `Awesm` integration.
*/
var Awesm = exports.Integration = integration('awe.sm')
.assumesPageview()
.readyOnLoad()
.global('AWESM')
.option('apiKey', '')
.option('events', {});
/**
* Initialize.
*
* http://developers.awe.sm/guides/javascript/
*
* @param {Object} page
*/
Awesm.prototype.initialize = function (page) {
window.AWESM = { api_key: this.options.apiKey };
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesm.prototype.loaded = function () {
return !! window.AWESM._exists;
};
/**
* Load.
*
* @param {Function} callback
*/
Awesm.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widgets.awe.sm/v3/widgets.js?key=' + key + '&async=true', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Awesm.prototype.track = function (track) {
var event = track.event();
var goal = this.options.events[event];
if (!goal) return;
window.AWESM.convert(goal, track.cents(), null, user.id());
};
});
require.register("segmentio-analytics.js-integrations/lib/awesomatic.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var noop = function(){};
var onBody = require('on-body');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesomatic);
user = analytics.user(); // store for later
};
/**
* Expose `Awesomatic` integration.
*/
var Awesomatic = exports.Integration = integration('Awesomatic')
.assumesPageview()
.global('Awesomatic')
.global('AwesomaticSettings')
.global('AwsmSetup')
.global('AwsmTmp')
.option('appId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Awesomatic.prototype.initialize = function (page) {
var self = this;
var id = user.id();
var options = user.traits();
options.appId = this.options.appId;
if (id) options.user_id = id;
this.load(function () {
window.Awesomatic.initialize(options, function () {
self.emit('ready'); // need to wait for initialize to callback
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesomatic.prototype.loaded = function () {
return is.object(window.Awesomatic);
};
/**
* Load the Awesomatic library.
*
* @param {Function} callback
*/
Awesomatic.prototype.load = function (callback) {
var url = 'https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js';
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bing-ads.js", function(exports, require, module){
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bing);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Bing`
*/
var Bing = exports.Integration = integration('Bing Ads')
.readyOnInitialize()
.option('siteId', '')
.option('domainId', '')
.option('goals', {});
/**
* Track.
*
* @param {Track} track
*/
Bing.prototype.track = function(track){
var goals = this.options.goals;
var traits = track.traits();
var event = track.event();
if (!has.call(goals, event)) return;
var goal = goals[event];
return exports.load(goal, track.revenue(), this.options);
};
/**
* Load conversion.
*
* @param {Mixed} goal
* @param {Number} revenue
* @param {String} currency
* @return {IFrame}
* @api private
*/
exports.load = function(goal, revenue, options){
var iframe = document.createElement('iframe');
iframe.src = '//flex.msn.com/mstag/tag/' + options.siteId
+ '/analytics.html'
+ '?domainId=' + options.domainId
+ '&revenue=' + revenue || 0
+ '&actionid=' + goal;
+ '&dedup=1'
+ '&type=1'
iframe.width = 1;
iframe.height = 1;
return iframe;
};
});
require.register("segmentio-analytics.js-integrations/lib/bronto.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var Track = require('facade').Track;
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bronto);
};
/**
* Expose `Bronto` integration.
*/
var Bronto = exports.Integration = integration('Bronto')
.readyOnLoad()
.global('__bta')
.option('siteId', '')
.option('host', '');
/**
* Initialize.
*
* http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB
* http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB
*
* @param {Object} page
*/
Bronto.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bronto.prototype.loaded = function(){
return this.bta;
};
/**
* Load the Bronto library.
*
* @param {Function} fn
*/
Bronto.prototype.load = function(fn){
var self = this;
load('//p.bm23.com/bta.js', function(err){
if (err) return fn(err);
var opts = self.options;
self.bta = new window.__bta(opts.siteId);
if (opts.host) self.bta.setHost(opts.host);
fn();
});
};
/**
* Track.
*
* @param {Track} event
*/
Bronto.prototype.track = function(track){
var revenue = track.revenue();
var event = track.event();
var type = 'number' == typeof revenue ? '$' : 't';
this.bta.addConversionLegacy(type, event, revenue);
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
Bronto.prototype.completedOrder = function(track){
var products = track.products();
var props = track.properties();
var items = [];
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
item_id: track.id() || track.sku(),
desc: product.description || track.name(),
quantity: track.quantity(),
amount: track.price(),
});
});
// add conversion
this.bta.addConversion({
order_id: track.orderId(),
date: props.date || new Date,
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/bugherd.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(BugHerd);
};
/**
* Expose `BugHerd` integration.
*/
var BugHerd = exports.Integration = integration('BugHerd')
.assumesPageview()
.readyOnLoad()
.global('BugHerdConfig')
.global('_bugHerd')
.option('apiKey', '')
.option('showFeedbackTab', true);
/**
* Initialize.
*
* http://support.bugherd.com/home
*
* @param {Object} page
*/
BugHerd.prototype.initialize = function (page) {
window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
BugHerd.prototype.loaded = function () {
return !! window._bugHerd;
};
/**
* Load the BugHerd library.
*
* @param {Function} callback
*/
BugHerd.prototype.load = function (callback) {
load('//www.bugherd.com/sidebarv2.js?apikey=' + this.options.apiKey, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bugsnag.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var extend = require('extend');
var load = require('load-script');
var onError = require('on-error');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Bugsnag);
};
/**
* Expose `Bugsnag` integration.
*/
var Bugsnag = exports.Integration = integration('Bugsnag')
.readyOnLoad()
.global('Bugsnag')
.option('apiKey', '');
/**
* Initialize.
*
* https://bugsnag.com/docs/notifiers/js
*
* @param {Object} page
*/
Bugsnag.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bugsnag.prototype.loaded = function () {
return is.object(window.Bugsnag);
};
/**
* Load.
*
* @param {Function} callback (optional)
*/
Bugsnag.prototype.load = function (callback) {
var apiKey = this.options.apiKey;
load('//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js', function(err){
if (err) return callback(err);
window.Bugsnag.apiKey = apiKey;
callback();
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
Bugsnag.prototype.identify = function (identify) {
window.Bugsnag.metaData = window.Bugsnag.metaData || {};
extend(window.Bugsnag.metaData, identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/chartbeat.js", function(exports, require, module){
var integration = require('integration');
var onBody = require('on-body');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Chartbeat);
};
/**
* Expose `Chartbeat` integration.
*/
var Chartbeat = exports.Integration = integration('Chartbeat')
.assumesPageview()
.readyOnLoad()
.global('_sf_async_config')
.global('_sf_endpt')
.global('pSUPERFLY')
.option('domain', '')
.option('uid', null);
/**
* Initialize.
*
* http://chartbeat.com/docs/configuration_variables/
*
* @param {Object} page
*/
Chartbeat.prototype.initialize = function (page) {
window._sf_async_config = this.options;
onBody(function () {
window._sf_endpt = new Date().getTime();
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Chartbeat.prototype.loaded = function () {
return !! window.pSUPERFLY;
};
/**
* Load the Chartbeat library.
*
* http://chartbeat.com/docs/adding_the_code/
*
* @param {Function} callback
*/
Chartbeat.prototype.load = function (callback) {
load({
https: 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js',
http: 'http://static.chartbeat.com/js/chartbeat.js'
}, callback);
};
/**
* Page.
*
* http://chartbeat.com/docs/handling_virtual_page_changes/
*
* @param {Page} page
*/
Chartbeat.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
window.pSUPERFLY.virtualPage(props.path, name || props.title);
};
});
require.register("segmentio-analytics.js-integrations/lib/churnbee.js", function(exports, require, module){
/**
* Module dependencies.
*/
var push = require('global-queue')('_cbq');
var integration = require('integration');
var load = require('load-script');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Supported events
*/
var supported = {
activation: true,
changePlan: true,
register: true,
refund: true,
charge: true,
cancel: true,
login: true
};
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(ChurnBee);
};
/**
* Expose `ChurnBee` integration.
*/
var ChurnBee = exports.Integration = integration('ChurnBee')
.readyOnInitialize()
.global('_cbq')
.global('ChurnBee')
.option('events', {})
.option('apiKey', '');
/**
* Initialize.
*
* https://churnbee.com/docs
*
* @param {Object} page
*/
ChurnBee.prototype.initialize = function(page){
push('_setApiKey', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
ChurnBee.prototype.loaded = function(){
return !! window.ChurnBee;
};
/**
* Load the ChurnBee library.
*
* @param {Function} fn
*/
ChurnBee.prototype.load = function(fn){
load('//api.churnbee.com/cb.js', fn);
};
/**
* Track.
*
* @param {Track} event
*/
ChurnBee.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (has.call(events, event)) event = events[event];
if (true != supported[event]) return;
push(event, track.properties({ revenue: 'amount' }));
};
});
require.register("segmentio-analytics.js-integrations/lib/clicky.js", function(exports, require, module){
var Identify = require('facade').Identify;
var extend = require('extend');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Clicky);
user = analytics.user(); // store for later
};
/**
* Expose `Clicky` integration.
*/
var Clicky = exports.Integration = integration('Clicky')
.assumesPageview()
.readyOnLoad()
.global('clicky')
.global('clicky_site_ids')
.global('clicky_custom')
.option('siteId', null);
/**
* Initialize.
*
* http://clicky.com/help/customization
*
* @param {Object} page
*/
Clicky.prototype.initialize = function (page) {
window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId];
this.identify(new Identify({
userId: user.id(),
traits: user.traits()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Clicky.prototype.loaded = function () {
return is.object(window.clicky);
};
/**
* Load the Clicky library.
*
* @param {Function} callback
*/
Clicky.prototype.load = function (callback) {
load('//static.getclicky.com/js', callback);
};
/**
* Page.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Page} page
*/
Clicky.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
window.clicky.log(properties.path, name || properties.title);
};
/**
* Identify.
*
* @param {Identify} id (optional)
*/
Clicky.prototype.identify = function (identify) {
window.clicky_custom = window.clicky_custom || {};
window.clicky_custom.session = window.clicky_custom.session || {};
extend(window.clicky_custom.session, identify.traits());
};
/**
* Track.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Track} event
*/
Clicky.prototype.track = function (track) {
window.clicky.goal(track.event(), track.revenue());
};
});
require.register("segmentio-analytics.js-integrations/lib/comscore.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Comscore);
};
/**
* Expose `Comscore` integration.
*/
var Comscore = exports.Integration = integration('comScore')
.assumesPageview()
.readyOnLoad()
.global('_comscore')
.global('COMSCORE')
.option('c1', '2')
.option('c2', '');
/**
* Initialize.
*
* @param {Object} page
*/
Comscore.prototype.initialize = function (page) {
window._comscore = window._comscore || [this.options];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Comscore.prototype.loaded = function () {
return !! window.COMSCORE;
};
/**
* Load.
*
* @param {Function} callback
*/
Comscore.prototype.load = function (callback) {
load({
http: 'http://b.scorecardresearch.com/beacon.js',
https: 'https://sb.scorecardresearch.com/beacon.js'
}, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(CrazyEgg);
};
/**
* Expose `CrazyEgg` integration.
*/
var CrazyEgg = exports.Integration = integration('Crazy Egg')
.assumesPageview()
.readyOnLoad()
.global('CE2')
.option('accountNumber', '');
/**
* Initialize.
*
* @param {Object} page
*/
CrazyEgg.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
CrazyEgg.prototype.loaded = function () {
return !! window.CE2;
};
/**
* Load the Crazy Egg library.
*
* @param {Function} callback
*/
CrazyEgg.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,4) + '/' + number.slice(4);
var cache = Math.floor(new Date().getTime()/3600000);
var url = '//dnn506yrbagrg.cloudfront.net/pages/scripts/' + path + '.js?' + cache;
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/curebit.js", function(exports, require, module){
var clone = require('clone');
var each = require('each');
var Identify = require('facade').Identify;
var integration = require('integration');
var iso = require('to-iso-string');
var load = require('load-script');
var push = require('global-queue')('_curebitq');
var Track = require('facade').Track;
/**
* User reference
*/
var user;
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Curebit);
user = analytics.user();
};
/**
* Expose `Curebit` integration
*/
var Curebit = exports.Integration = integration('Curebit')
.readyOnLoad() // so iframes get loaded right away
.global('_curebitq')
.global('curebit')
.option('siteId', '')
.option('iframeWidth', '100%')
.option('iframeHeight', '480')
.option('iframeBorder', 0)
.option('iframeId', 'curebit_integration')
.option('responsive', true)
.option('device', '')
.option('insertIntoId', '')
.option('campaigns', {})
.option('server', 'https://www.curebit.com');
/**
* Initialize.
*
* @param {Object} page
*/
Curebit.prototype.initialize = function(page){
push('init', {
site_id: this.options.siteId,
server: this.options.server
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Curebit.prototype.loaded = function(){
return !! window.curebit;
};
/**
* Load Curebit's Javascript library.
*
* @param {Function} fn
*/
Curebit.prototype.load = function(fn){
var url = '//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js';
load(url, fn);
};
/**
* Page.
*
* Call the `register_affiliate` method of the Curebit API that will load a
* custom iframe onto the page, only if this page's path is marked as a
* campaign.
*
* http://www.curebit.com/docs/affiliate/registration
*
* @param {Page} page
*/
Curebit.prototype.page = function(page){
var campaigns = this.options.campaigns;
var path = window.location.pathname;
if (!campaigns[path]) return;
var tags = (campaigns[path] || '').split(',');
if (!tags.length) return;
var settings = {
responsive: this.options.responsive,
device: this.options.device,
campaign_tags: tags,
iframe: {
width: this.options.iframeWidth,
height: this.options.iframeHeight,
id: this.options.iframeId,
frameborder: this.options.iframeBorder,
container: this.options.insertIntoId
}
};
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
// if we have an email, add any information about the user
if (identify.email()) {
settings.affiliate_member = {
email: identify.email(),
first_name: identify.firstName(),
last_name: identify.lastName(),
customer_id: identify.userId()
};
}
// remove iframe if exists.
var iframe = document.getElementById(this.options.iframeId);
if (iframe) {
this.debug('Warning: Curebit iframe may have been added twice. '
+ 'Double check `analytics.page()` is only being called once.');
iframe.parentNode.removeChild(iframe);
}
push('register_affiliate', settings);
};
/**
* Completed order.
*
* Fire the Curebit `register_purchase` with the order details and items.
*
* https://www.curebit.com/docs/ecommerce/custom
*
* @param {Track} track
*/
Curebit.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
traits: user.traits(),
userId: user.id()
});
each(products, function(product){
var track = new Track({ properties: product });
items.push({
product_id: track.id() || track.sku(),
quantity: track.quantity(),
image_url: product.image,
price: track.price(),
title: track.name(),
url: product.url,
});
});
push('register_purchase', {
order_date: iso(props.date || new Date),
order_number: orderId,
coupon_code: track.coupon(),
subtotal: track.total(),
customer_id: identify.userId(),
first_name: identify.firstName(),
last_name: identify.lastName(),
email: identify.email(),
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/customerio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Customerio);
user = analytics.user(); // store for later
};
/**
* Expose `Customerio` integration.
*/
var Customerio = exports.Integration = integration('Customer.io')
.assumesPageview()
.readyOnInitialize()
.global('_cio')
.option('siteId', '');
/**
* Initialize.
*
* http://customer.io/docs/api/javascript.html
*
* @param {Object} page
*/
Customerio.prototype.initialize = function (page) {
window._cio = window._cio || [];
(function() {var a,b,c; a = function (f) {return function () {window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Customerio.prototype.loaded = function () {
return !! (window._cio && window._cio.pageHasLoaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Customerio.prototype.load = function (callback) {
var script = load('https://assets.customer.io/assets/track.js', callback);
script.id = 'cio-tracker';
script.setAttribute('data-site-id', this.options.siteId);
};
/**
* Identify.
*
* http://customer.io/docs/api/javascript.html#section-Identify_customers
*
* @param {Identify} identify
*/
Customerio.prototype.identify = function (identify) {
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
window._cio.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Customerio.prototype.group = function (group) {
var traits = group.traits();
traits = alias(traits, function (trait) {
return 'Group ' + trait;
});
this.identify(new Identify({
userId: user.id(),
traits: traits
}));
};
/**
* Track.
*
* http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
*
* @param {Track} track
*/
Customerio.prototype.track = function (track) {
var properties = track.properties();
properties = convertDates(properties, convertDate);
window._cio.track(track.event(), properties);
};
/**
* Convert a date to the format Customer.io supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/drip.js", function(exports, require, module){
var alias = require('alias');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_dcq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Drip);
};
/**
* Expose `Drip` integration.
*/
var Drip = exports.Integration = integration('Drip')
.assumesPageview()
.readyOnLoad()
.global('dc')
.global('_dcq')
.global('_dcs')
.option('account', '');
/**
* Initialize.
*
* @param {Object} page
*/
Drip.prototype.initialize = function (page) {
window._dcq = window._dcq || [];
window._dcs = window._dcs || {};
window._dcs.account = this.options.account;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Drip.prototype.loaded = function () {
return is.object(window.dc);
};
/**
* Load.
*
* @param {Function} callback
*/
Drip.prototype.load = function (callback) {
load('//tag.getdrip.com/' + this.options.account + '.js', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Drip.prototype.track = function (track) {
var props = track.properties();
var cents = Math.round(track.cents());
props.action = track.event();
if (cents) props.value = cents;
delete props.revenue;
push('track', props);
};
});
require.register("segmentio-analytics.js-integrations/lib/errorception.js", function(exports, require, module){
var callback = require('callback');
var extend = require('extend');
var integration = require('integration');
var load = require('load-script');
var onError = require('on-error');
var push = require('global-queue')('_errs');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Errorception);
};
/**
* Expose `Errorception` integration.
*/
var Errorception = exports.Integration = integration('Errorception')
.assumesPageview()
.readyOnInitialize()
.global('_errs')
.option('projectId', '')
.option('meta', true);
/**
* Initialize.
*
* https://github.com/amplitude/Errorception-Javascript
*
* @param {Object} page
*/
Errorception.prototype.initialize = function (page) {
window._errs = window._errs || [this.options.projectId];
onError(push);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Errorception.prototype.loaded = function () {
return !! (window._errs && window._errs.push !== Array.prototype.push);
};
/**
* Load the Errorception library.
*
* @param {Function} callback
*/
Errorception.prototype.load = function (callback) {
load('//beacon.errorception.com/' + this.options.projectId + '.js', callback);
};
/**
* Identify.
*
* http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html
*
* @param {Object} identify
*/
Errorception.prototype.identify = function (identify) {
if (!this.options.meta) return;
var traits = identify.traits();
window._errs = window._errs || [];
window._errs.meta = window._errs.meta || {};
extend(window._errs.meta, traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/evergage.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_aaq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Evergage);
};
/**
* Expose `Evergage` integration.integration.
*/
var Evergage = exports.Integration = integration('Evergage')
.assumesPageview()
.readyOnInitialize()
.global('_aaq')
.option('account', '')
.option('dataset', '');
/**
* Initialize.
*
* @param {Object} page
*/
Evergage.prototype.initialize = function (page) {
var account = this.options.account;
var dataset = this.options.dataset;
window._aaq = window._aaq || [];
push('setEvergageAccount', account);
push('setDataset', dataset);
push('setUseSiteConfig', true);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Evergage.prototype.loaded = function () {
return !! (window._aaq && window._aaq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Evergage.prototype.load = function (callback) {
var account = this.options.account;
var dataset = this.options.dataset;
var url = '//cdn.evergage.com/beacon/' + account + '/' + dataset + '/scripts/evergage.min.js';
load(url, callback);
};
/**
* Page.
*
* @param {Page} page
*/
Evergage.prototype.page = function (page) {
var props = page.properties();
var name = page.name();
if (name) push('namePage', name);
each(props, function(key, value) {
push('setCustomField', key, value, 'page');
});
window.Evergage.init(true);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Evergage.prototype.identify = function (identify) {
var id = identify.userId();
if (!id) return;
push('setUser', id);
var traits = identify.traits({
email: 'userEmail',
name: 'userName'
});;
each(traits, function (key, value) {
push('setUserField', key, value, 'page');
});
};
/**
* Group.
*
* @param {Group} group
*/
Evergage.prototype.group = function (group) {
var props = group.traits();
var id = group.groupId();
if (!id) return;
push('setCompany', id);
each(props, function(key, value) {
push('setAccountField', key, value, 'page');
});
};
/**
* Track.
*
* @param {Track} track
*/
Evergage.prototype.track = function (track) {
push('trackAction', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js", function(exports, require, module){
var load = require('load-script');
var integration = require('integration');
var push = require('global-queue')('_fbq');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Facebook);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Facebook`
*/
var Facebook = exports.Integration = integration('Facebook Ads')
.readyOnInitialize()
.global('_fbq')
.option('currency', 'USD')
.option('events', {});
/**
* Initialize Facebook Ads.
*
* https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration
*
* @param {Object} page
*/
Facebook.prototype.initialize = function(page){
window._fbq = window._fbq || [];
this.load();
};
/**
* Load the Facebook Ads library.
*
* @param {Function} fn
*/
Facebook.prototype.load = function(fn){
load('//connect.facebook.net/en_US/fbds.js', fn);
window._fbq.loaded = true;
};
/**
* Loaded?
*
* @return {Boolean}
*/
Facebook.prototype.loaded = function(){
return !!window._fbq.loaded;
};
/**
* Track.
*
* @param {Track} track
*/
Facebook.prototype.track = function(track){
var events = this.options.events;
var traits = track.traits();
var event = track.event();
var revenue = track.revenue() || 0;
if (!has.call(events, event)) return;
push('track', events[event], {
value: String(revenue.toFixed(2)),
currency: this.options.currency
});
};
});
require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js", function(exports, require, module){
var push = require('global-queue')('_fxm');
var integration = require('integration');
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(FoxMetrics);
};
/**
* Expose `FoxMetrics` integration.
*/
var FoxMetrics = exports.Integration = integration('FoxMetrics')
.assumesPageview()
.readyOnInitialize()
.global('_fxm')
.option('appId', '');
/**
* Initialize.
*
* http://foxmetrics.com/documentation/apijavascript
*
* @param {Object} page
*/
FoxMetrics.prototype.initialize = function(page){
window._fxm = window._fxm || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
FoxMetrics.prototype.loaded = function(){
return !! (window._fxm && window._fxm.appId);
};
/**
* Load the FoxMetrics library.
*
* @param {Function} callback
*/
FoxMetrics.prototype.load = function(callback){
var id = this.options.appId;
load('//d35tca7vmefkrc.cloudfront.net/scripts/' + id + '.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
FoxMetrics.prototype.page = function(page){
var properties = page.proxy('properties');
var category = page.category();
var name = page.name();
this._category = category; // store for later
push(
'_fxm.pages.view',
properties.title, // title
name, // name
category, // category
properties.url, // url
properties.referrer // referrer
);
};
/**
* Identify.
*
* @param {Identify} identify
*/
FoxMetrics.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push(
'_fxm.visitor.profile',
id, // user id
identify.firstName(), // first name
identify.lastName(), // last name
identify.email(), // email
identify.address(), // address
undefined, // social
undefined, // partners
identify.traits() // attributes
);
};
/**
* Track.
*
* @param {Track} track
*/
FoxMetrics.prototype.track = function(track){
var props = track.properties();
var category = this._category || props.category;
push(track.event(), category, props);
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.viewedProduct = function(track){
ecommerce('productview', track);
};
/**
* Removed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.removedProduct = function(track){
ecommerce('removecartitem', track);
};
/**
* Added product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.addedProduct = function(track){
ecommerce('cartitem', track);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
// transaction
push('_fxm.ecommerce.order'
, orderId
, track.subtotal()
, track.shipping()
, track.tax()
, track.city()
, track.state()
, track.zip()
, track.quantity());
// items
each(track.products(), function(product){
var track = new Track({ properties: product });
ecommerce('purchaseitem', track, [
track.quantity(),
track.price(),
orderId
]);
});
};
/**
* Track ecommerce `event` with `track`
* with optional `arr` to append.
*
* @param {String} event
* @param {Track} track
* @param {Array} arr
* @api private
*/
function ecommerce(event, track, arr){
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
};
});
require.register("segmentio-analytics.js-integrations/lib/frontleaf.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Frontleaf);
};
/**
* Expose `Frontleaf` integration.
*/
var Frontleaf = exports.Integration = integration('Frontleaf')
.assumesPageview()
.readyOnInitialize()
.global('_fl')
.global('_flBaseUrl')
.option('baseUrl', 'https://api.frontleaf.com')
.option('token', '')
.option('stream', '');
/**
* Initialize.
*
* http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon
*
* @param {Object} page
*/
Frontleaf.prototype.initialize = function (page) {
window._fl = window._fl || [];
window._flBaseUrl = window._flBaseUrl || this.options.baseUrl;
this._push('setApiToken', this.options.token);
this._push('setStream', this.options.stream);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Frontleaf.prototype.loaded = function () {
return is.array(window._fl) && window._fl.ready === true ;
};
/**
* Load.
*
* @param {Function} fn
*/
Frontleaf.prototype.load = function (fn) {
if (document.getElementById('_fl')) return callback.async(fn);
var script = load(window._flBaseUrl + '/lib/tracker.js', fn);
script.id = '_fl';
};
/**
* Identify.
*
* @param {Identify} identify
*/
Frontleaf.prototype.identify = function (identify) {
var userId = identify.userId();
if (userId) {
this._push('setUser', {
id : userId,
name : identify.name() || identify.username(),
data : clean(identify.traits())
});
}
};
/**
* Group.
*
* @param {Group} group
*/
Frontleaf.prototype.group = function (group) {
var groupId = group.groupId();
if (groupId) {
this._push('setAccount', {
id : groupId,
name : group.proxy('traits.name'),
data : clean(group.traits())
});
}
};
/**
* Track.
*
* @param {Track} track
*/
Frontleaf.prototype.track = function (track) {
var event = track.event();
if (event) {
this._push('event', event, clean(track.properties()));
}
};
/**
* Push a command onto the global Frontleaf queue.
*
* @param {String} command
* @return {Object} args
* @api private
*/
Frontleaf.prototype._push = function (command) {
var args = [].slice.call(arguments, 1);
window._fl.push(function(t) { t[command].apply(command, args); });
}
/**
* Clean all nested objects and arrays.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function clean(obj) {
var ret = {};
// Remove traits/properties that are already represented
// outside of the data container
var excludeKeys = ["id","name","firstName","lastName"];
var len = excludeKeys.length;
for (var i = 0; i < len; i++) {
clear(obj, excludeKeys[i]);
}
// Flatten nested hierarchy, preserving arrays
obj = flatten(obj);
// Discard nulls, represent arrays as comma-separated strings
for (var key in obj) {
var val = obj[key];
if (null == val) {
continue;
}
if (is.array(val)) {
ret[key] = val.toString();
continue;
}
ret[key] = val;
}
return ret;
}
/**
* Remove a property from an object if set.
*
* @param {Object} obj
* @param {String} key
* @api private
*/
function clear(obj, key) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
/**
* Flatten a nested object into a single level space-delimited
* hierarchy.
*
* Based on https://github.com/hughsk/flat
*
* @param {Object} source
* @return {Object}
* @api private
*/
function flatten(source) {
var output = {};
function step(object, prev) {
for (var key in object) {
var value = object[key];
var newKey = prev ? prev + ' ' + key : key;
if (!is.array(value) && is.object(value)) {
return step(value, newKey);
}
output[newKey] = value;
}
}
step(source);
return output;
}
});
require.register("segmentio-analytics.js-integrations/lib/gauges.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_gauges');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Gauges);
};
/**
* Expose `Gauges` integration.
*/
var Gauges = exports.Integration = integration('Gauges')
.assumesPageview()
.readyOnInitialize()
.global('_gauges')
.option('siteId', '');
/**
* Initialize Gauges.
*
* http://get.gaug.es/documentation/tracking/
*
* @param {Object} page
*/
Gauges.prototype.initialize = function (page) {
window._gauges = window._gauges || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Gauges.prototype.loaded = function () {
return !! (window._gauges && window._gauges.push !== Array.prototype.push);
};
/**
* Load the Gauges library.
*
* @param {Function} callback
*/
Gauges.prototype.load = function (callback) {
var id = this.options.siteId;
var script = load('//secure.gaug.es/track.js', callback);
script.id = 'gauges-tracker';
script.setAttribute('data-site-id', id);
};
/**
* Page.
*
* @param {Page} page
*/
Gauges.prototype.page = function (page) {
push('track');
};
});
require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GetSatisfaction);
};
/**
* Expose `GetSatisfaction` integration.
*/
var GetSatisfaction = exports.Integration = integration('Get Satisfaction')
.assumesPageview()
.readyOnLoad()
.global('GSFN')
.option('widgetId', '');
/**
* Initialize.
*
* https://console.getsatisfaction.com/start/101022?signup=true#engage
*
* @param {Object} page
*/
GetSatisfaction.prototype.initialize = function (page) {
var widget = this.options.widgetId;
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + widget;
onBody(function (body) { body.appendChild(div); });
// usually the snippet is sync, so wait for it before initializing the tab
this.load(function () {
window.GSFN.loadWidget(widget, { containerId: id });
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
GetSatisfaction.prototype.loaded = function () {
return !! window.GSFN;
};
/**
* Load the Get Satisfaction library.
*
* @param {Function} callback
*/
GetSatisfaction.prototype.load = function (callback) {
load('https://loader.engage.gsfn.us/loader.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/google-analytics.js", function(exports, require, module){
var callback = require('callback');
var canonical = require('canonical');
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_gaq');
var Track = require('facade').Track;
var length = require('object').length;
var keys = require('object').keys;
var dot = require('obj-case');
var type = require('type');
var url = require('url');
var group;
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GA);
group = analytics.group();
user = analytics.user();
};
/**
* Expose `GA` integration.
*
* http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
*/
var GA = exports.Integration = integration('Google Analytics')
.readyOnLoad()
.global('ga')
.global('gaplugins')
.global('_gaq')
.global('GoogleAnalyticsObject')
.option('anonymizeIp', false)
.option('classic', false)
.option('domain', 'none')
.option('doubleClick', false)
.option('enhancedLinkAttribution', false)
.option('ignoredReferrers', null)
.option('includeSearch', false)
.option('siteSpeedSampleRate', 1)
.option('trackingId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('sendUserId', false)
.option('metrics', {})
.option('dimensions', {});
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
GA.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.initialize = integration.initializeClassic;
integration.load = integration.loadClassic;
integration.loaded = integration.loadedClassic;
integration.page = integration.pageClassic;
integration.track = integration.trackClassic;
integration.completedOrder = integration.completedOrderClassic;
});
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced
*/
GA.prototype.initialize = function () {
var opts = this.options;
var gMetrics = metrics(group.traits(), opts);
var uMetrics = metrics(user.traits(), opts);
var custom;
// setup the tracker globals
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function () {
window.ga.q = window.ga.q || [];
window.ga.q.push(arguments);
};
window.ga.l = new Date().getTime();
window.ga('create', opts.trackingId, {
cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string
siteSpeedSampleRate: opts.siteSpeedSampleRate,
allowLinker: true
});
// display advertising
if (opts.doubleClick) {
window.ga('require', 'displayfeatures');
}
// send global id
if (opts.sendUserId && user.id()) {
window.ga('set', '&uid', user.id());
}
// anonymize after initializing, otherwise a warning is shown
// in google analytics debugger
if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true);
// custom dimensions & metrics
if (length(gMetrics)) window.ga('set', gMetrics);
if (length(uMetrics)) window.ga('set', uMetrics);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
GA.prototype.loaded = function () {
return !! window.gaplugins;
};
/**
* Load the Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.load = function (callback) {
load('//www.google-analytics.com/analytics.js', callback);
};
/**
* Page.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
*
* @param {Page} page
*/
GA.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var pageview = {};
var track;
this._category = category; // store for later
// add metrics and dimensions
var hit = metrics(page.properties(), this.options);
hit.page = path(props, this.options);
hit.title = name || props.title;
hit.location = props.url;
// send
window.ga('send', 'pageview', hit);
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/events
* https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference
*
* @param {Track} event
*/
GA.prototype.track = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
// metrics & dimensions
var event = metrics(props, this.options);
// event
event.eventAction = track.event();
event.eventCategory = props.category || this._category || 'All';
event.eventLabel = props.label;
event.eventValue = formatValue(props.value || track.revenue());
event.nonInteraction = props.noninteraction || opts.noninteraction;
// send
window.ga('send', 'event', event);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrder = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
// require ecommerce
if (!this.ecommerce) {
window.ga('require', 'ecommerce', 'ecommerce.js');
this.ecommerce = true;
}
// add transaction
window.ga('ecommerce:addTransaction', {
affiliation: props.affiliation,
shipping: track.shipping(),
revenue: total,
tax: track.tax(),
id: orderId
});
// add products
each(products, function(product){
var track = new Track({ properties: product });
window.ga('ecommerce:addItem', {
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
sku: track.sku(),
id: orderId
});
});
// send
window.ga('ecommerce:send');
};
/**
* Initialize (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*/
GA.prototype.initializeClassic = function () {
var opts = this.options;
var anonymize = opts.anonymizeIp;
var db = opts.doubleClick;
var domain = opts.domain;
var enhanced = opts.enhancedLinkAttribution;
var ignore = opts.ignoredReferrers;
var sample = opts.siteSpeedSampleRate;
window._gaq = window._gaq || [];
push('_setAccount', opts.trackingId);
push('_setAllowLinker', true);
if (anonymize) push('_gat._anonymizeIp');
if (domain) push('_setDomainName', domain);
if (sample) push('_setSiteSpeedSampleRate', sample);
if (enhanced) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
push('_require', 'inpage_linkid', pluginUrl);
}
if (ignore) {
if (!is.array(ignore)) ignore = [ignore];
each(ignore, function (domain) {
push('_addIgnoredRef', domain);
});
}
this.load();
};
/**
* Loaded? (classic)
*
* @return {Boolean}
*/
GA.prototype.loadedClassic = function () {
return !! (window._gaq && window._gaq.push !== Array.prototype.push);
};
/**
* Load the classic Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.loadClassic = function (callback) {
if (this.options.doubleClick) {
load('//stats.g.doubleclick.net/dc.js', callback);
} else {
load({
http: 'http://www.google-analytics.com/ga.js',
https: 'https://ssl.google-analytics.com/ga.js'
}, callback);
}
};
/**
* Page (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*
* @param {Page} page
*/
GA.prototype.pageClassic = function (page) {
var opts = page.options(this.name);
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
push('_trackPageview', path(props, this.options));
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
*
* @param {Track} track
*/
GA.prototype.trackClassic = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var category = this._category || props.category || 'All';
var label = props.label;
var value = formatValue(revenue || props.value);
var noninteraction = props.noninteraction || opts.noninteraction;
push('_trackEvent', category, event, label, value, noninteraction);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrderClassic = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products() || [];
var props = track.properties();
// required
if (!orderId) return;
// add transaction
push('_addTrans'
, orderId
, props.affiliation
, total
, track.tax()
, track.shipping()
, track.city()
, track.state()
, track.country());
// add items
each(products, function(product){
var track = new Track({ properties: product });
push('_addItem'
, orderId
, track.sku()
, track.name()
, track.category()
, track.price()
, track.quantity());
})
// send
push('_trackTrans');
};
/**
* Return the path based on `properties` and `options`.
*
* @param {Object} properties
* @param {Object} options
*/
function path (properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
/**
* Format the value property to Google's liking.
*
* @param {Number} value
* @return {Number}
*/
function formatValue (value) {
if (!value || value < 0) return 0;
return Math.round(value);
}
/**
* Map google's custom dimensions & metrics with `obj`.
*
* Example:
*
* metrics({ revenue: 1.9 }, { { metrics : { metric8: 'revenue' } });
* // => { metric8: 1.9 }
*
* metrics({ revenue: 1.9 }, {});
* // => {}
*
* @param {Object} obj
* @param {Object} data
* @return {Object|null}
* @api private
*/
function metrics(obj, data){
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = metrics[names[i]] || dimensions[names[i]];
var value = dot(obj, name);
if (null == value) continue;
ret[names[i]] = value;
}
return ret;
}
});
require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js", function(exports, require, module){
var push = require('global-queue')('dataLayer', { wrap: false });
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(GTM);
};
/**
* Expose `GTM`
*/
var GTM = exports.Integration = integration('Google Tag Manager')
.assumesPageview()
.readyOnLoad()
.global('dataLayer')
.global('google_tag_manager')
.option('containerId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
/**
* Initialize
*
* https://developers.google.com/tag-manager
*
* @param {Object} page
*/
GTM.prototype.initialize = function(){
this.load();
};
/**
* Loaded
*
* @return {Boolean}
*/
GTM.prototype.loaded = function(){
return !! (window.dataLayer && [].push != window.dataLayer.push);
};
/**
* Load.
*
* @param {Function} fn
*/
GTM.prototype.load = function(fn){
var id = this.options.containerId;
push({ 'gtm.start': +new Date, event: 'gtm.js' });
load('//www.googletagmanager.com/gtm.js?id=' + id + '&l=dataLayer', fn);
};
/**
* Page.
*
* @param {Page} page
* @api public
*/
GTM.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var track;
// all
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* https://developers.google.com/tag-manager/devguide#events
*
* @param {Track} track
* @api public
*/
GTM.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
push(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/gosquared.js", function(exports, require, module){
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
var each = require('each');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GoSquared);
user = analytics.user(); // store reference for later
};
/**
* Expose `GoSquared` integration.
*/
var GoSquared = exports.Integration = integration('GoSquared')
.assumesPageview()
.readyOnLoad()
.global('_gs')
.option('siteToken', '')
.option('anonymizeIP', false)
.option('cookieDomain', null)
.option('useCookies', true)
.option('trackHash', false)
.option('trackLocal', false)
.option('trackParams', true);
/**
* Initialize.
*
* https://www.gosquared.com/developer/tracker
* Options: https://www.gosquared.com/developer/tracker/configuration
*
* @param {Object} page
*/
GoSquared.prototype.initialize = function (page) {
var self = this;
var options = this.options;
push(options.siteToken);
each(options, function(name, value){
if ('siteToken' == name) return;
if (null == value) return;
push('set', name, value);
});
self.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
self.load();
};
/**
* Loaded? (checks if the tracker version is set)
*
* @return {Boolean}
*/
GoSquared.prototype.loaded = function () {
return !! (window._gs && window._gs.v);
};
/**
* Load the GoSquared library.
*
* @param {Function} callback
*/
GoSquared.prototype.load = function (callback) {
load('//d1l6p2sc9645hc.cloudfront.net/tracker.js', callback);
};
/**
* Page.
*
* https://www.gosquared.com/developer/tracker/pageviews
*
* @param {Page} page
*/
GoSquared.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
push('track', props.path, name || props.title)
};
/**
* Identify.
*
* https://www.gosquared.com/developer/tracker/tagging
*
* @param {Identify} identify
*/
GoSquared.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'userID' });
var username = identify.username();
var email = identify.email();
var id = identify.userId();
if (id) push('set', 'visitorID', id);
var name = email || username || id;
if (name) push('set', 'visitorName', name);
push('set', 'visitor', traits);
};
/**
* Track.
*
* https://www.gosquared.com/developer/tracker/events
*
* @param {Track} track
*/
GoSquared.prototype.track = function (track) {
push('event', track.event(), track.properties());
};
/**
* Checked out.
*
* @param {Track} track
* @api private
*/
GoSquared.prototype.completedOrder = function(track){
var products = track.products();
var items = [];
each(products, function(product){
var track = new Track({ properties: product });
items.push({
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
});
})
push('transaction', track.orderId(), {
revenue: track.total(),
track: true
}, items);
};
/**
* Push to `_gs.q`.
*
* @param {...} args
* @api private
*/
function push(){
var _gs = window._gs = window._gs || function(){
(_gs.q = _gs.q || []).push(arguments);
};
_gs.apply(null, arguments);
}
});
require.register("segmentio-analytics.js-integrations/lib/heap.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Heap);
};
/**
* Expose `Heap` integration.
*/
var Heap = exports.Integration = integration('Heap')
.assumesPageview()
.readyOnInitialize()
.global('heap')
.global('_heapid')
.option('apiKey', '');
/**
* Initialize.
*
* https://heapanalytics.com/docs#installWeb
*
* @param {Object} page
*/
Heap.prototype.initialize = function (page) {
window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);};
window.heap.load(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Heap.prototype.loaded = function () {
return (window.heap && window.heap.appid);
};
/**
* Load the Heap library.
*
* @param {Function} callback
*/
Heap.prototype.load = function (callback) {
load('//d36lvucg9kzous.cloudfront.net', callback);
};
/**
* Identify.
*
* https://heapanalytics.com/docs#identify
*
* @param {Identify} identify
*/
Heap.prototype.identify = function (identify) {
var traits = identify.traits();
var username = identify.username();
var id = identify.userId();
var handle = username || id;
if (handle) traits.handle = handle;
delete traits.username;
window.heap.identify(traits);
};
/**
* Track.
*
* https://heapanalytics.com/docs#track
*
* @param {Track} track
*/
Heap.prototype.track = function (track) {
window.heap.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/hellobar.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Hellobar);
};
/**
* Expose `hellobar.com` integration.
*/
var Hellobar = exports.Integration = integration('Hello Bar')
.assumesPageview()
.readyOnInitialize()
.global('_hbq')
.option('apiKey', '');
/**
* Initialize.
*
* https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js
*
* @param {Object} page
*/
Hellobar.prototype.initialize = function(page) {
window._hbq = window._hbq || [];
this.load();
};
/**
* Load.
*
* @param {Function} callback
*/
Hellobar.prototype.load = function (callback) {
var url = '//s3.amazonaws.com/scripts.hellobar.com/' + this.options.apiKey + '.js';
load(url, callback);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Hellobar.prototype.loaded = function () {
return !! (window._hbq && window._hbq.push !== Array.prototype.push);
};
});
require.register("segmentio-analytics.js-integrations/lib/hittail.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HitTail);
};
/**
* Expose `HitTail` integration.
*/
var HitTail = exports.Integration = integration('HitTail')
.assumesPageview()
.readyOnLoad()
.global('htk')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
HitTail.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HitTail.prototype.loaded = function () {
return is.fn(window.htk);
};
/**
* Load the HitTail library.
*
* @param {Function} callback
*/
HitTail.prototype.load = function (callback) {
var id = this.options.siteId;
load('//' + id + '.hittail.com/mlt.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/hubspot.js", function(exports, require, module){
var callback = require('callback');
var convert = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_hsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HubSpot);
};
/**
* Expose `HubSpot` integration.
*/
var HubSpot = exports.Integration = integration('HubSpot')
.assumesPageview()
.readyOnInitialize()
.global('_hsq')
.option('portalId', null);
/**
* Initialize.
*
* @param {Object} page
*/
HubSpot.prototype.initialize = function (page) {
window._hsq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HubSpot.prototype.loaded = function () {
return !! (window._hsq && window._hsq.push !== Array.prototype.push);
};
/**
* Load the HubSpot library.
*
* @param {Function} fn
*/
HubSpot.prototype.load = function (fn) {
if (document.getElementById('hs-analytics')) return callback.async(fn);
var id = this.options.portalId;
var cache = Math.ceil(new Date() / 300000) * 300000;
var url = 'https://js.hs-analytics.net/analytics/' + cache + '/' + id + '.js';
var script = load(url, fn);
script.id = 'hs-analytics';
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
HubSpot.prototype.page = function (page) {
push('_trackPageview');
};
/**
* Identify.
*
* @param {Identify} identify
*/
HubSpot.prototype.identify = function (identify) {
if (!identify.email()) return;
var traits = identify.traits();
traits = convertDates(traits);
push('identify', traits);
};
/**
* Track.
*
* @param {Track} track
*/
HubSpot.prototype.track = function (track) {
var props = track.properties();
props = convertDates(props);
push('trackEvent', track.event(), props);
};
/**
* Convert all the dates in the HubSpot properties to millisecond times
*
* @param {Object} properties
*/
function convertDates (properties) {
return convert(properties, function (date) { return date.getTime(); });
}
});
require.register("segmentio-analytics.js-integrations/lib/improvely.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Improvely);
};
/**
* Expose `Improvely` integration.
*/
var Improvely = exports.Integration = integration('Improvely')
.assumesPageview()
.readyOnInitialize()
.global('_improvely')
.global('improvely')
.option('domain', '')
.option('projectId', null);
/**
* Initialize.
*
* http://www.improvely.com/docs/landing-page-code
*
* @param {Object} page
*/
Improvely.prototype.initialize = function (page) {
window._improvely = [];
window.improvely = {init: function (e, t) { window._improvely.push(["init", e, t]); }, goal: function (e) { window._improvely.push(["goal", e]); }, label: function (e) { window._improvely.push(["label", e]); } };
var domain = this.options.domain;
var id = this.options.projectId;
window.improvely.init(domain, id);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Improvely.prototype.loaded = function () {
return !! (window.improvely && window.improvely.identify);
};
/**
* Load the Improvely library.
*
* @param {Function} callback
*/
Improvely.prototype.load = function (callback) {
var domain = this.options.domain;
load('//' + domain + '.iljmp.com/improvely.js', callback);
};
/**
* Identify.
*
* http://www.improvely.com/docs/labeling-visitors
*
* @param {Identify} identify
*/
Improvely.prototype.identify = function (identify) {
var id = identify.userId();
if (id) window.improvely.label(id);
};
/**
* Track.
*
* http://www.improvely.com/docs/conversion-code
*
* @param {Track} track
*/
Improvely.prototype.track = function (track) {
var props = track.properties({ revenue: 'amount' });
props.type = track.event();
window.improvely.goal(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/inspectlet.js", function(exports, require, module){
var integration = require('integration');
var alias = require('alias');
var clone = require('clone');
var load = require('load-script');
var push = require('global-queue')('__insp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Inspectlet);
};
/**
* Expose `Inspectlet` integration.
*/
var Inspectlet = exports.Integration = integration('Inspectlet')
.assumesPageview()
.readyOnLoad()
.global('__insp')
.global('__insp_')
.option('wid', '');
/**
* Initialize.
*
* https://www.inspectlet.com/dashboard/embedcode/1492461759/initial
*
* @param {Object} page
*/
Inspectlet.prototype.initialize = function (page) {
push('wid', this.options.wid);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Inspectlet.prototype.loaded = function () {
return !! window.__insp_;
};
/**
* Load the Inspectlet library.
*
* @param {Function} callback
*/
Inspectlet.prototype.load = function (callback) {
load('//www.inspectlet.com/inspectlet.js', callback);
};
/**
* Identify.
*
* http://www.inspectlet.com/docs#tagging
*
* @param {Identify} identify
*/
Inspectlet.prototype.identify = function (identify) {
var traits = identify.traits({ id: 'userid' });
push('tagSession', traits);
};
/**
* Track.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.track = function (track) {
push('tagSession', track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/intercom.js", function(exports, require, module){
var alias = require('alias');
var convertDates = require('convert-dates');
var integration = require('integration');
var each = require('each');
var is = require('is');
var isEmail = require('is-email');
var load = require('load-script');
var defaults = require('defaults');
var empty = require('is-empty');
var when = require('when');
/* Group reference. */
var group;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Intercom);
group = analytics.group();
};
/**
* Expose `Intercom` integration.
*/
var Intercom = exports.Integration = integration('Intercom')
.assumesPageview()
.readyOnLoad()
.global('Intercom')
.option('activator', '#IntercomDefaultWidget')
.option('appId', '')
.option('inbox', false);
/**
* Initialize.
*
* http://docs.intercom.io/
* http://docs.intercom.io/#IntercomJS
*
* @param {Object} page
*/
Intercom.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Intercom.prototype.loaded = function () {
return is.fn(window.Intercom);
};
/**
* Load the Intercom library.
*
* TODO: remove `when()` when integration `.loaded()`
* behavior is fixed.
*
* @param {Function} callback
*/
Intercom.prototype.load = function (callback) {
var self = this;
load('https://static.intercomcdn.com/intercom.v1.js', function(err){
if (err) return callback(err);
when(function(){
return self.loaded();
}, callback);
});
};
/**
* Page.
*
* @param {Page} page
*/
Intercom.prototype.page = function(page){
window.Intercom('update');
};
/**
* Identify.
*
* http://docs.intercom.io/#IntercomJS
*
* @param {Identify} identify
*/
Intercom.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'user_id' });
var activator = this.options.activator;
var opts = identify.options(this.name);
var companyCreated = identify.companyCreated();
var created = identify.created();
var email = identify.email();
var name = identify.name();
var id = identify.userId();
if (!id && !traits.email) return; // one is required
traits.app_id = this.options.appId;
// Make sure company traits are carried over (fixes #120).
if (!empty(group.traits())) {
traits.company = traits.company || {};
defaults(traits.company, group.traits());
}
// name
if (name) traits.name = name;
// handle dates
if (companyCreated) traits.company.created = companyCreated;
if (created) traits.created = created;
// convert dates
traits = convertDates(traits, formatDate);
traits = alias(traits, { created: 'created_at'});
// company
if (traits.company) {
traits.company = alias(traits.company, { created: 'created_at' });
}
// handle options
if (opts.increments) traits.increments = opts.increments;
if (opts.userHash) traits.user_hash = opts.userHash;
if (opts.user_hash) traits.user_hash = opts.user_hash;
// Intercom, will force the widget to appear
// if the selector is #IntercomDefaultWidget
// so no need to check inbox, just need to check
// that the selector isn't #IntercomDefaultWidget.
if ('#IntercomDefaultWidget' != activator) {
traits.widget = { activator: activator };
}
var method = this._id !== id ? 'boot': 'update';
this._id = id; // cache for next time
window.Intercom(method, traits);
};
/**
* Group.
*
* @param {Group} group
*/
Intercom.prototype.group = function (group) {
var props = group.properties();
var id = group.groupId();
if (id) props.id = id;
window.Intercom('update', { company: props });
};
/**
* Track.
*
* @param {Track} track
*/
Intercom.prototype.track = function(track){
window.Intercom('trackEvent', track.event(), track.properties());
};
/**
* Format a date to Intercom's liking.
*
* @param {Date} date
* @return {Number}
*/
function formatDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/keen-io.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Keen);
};
/**
* Expose `Keen IO` integration.
*/
var Keen = exports.Integration = integration('Keen IO')
.readyOnInitialize()
.global('Keen')
.option('projectId', '')
.option('readKey', '')
.option('writeKey', '')
.option('trackNamedPages', true)
.option('trackAllPages', false)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://keen.io/docs/
*/
Keen.prototype.initialize = function () {
var options = this.options;
window.Keen = window.Keen||{configure:function(e){this._cf=e;},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);},setGlobalProperties:function(e){this._gp=e;},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}};
window.Keen.configure({
projectId: options.projectId,
writeKey: options.writeKey,
readKey: options.readKey
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Keen.prototype.loaded = function () {
return !! (window.Keen && window.Keen.Base64);
};
/**
* Load the Keen IO library.
*
* @param {Function} callback
*/
Keen.prototype.load = function (callback) {
load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Keen.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* TODO: migrate from old `userId` to simpler `id`
*
* @param {Identify} identify
*/
Keen.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var user = {};
if (id) user.userId = id;
if (traits) user.traits = traits;
window.Keen.setGlobalProperties(function() {
return { user: user };
});
};
/**
* Track.
*
* @param {Track} track
*/
Keen.prototype.track = function (track) {
window.Keen.addEvent(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/kenshoo.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Kenshoo);
};
/**
* Expose `Kenshoo` integration.
*/
var Kenshoo = exports.Integration = integration('Kenshoo')
.readyOnLoad()
.global('k_trackevent')
.option('cid', '')
.option('subdomain', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* See https://gist.github.com/justinboyle/7875832
*
* @param {Object} page
*/
Kenshoo.prototype.initialize = function(page) {
this.load();
};
/**
* Loaded? (checks if the tracking function is set)
*
* @return {Boolean}
*/
Kenshoo.prototype.loaded = function() {
return is.fn(window.k_trackevent);
};
/**
* Load Kenshoo script.
*
* @param {Function} callback
*/
Kenshoo.prototype.load = function(callback) {
var url = '//' + this.options.subdomain + '.xg4ken.com/media/getpx.php?cid=' + this.options.cid;
load(url, callback);
};
/**
* Completed order.
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} track
* @api private
*/
Kenshoo.prototype.completedOrder = function(track) {
this._track(track, { val: track.total() });
};
/**
* Page.
*
* @param {Page} page
*/
Kenshoo.prototype.page = function(page) {
var category = page.category();
var name = page.name();
var fullName = page.fullName();
var isNamed = (name && this.options.trackNamedPages);
var isCategorized = (category && this.options.trackCategorizedPages);
var track;
if (name && ! this.options.trackNamedPages) {
return;
}
if (category && ! this.options.trackCategorizedPages) {
return;
}
if (isNamed && isCategorized) {
track = page.track(fullName);
} else if (isNamed) {
track = page.track(name);
} else if (isCategorized) {
track = page.track(category);
} else {
track = page.track();
}
this._track(track);
};
/**
* Track.
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} event
*/
Kenshoo.prototype.track = function(track) {
this._track(track);
};
/**
* Track a Kenshoo event.
*
* Private method for sending an event. We use it because `completedOrder`
* can't call track directly (would result in an infinite loop).
*
* @param {track} event
* @param {options} object
*/
Kenshoo.prototype._track = function(track, options) {
options = options || { val: track.revenue() };
var params = [
'id=' + this.options.cid,
'type=' + track.event(),
'val=' + (options.val || '0.0'),
'orderId=' + (track.orderId() || ''),
'promoCode=' + (track.coupon() || ''),
'valueCurrency=' + (track.currency() || ''),
// Live tracking fields. Ignored for now (until we get documentation).
'GCID=',
'kw=',
'product='
];
window.k_trackevent(params, this.options.subdomain);
};
});
require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js", function(exports, require, module){
var alias = require('alias');
var Batch = require('batch');
var callback = require('callback');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_kmq');
var Track = require('facade').Track;
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(KISSmetrics);
};
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = exports.Integration = integration('KISSmetrics')
.assumesPageview()
.readyOnInitialize()
.global('_kmq')
.global('KM')
.global('_kmil')
.option('apiKey', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('prefixProperties', true);
/**
* Check if browser is mobile, for kissmetrics.
*
* http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile
*/
exports.isMobile = navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/iPhone|iPod/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/Opera Mini/i)
|| navigator.userAgent.match(/IEMobile/i);
/**
* Initialize.
*
* http://support.kissmetrics.com/apis/javascript
*
* @param {Object} page
*/
KISSmetrics.prototype.initialize = function (page) {
window._kmq = [];
if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function () {
return is.object(window.KM);
};
/**
* Load.
*
* @param {Function} callback
*/
KISSmetrics.prototype.load = function (callback) {
var key = this.options.apiKey;
var useless = '//i.kissmetrics.com/i.js';
var library = '//doug1izaerwt3.cloudfront.net/' + key + '.1.js';
new Batch()
.push(function (done) { load(useless, done); }) // :)
.push(function (done) { load(library, done); })
.end(callback);
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
KISSmetrics.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function (track) {
var mapping = { revenue: 'Billing Amount' };
var event = track.event();
var properties = track.properties(mapping);
if (this.options.prefixProperties) properties = prefix(event, properties);
push('record', event, properties);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function (alias) {
push('alias', alias.to(), alias.from());
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track){
var products = track.products();
var event = track.event();
// transaction
push('record', event, prefix(event, track.properties()));
// items
window._kmq.push(function(){
var km = window.KM;
each(products, function(product, i){
var temp = new Track({ event: event, properties: product });
var item = prefix(event, product);
item._t = km.ts() + i;
item._d = 1;
km.set(item);
});
});
};
/**
* Prefix properties with the event name.
*
* @param {String} event
* @param {Object} properties
* @return {Object} prefixed
* @api private
*/
function prefix(event, properties){
var prefixed = {};
each(properties, function(key, val){
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
});
require.register("segmentio-analytics.js-integrations/lib/klaviyo.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_learnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Klaviyo);
};
/**
* Expose `Klaviyo` integration.
*/
var Klaviyo = exports.Integration = integration('Klaviyo')
.assumesPageview()
.readyOnInitialize()
.global('_learnq')
.option('apiKey', '');
/**
* Initialize.
*
* https://www.klaviyo.com/docs/getting-started
*
* @param {Object} page
*/
Klaviyo.prototype.initialize = function (page) {
push('account', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Klaviyo.prototype.loaded = function () {
return !! (window._learnq && window._learnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Klaviyo.prototype.load = function (callback) {
load('//a.klaviyo.com/media/js/learnmarklet.js', callback);
};
/**
* Trait aliases.
*/
var aliases = {
id: '$id',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
phone: '$phone_number',
title: '$title'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Klaviyo.prototype.identify = function (identify) {
var traits = identify.traits(aliases);
if (!traits.$id && !traits.$email) return;
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
Klaviyo.prototype.group = function (group) {
var props = group.properties();
if (!props.name) return;
push('identify', { $organization: props.name });
};
/**
* Track.
*
* @param {Track} track
*/
Klaviyo.prototype.track = function (track) {
push('track', track.event(), track.properties({
revenue: '$value'
}));
};
});
require.register("segmentio-analytics.js-integrations/lib/leadlander.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LeadLander);
};
/**
* Expose `LeadLander` integration.
*/
var LeadLander = exports.Integration = integration('LeadLander')
.assumesPageview()
.readyOnLoad()
.global('llactid')
.global('trackalyzer')
.option('accountId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LeadLander.prototype.initialize = function (page) {
window.llactid = this.options.accountId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LeadLander.prototype.loaded = function () {
return !! window.trackalyzer;
};
/**
* Load.
*
* @param {Function} callback
*/
LeadLander.prototype.load = function (callback) {
load('http://t6.trackalyzer.com/trackalyze-nodoc.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/livechat.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var clone = require('clone');
var when = require('when');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LiveChat);
};
/**
* Expose `LiveChat` integration.
*/
var LiveChat = exports.Integration = integration('LiveChat')
.assumesPageview()
.readyOnLoad()
.global('__lc')
.global('__lc_inited')
.global('LC_API')
.global('LC_Invite')
.option('group', 0)
.option('license', '');
/**
* Initialize.
*
* http://www.livechatinc.com/api/javascript-api
*
* @param {Object} page
*/
LiveChat.prototype.initialize = function (page) {
window.__lc = clone(this.options);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LiveChat.prototype.loaded = function () {
return !!(window.LC_API && window.LC_Invite);
};
/**
* Load.
*
* @param {Function} callback
*/
LiveChat.prototype.load = function (callback) {
var self = this;
load('//cdn.livechatinc.com/tracking.js', function(err){
if (err) return callback(err);
when(function(){
return self.loaded();
}, callback);
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
LiveChat.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'User ID' });
window.LC_API.set_custom_variables(convert(traits));
};
/**
* Convert a traits object into the format LiveChat requires.
*
* @param {Object} traits
* @return {Array}
*/
function convert (traits) {
var arr = [];
each(traits, function (key, value) {
arr.push({ name: key, value: value });
});
return arr;
}
});
require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js", function(exports, require, module){
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User ref
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LuckyOrange);
user = analytics.user();
};
/**
* Expose `LuckyOrange` integration.
*/
var LuckyOrange = exports.Integration = integration('Lucky Orange')
.assumesPageview()
.readyOnLoad()
.global('_loq')
.global('__wtw_watcher_added')
.global('__wtw_lucky_site_id')
.global('__wtw_lucky_is_segment_io')
.global('__wtw_custom_user_data')
.option('siteId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LuckyOrange.prototype.initialize = function (page) {
window._loq || (window._loq = []);
window.__wtw_lucky_site_id = this.options.siteId;
this.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LuckyOrange.prototype.loaded = function () {
return !! window.__wtw_watcher_added;
};
/**
* Load.
*
* @param {Function} callback
*/
LuckyOrange.prototype.load = function (callback) {
var cache = Math.floor(new Date().getTime() / 60000);
load({
http: 'http://www.luckyorange.com/w.js?' + cache,
https: 'https://ssl.luckyorange.com/w.js?' + cache
}, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
LuckyOrange.prototype.identify = function (identify) {
var traits = window.__wtw_custom_user_data = identify.traits();
var email = identify.email();
var name = identify.name();
if (name) traits.name = name;
if (email) traits.email = email;
};
});
require.register("segmentio-analytics.js-integrations/lib/lytics.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Lytics);
};
/**
* Expose `Lytics` integration.
*/
var Lytics = exports.Integration = integration('Lytics')
.readyOnInitialize()
.global('jstag')
.option('cid', '')
.option('cookie', 'seerid')
.option('delay', 2000)
.option('sessionTimeout', 1800)
.option('url', '//c.lytics.io');
/**
* Options aliases.
*/
var aliases = {
sessionTimeout: 'sessecs'
};
/**
* Initialize.
*
* http://admin.lytics.io/doc#jstag
*
* @param {Object} page
*/
Lytics.prototype.initialize = function (page) {
var options = alias(this.options, aliases);
window.jstag = (function () {var t = {_q: [], _c: options, ts: (new Date()).getTime() }; t.send = function() {this._q.push([ 'ready', 'send', Array.prototype.slice.call(arguments) ]); return this; }; return t; })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Lytics.prototype.loaded = function () {
return !! (window.jstag && window.jstag.bind);
};
/**
* Load the Lytics library.
*
* @param {Function} callback
*/
Lytics.prototype.load = function (callback) {
load('//c.lytics.io/static/io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Lytics.prototype.page = function (page) {
window.jstag.send(page.properties());
};
/**
* Idenfity.
*
* @param {Identify} identify
*/
Lytics.prototype.identify = function (identify) {
var traits = identify.traits({ userId: '_uid' });
window.jstag.send(traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Lytics.prototype.track = function (track) {
var props = track.properties();
props._e = track.event();
window.jstag.send(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/mixpanel.js", function(exports, require, module){
var alias = require('alias');
var clone = require('clone');
var dates = require('convert-dates');
var integration = require('integration');
var iso = require('to-iso-string');
var load = require('load-script');
var indexof = require('indexof');
var del = require('obj-case').del;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mixpanel);
};
/**
* Expose `Mixpanel` integration.
*/
var Mixpanel = exports.Integration = integration('Mixpanel')
.readyOnLoad()
.global('mixpanel')
.option('increments', [])
.option('cookieName', '')
.option('nameTag', true)
.option('pageview', false)
.option('people', false)
.option('token', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
cookieName: 'cookie_name'
};
/**
* Initialize.
*
* https://mixpanel.com/help/reference/javascript#installing
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init
*/
Mixpanel.prototype.initialize = function () {
(function (c, a) {window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function (b, c, f) {function d(a, b) {var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function () {a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []);
this.options.increments = lowercase(this.options.increments);
var options = alias(this.options, optionsAliases);
window.mixpanel.init(options.token, options);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mixpanel.prototype.loaded = function () {
return !! (window.mixpanel && window.mixpanel.config);
};
/**
* Load.
*
* @param {Function} callback
*/
Mixpanel.prototype.load = function (callback) {
load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', callback);
};
/**
* Page.
*
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Mixpanel.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Trait aliases.
*/
var traitAliases = {
created: '$created',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
lastSeen: '$last_seen',
name: '$name',
username: '$username',
phone: '$phone'
};
/**
* Identify.
*
* https://mixpanel.com/help/reference/javascript#super-properties
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript#storing-user-profiles
*
* @param {Identify} identify
*/
Mixpanel.prototype.identify = function (identify) {
var username = identify.username();
var email = identify.email();
var id = identify.userId();
// id
if (id) window.mixpanel.identify(id);
// name tag
var nametag = email || username || id;
if (nametag) window.mixpanel.name_tag(nametag);
// traits
var traits = identify.traits(traitAliases);
if (traits.$created) del(traits, 'createdAt');
window.mixpanel.register(traits);
if (this.options.people) window.mixpanel.people.set(traits);
};
/**
* Track.
*
* https://mixpanel.com/help/reference/javascript#sending-events
* https://mixpanel.com/help/reference/javascript#tracking-revenue
*
* @param {Track} track
*/
Mixpanel.prototype.track = function (track) {
var increments = this.options.increments;
var increment = track.event().toLowerCase();
var people = this.options.people;
var props = track.properties();
var revenue = track.revenue();
if (people && ~indexof(increments, increment)) {
window.mixpanel.people.increment(track.event());
window.mixpanel.people.set('Last ' + track.event(), new Date);
}
props = dates(props, iso);
window.mixpanel.track(track.event(), props);
if (revenue && people) {
window.mixpanel.people.track_charge(revenue);
}
};
/**
* Alias.
*
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias
*
* @param {Alias} alias
*/
Mixpanel.prototype.alias = function (alias) {
var mp = window.mixpanel;
var to = alias.to();
if (mp.get_distinct_id && mp.get_distinct_id() === to) return;
// HACK: internal mixpanel API to ensure we don't overwrite
if (mp.get_property && mp.get_property('$people_distinct_id') === to) return;
// although undocumented, mixpanel takes an optional original id
mp.alias(to, alias.from());
};
/**
* Lowercase the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function lowercase(arr){
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
}
});
require.register("segmentio-analytics.js-integrations/lib/mojn.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mojn);
};
/**
* Expose `Mojn`
*/
var Mojn = exports.Integration = integration('Mojn')
.option('customerCode', '')
.global('_mojnTrack')
.readyOnInitialize();
/**
* Initialize.
*
* @param {Object} page
*/
Mojn.prototype.initialize = function(){
window._mojnTrack = window._mojnTrack || [];
window._mojnTrack.push({ cid: this.options.customerCode });
this.load();
};
/**
* Load the Mojn script.
*
* @param {Function} fn
*/
Mojn.prototype.load = function(fn) {
load('https://track.idtargeting.com/' + this.options.customerCode + '/track.js', fn);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mojn.prototype.loaded = function () {
return is.object(window._mojnTrack);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Mojn.prototype.identify = function(identify) {
var email = identify.email();
if (!email) return;
var img = new Image();
img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email;
img.width = 1;
img.height = 1;
return img;
};
/**
* Track.
*
* @param {Track} event
*/
Mojn.prototype.track = function(track) {
var properties = track.properties();
var revenue = properties.revenue;
var currency = properties.currency || '';
var conv = currency + revenue;
if (!revenue) return;
window._mojnTrack.push({ conv: conv });
return conv;
};
});
require.register("segmentio-analytics.js-integrations/lib/mouseflow.js", function(exports, require, module){
var push = require('global-queue')('_mfq');
var integration = require('integration');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Mouseflow);
};
/**
* Expose `Mouseflow`
*/
var Mouseflow = exports.Integration = integration('Mouseflow')
.assumesPageview()
.readyOnLoad()
.global('mouseflow')
.global('_mfq')
.option('apiKey', '')
.option('mouseflowHtmlDelay', 0);
/**
* Iniitalize
*
* @param {Object} page
*/
Mouseflow.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mouseflow.prototype.loaded = function(){
return !! (window._mfq && [].push != window._mfq.push);
};
/**
* Load mouseflow.
*
* @param {Function} fn
*/
Mouseflow.prototype.load = function(fn){
var apiKey = this.options.apiKey;
window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay;
load('//cdn.mouseflow.com/projects/' + apiKey + '.js', fn);
};
/**
* Page.
*
* //mouseflow.zendesk.com/entries/22528817-Single-page-websites
*
* @param {Page} page
*/
Mouseflow.prototype.page = function(page){
if (!window.mouseflow) return;
if ('function' != typeof mouseflow.newPageView) return;
mouseflow.newPageView();
};
/**
* Identify.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Identify} identify
*/
Mouseflow.prototype.identify = function(identify){
set(identify.traits());
};
/**
* Track.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Track} track
*/
Mouseflow.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
set(props);
};
/**
* Push the given `hash`.
*
* @param {Object} hash
*/
function set(hash){
each(hash, function(k, v){
push('setVariable', k, v);
});
}
});
require.register("segmentio-analytics.js-integrations/lib/mousestats.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(MouseStats);
};
/**
* Expose `MouseStats` integration.
*/
var MouseStats = exports.Integration = integration('MouseStats')
.assumesPageview()
.readyOnLoad()
.global('msaa')
.global('MouseStatsVisitorPlaybacks')
.option('accountNumber', '');
/**
* Initialize.
*
* http://www.mousestats.com/docs/pages/allpages
*
* @param {Object} page
*/
MouseStats.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
MouseStats.prototype.loaded = function () {
return is.array(window.MouseStatsVisitorPlaybacks);
};
/**
* Load.
*
* @param {Function} callback
*/
MouseStats.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number;
var cache = Math.floor(new Date().getTime() / 60000);
var partial = '.mousestats.com/js/' + path + '.js?' + cache;
var http = 'http://www2' + partial;
var https = 'https://ssl' + partial;
load({ http: http, https: https }, callback);
};
/**
* Identify.
*
* http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks
*
* @param {Identify} identify
*/
MouseStats.prototype.identify = function (identify) {
each(identify.traits(), function (key, value) {
window.MouseStatsVisitorPlaybacks.customVariable(key, value);
});
};
});
require.register("segmentio-analytics.js-integrations/lib/navilytics.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('__nls');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Navilytics);
};
/**
* Expose `Navilytics` integration.
*/
var Navilytics = exports.Integration = integration('Navilytics')
.assumesPageview()
.readyOnLoad()
.global('__nls')
.option('memberId', '')
.option('projectId', '');
/**
* Initialize.
*
* https://www.navilytics.com/member/code_settings
*
* @param {Object} page
*/
Navilytics.prototype.initialize = function(page){
window.__nls = window.__nls || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Navilytics.prototype.loaded = function(){
return !! (window.__nls && [].push != window.__nls.push);
};
/**
* Load the Navilytics library.
*
* @param {Function} callback
*/
Navilytics.prototype.load = function(callback){
var mid = this.options.memberId;
var pid = this.options.projectId;
var url = '//www.navilytics.com/nls.js?mid=' + mid + '&pid=' + pid;
load(url, callback);
};
/**
* Track.
*
* https://www.navilytics.com/docs#tags
*
* @param {Track} track
*/
Navilytics.prototype.track = function(track){
push('tagRecording', track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/olark.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var https = require('use-https');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Olark);
};
/**
* Expose `Olark` integration.
*/
var Olark = exports.Integration = integration('Olark')
.assumesPageview()
.readyOnInitialize()
.global('olark')
.option('identify', true)
.option('page', true)
.option('siteId', '')
.option('track', false);
/**
* Initialize.
*
* http://www.olark.com/documentation
*
* @param {Object} page
*/
Olark.prototype.initialize = function (page) {
window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
window.olark.identify(this.options.siteId);
// keep track of the widget's open state
var self = this;
box('onExpand', function () { self._open = true; });
box('onShrink', function () { self._open = false; });
};
/**
* Page.
*
* @param {Page} page
*/
Olark.prototype.page = function (page) {
if (!this.options.page || !this._open) return;
var props = page.properties();
var name = page.fullName();
if (!name && !props.url) return;
var msg = name ? name.toLowerCase() + ' page' : props.url;
chat('sendNotificationToOperator', {
body: 'looking at ' + msg // lowercase since olark does
});
};
/**
* Identify.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
*/
Olark.prototype.identify = function (identify) {
if (!this.options.identify) return;
var username = identify.username();
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
var phone = identify.phone();
var name = identify.name()
|| identify.firstName();
visitor('updateCustomFields', traits);
if (email) visitor('updateEmailAddress', { emailAddress: email });
if (phone) visitor('updatePhoneNumber', { phoneNumber: phone });
// figure out best name
if (name) visitor('updateFullName', { fullName: name });
// figure out best nickname
var nickname = name || email || username || id;
if (name && email) nickname += ' (' + email + ')';
if (nickname) chat('updateVisitorNickname', { snippet: nickname });
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Olark.prototype.track = function (track) {
if (!this.options.track || !this._open) return;
chat('sendNotificationToOperator', {
body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does
});
};
/**
* Helper method for Olark box API calls.
*
* @param {String} action
* @param {Object} value
*/
function box (action, value) {
window.olark('api.box.' + action, value);
}
/**
* Helper method for Olark visitor API calls.
*
* @param {String} action
* @param {Object} value
*/
function visitor (action, value) {
window.olark('api.visitor.' + action, value);
}
/**
* Helper method for Olark chat API calls.
*
* @param {String} action
* @param {Object} value
*/
function chat (action, value) {
window.olark('api.chat.' + action, value);
}
});
require.register("segmentio-analytics.js-integrations/lib/optimizely.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var push = require('global-queue')('optimizely');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(Optimizely);
analytics = ajs; // store for later
};
/**
* Expose `Optimizely` integration.
*/
var Optimizely = exports.Integration = integration('Optimizely')
.readyOnInitialize()
.option('variations', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://www.optimizely.com/docs/api#function-calls
*/
Optimizely.prototype.initialize = function () {
if (this.options.variations) tick(this.replay);
};
/**
* Track.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Track} track
*/
Optimizely.prototype.track = function (track) {
var props = track.properties();
if (props.revenue) props.revenue *= 100;
push('trackEvent', track.event(), props);
};
/**
* Page.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Page} page
*/
Optimizely.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Replay experiment data as traits to other enabled providers.
*
* https://www.optimizely.com/docs/api#data-object
*/
Optimizely.prototype.replay = function () {
if (!window.optimizely) return; // in case the snippet isnt on the page
var data = window.optimizely.data;
if (!data) return;
var experiments = data.experiments;
var map = data.state.variationNamesMap;
var traits = {};
each(map, function (experimentId, variation) {
var experiment = experiments[experimentId].name;
traits['Experiment: ' + experiment] = variation;
});
analytics.identify(traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(PerfectAudience);
};
/**
* Expose `PerfectAudience` integration.
*/
var PerfectAudience = exports.Integration = integration('Perfect Audience')
.assumesPageview()
.readyOnLoad()
.global('_pa')
.option('siteId', '');
/**
* Initialize.
*
* https://www.perfectaudience.com/docs#javascript_api_autoopen
*
* @param {Object} page
*/
PerfectAudience.prototype.initialize = function (page) {
window._pa = window._pa || {};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
PerfectAudience.prototype.loaded = function () {
return !! (window._pa && window._pa.track);
};
/**
* Load.
*
* @param {Function} callback
*/
PerfectAudience.prototype.load = function (callback) {
var id = this.options.siteId;
load('//tag.perfectaudience.com/serve/' + id + '.js', callback);
};
/**
* Track.
*
* @param {Track} event
*/
PerfectAudience.prototype.track = function (track) {
window._pa.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/pingdom.js", function(exports, require, module){
var date = require('load-date');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_prum');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Pingdom);
};
/**
* Expose `Pingdom` integration.
*/
var Pingdom = exports.Integration = integration('Pingdom')
.assumesPageview()
.readyOnLoad()
.global('_prum')
.option('id', '');
/**
* Initialize.
*
* @param {Object} page
*/
Pingdom.prototype.initialize = function (page) {
window._prum = window._prum || [];
push('id', this.options.id);
push('mark', 'firstbyte', date.getTime());
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Pingdom.prototype.loaded = function () {
return !! (window._prum && window._prum.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Pingdom.prototype.load = function (callback) {
load('//rum-static.pingdom.net/prum.min.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/piwik.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_paq');
var each = require('each');
/**
* Expose plugin
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Piwik);
};
/**
* Expose `Piwik` integration.
*/
var Piwik = exports.Integration = integration('Piwik')
.global('_paq')
.option('url', null)
.option('siteId', '')
.readyOnInitialize()
.mapping('goals');
/**
* Initialize.
*
* http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
*/
Piwik.prototype.initialize = function () {
window._paq = window._paq || [];
push('setSiteId', this.options.siteId);
push('setTrackerUrl', this.options.url + '/piwik.php');
push('enableLinkTracking');
this.load();
};
/**
* Load the Piwik Analytics library.
*/
Piwik.prototype.load = function (callback) {
load(this.options.url + "/piwik.js", callback);
};
/**
* Check if Piwik is loaded
*/
Piwik.prototype.loaded = function () {
return !! (window._paq && window._paq.push != [].push);
};
/**
* Page
*
* @param {Page} page
*/
Piwik.prototype.page = function (page) {
push('trackPageView');
};
/**
* Track.
*
* @param {Track} track
*/
Piwik.prototype.track = function(track){
var goals = this.goals(track.event());
var revenue = track.revenue() || 0;
each(goals, function(goal){
push('trackGoal', goal, revenue);
});
};
});
require.register("segmentio-analytics.js-integrations/lib/preact.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_lnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Preact);
};
/**
* Expose `Preact` integration.
*/
var Preact = exports.Integration = integration('Preact')
.assumesPageview()
.readyOnInitialize()
.global('_lnq')
.option('projectCode', '');
/**
* Initialize.
*
* http://www.preact.io/api/javascript
*
* @param {Object} page
*/
Preact.prototype.initialize = function (page) {
window._lnq = window._lnq || [];
push('_setCode', this.options.projectCode);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Preact.prototype.loaded = function () {
return !! (window._lnq && window._lnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Preact.prototype.load = function (callback) {
load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Preact.prototype.identify = function (identify) {
if (!identify.userId()) return;
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
push('_setPersonData', {
name: identify.name(),
email: identify.email(),
uid: identify.userId(),
properties: traits
});
};
/**
* Group.
*
* @param {String} id
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Preact.prototype.group = function (group) {
if (!group.groupId()) return;
push('_setAccount', group.traits());
};
/**
* Track.
*
* @param {Track} track
*/
Preact.prototype.track = function (track) {
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var special = { name: event };
if (revenue) {
special.revenue = revenue * 100;
delete props.revenue;
}
if (props.note) {
special.note = props.note;
delete props.note;
}
push('_logEvent', special, props);
};
/**
* Convert a `date` to a format Preact supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/qualaroo.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_kiq');
var Facade = require('facade');
var Identify = Facade.Identify;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Qualaroo);
};
/**
* Expose `Qualaroo` integration.
*/
var Qualaroo = exports.Integration = integration('Qualaroo')
.assumesPageview()
.readyOnInitialize()
.global('_kiq')
.option('customerId', '')
.option('siteToken', '')
.option('track', false);
/**
* Initialize.
*
* @param {Object} page
*/
Qualaroo.prototype.initialize = function (page) {
window._kiq = window._kiq || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Qualaroo.prototype.loaded = function () {
return !! (window._kiq && window._kiq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Qualaroo.prototype.load = function (callback) {
var token = this.options.siteToken;
var id = this.options.customerId;
load('//s3.amazonaws.com/ki.js/' + id + '/' + token + '.js', callback);
};
/**
* Identify.
*
* http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
* http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
*
* @param {Identify} identify
*/
Qualaroo.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
if (email) id = email;
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Qualaroo.prototype.track = function (track) {
if (!this.options.track) return;
var event = track.event();
var traits = {};
traits['Triggered: ' + event] = true;
this.identify(new Identify({ traits: traits }));
};
});
require.register("segmentio-analytics.js-integrations/lib/quantcast.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_qevents', { wrap: false });
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Quantcast);
user = analytics.user(); // store for later
};
/**
* Expose `Quantcast` integration.
*/
var Quantcast = exports.Integration = integration('Quantcast')
.assumesPageview()
.readyOnInitialize()
.global('_qevents')
.global('__qc')
.option('pCode', null)
.option('advertise', false);
/**
* Initialize.
*
* https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {Page} page
*/
Quantcast.prototype.initialize = function (page) {
window._qevents = window._qevents || [];
var opts = this.options;
var settings = { qacct: opts.pCode };
if (user.id()) settings.uid = user.id();
if (page) {
settings.labels = this.labels('page', page.category(), page.name());
}
push(settings);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Quantcast.prototype.loaded = function () {
return !! window.__qc;
};
/**
* Load.
*
* @param {Function} callback
*/
Quantcast.prototype.load = function (callback) {
load({
http: 'http://edge.quantserve.com/quant.js',
https: 'https://secure.quantserve.com/quant.js'
}, callback);
};
/**
* Page.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Page} page
*/
Quantcast.prototype.page = function (page) {
var category = page.category();
var name = page.name();
var settings = {
event: 'refresh',
labels: this.labels('page', category, name),
qacct: this.options.pCode,
};
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Identify.
*
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {String} id (optional)
*/
Quantcast.prototype.identify = function (identify) {
// edit the initial quantcast settings
var id = identify.userId();
if (id) window._qevents[0].uid = id;
};
/**
* Track.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Track} track
*/
Quantcast.prototype.track = function (track) {
var name = track.event();
var revenue = track.revenue();
var settings = {
event: 'click',
labels: this.labels('event', name),
qacct: this.options.pCode
};
if (null != revenue) settings.revenue = (revenue+''); // convert to string
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
Quantcast.prototype.completedOrder = function(track){
var name = track.event();
var revenue = track.total();
var labels = this.labels('event', name);
var category = track.category();
if (this.options.advertise && category) {
labels += ',' + this.labels('pcat', category);
}
var settings = {
event: 'refresh', // the example Quantcast sent has completed order send refresh not click
labels: labels,
revenue: (revenue+''), // convert to string
orderid: track.orderId(),
qacct: this.options.pCode
};
push(settings);
};
/**
* Generate quantcast labels.
*
* Example:
*
* options.advertise = false;
* labels('event', 'my event');
* // => "event.my event"
*
* options.advertise = true;
* labels('event', 'my event');
* // => "_fp.event.my event"
*
* @param {String} type
* @param {String} ...
* @return {String}
* @api private
*/
Quantcast.prototype.labels = function(type){
var args = [].slice.call(arguments, 1);
var advertise = this.options.advertise;
var ret = [];
if (advertise && 'page' == type) type = 'event';
if (advertise) type = '_fp.' + type;
for (var i = 0; i < args.length; ++i) {
if (null == args[i]) continue;
var value = String(args[i]);
ret.push(value.replace(/,/g, ';'));
}
ret = advertise ? ret.join(' ') : ret.join('.');
return [type, ret].join('.');
};
});
require.register("segmentio-analytics.js-integrations/lib/rollbar.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var is = require('is');
var extend = require('extend');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics) {
analytics.addIntegration(RollbarIntegration);
};
/**
* Expose `Rollbar` integration.
*/
var RollbarIntegration = exports.Integration = integration('Rollbar')
.readyOnInitialize()
.global('Rollbar')
.option('identify', true)
.option('accessToken', '')
.option('environment', 'unknown')
.option('captureUncaught', true);
/**
* Initialize.
*
* @param {Object} page
*/
RollbarIntegration.prototype.initialize = function(page) {
var _rollbarConfig = this.config = {
accessToken: this.options.accessToken,
captureUncaught: this.options.captureUncaught,
payload: {
environment: this.options.environment
}
};
!function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)}(window,document);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
RollbarIntegration.prototype.loaded = function() {
return is.object(window.Rollbar) && null == window.Rollbar.shimId;
};
/**
* Load.
*
* @param {Function} callback
*/
RollbarIntegration.prototype.load = function(callback) {
window.Rollbar.loadFull(window, document, true, this.config, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
RollbarIntegration.prototype.identify = function(identify) {
// do stuff with `id` or `traits`
if (!this.options.identify) return;
// Don't allow identify without a user id
var uid = identify.userId();
if (uid === null || uid === undefined) return;
var rollbar = window.Rollbar;
var person = {id: uid};
extend(person, identify.traits());
rollbar.configure({payload: {person: person}});
};
});
require.register("segmentio-analytics.js-integrations/lib/saasquatch.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(SaaSquatch);
};
/**
* Expose `SaaSquatch` integration.
*/
var SaaSquatch = exports.Integration = integration('SaaSquatch')
.readyOnInitialize()
.option('tenantAlias', '')
.global('_sqh');
/**
* Initialize
*
* @param {Page} page
*/
SaaSquatch.prototype.initialize = function(page){};
/**
* Loaded?
*
* @return {Boolean}
*/
SaaSquatch.prototype.loaded = function(){
return window._sqh && window._sqh.push != [].push;
};
/**
* Load the SaaSquatch library.
*
* @param {Function} fn
*/
SaaSquatch.prototype.load = function(fn){
load('//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js', fn);
};
/**
* Identify.
*
* @param {Facade} identify
*/
SaaSquatch.prototype.identify = function(identify){
var sqh = window._sqh = window._sqh || [];
var accountId = identify.proxy('traits.accountId');
var image = identify.proxy('traits.referralImage');
var opts = identify.options(this.name);
var id = identify.userId();
var email = identify.email();
if (!(id || email)) return;
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
first_name: identify.firstName(),
last_name: identify.lastName(),
user_image: identify.avatar(),
email: email,
user_id: id,
};
if (accountId) init.account_id = accountId;
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
});
require.register("segmentio-analytics.js-integrations/lib/sentry.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Sentry);
};
/**
* Expose `Sentry` integration.
*/
var Sentry = exports.Integration = integration('Sentry')
.readyOnLoad()
.global('Raven')
.option('config', '');
/**
* Initialize.
*
* http://raven-js.readthedocs.org/en/latest/config/index.html
*/
Sentry.prototype.initialize = function () {
var config = this.options.config;
this.load(function () {
// for now, raven basically requires `install` to be called
// https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113
window.Raven.config(config).install();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Sentry.prototype.loaded = function () {
return is.object(window.Raven);
};
/**
* Load.
*
* @param {Function} callback
*/
Sentry.prototype.load = function (callback) {
load('//cdn.ravenjs.com/1.1.10/native/raven.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Sentry.prototype.identify = function (identify) {
window.Raven.setUser(identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/snapengage.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(SnapEngage);
};
/**
* Expose `SnapEngage` integration.
*/
var SnapEngage = exports.Integration = integration('SnapEngage')
.assumesPageview()
.readyOnLoad()
.global('SnapABug')
.option('apiKey', '');
/**
* Initialize.
*
* http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
*
* @param {Object} page
*/
SnapEngage.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
SnapEngage.prototype.loaded = function () {
return is.object(window.SnapABug);
};
/**
* Load.
*
* @param {Function} callback
*/
SnapEngage.prototype.load = function (callback) {
var key = this.options.apiKey;
var url = '//commondatastorage.googleapis.com/code.snapengage.com/js/' + key + '.js';
load(url, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
SnapEngage.prototype.identify = function (identify) {
var email = identify.email();
if (!email) return;
window.SnapABug.setUserEmail(email);
};
});
require.register("segmentio-analytics.js-integrations/lib/spinnakr.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Spinnakr);
};
/**
* Expose `Spinnakr` integration.
*/
var Spinnakr = exports.Integration = integration('Spinnakr')
.assumesPageview()
.readyOnLoad()
.global('_spinnakr_site_id')
.global('_spinnakr')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Spinnakr.prototype.initialize = function (page) {
window._spinnakr_site_id = this.options.siteId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Spinnakr.prototype.loaded = function () {
return !! window._spinnakr;
};
/**
* Load.
*
* @param {Function} callback
*/
Spinnakr.prototype.load = function (callback) {
load('//d3ojzyhbolvoi5.cloudfront.net/js/so.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/tapstream.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var slug = require('slug');
var push = require('global-queue')('_tsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Tapstream);
};
/**
* Expose `Tapstream` integration.
*/
var Tapstream = exports.Integration = integration('Tapstream')
.assumesPageview()
.readyOnInitialize()
.global('_tsq')
.option('accountName', '')
.option('trackAllPages', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* @param {Object} page
*/
Tapstream.prototype.initialize = function (page) {
window._tsq = window._tsq || [];
push('setAccountName', this.options.accountName);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Tapstream.prototype.loaded = function () {
return !! (window._tsq && window._tsq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Tapstream.prototype.load = function (callback) {
load('//cdn.tapstream.com/static/js/tapstream.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Tapstream.prototype.page = function (page) {
var category = page.category();
var opts = this.options;
var name = page.fullName();
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Track.
*
* @param {Track} track
*/
Tapstream.prototype.track = function (track) {
var props = track.properties();
push('fireHit', slug(track.event()), [props.url]); // needs events as slugs
};
});
require.register("segmentio-analytics.js-integrations/lib/trakio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Trakio);
};
/**
* Expose `Trakio` integration.
*/
var Trakio = exports.Integration = integration('trak.io')
.assumesPageview()
.readyOnInitialize()
.global('trak')
.option('token', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
initialPageview: 'auto_track_page_view'
};
/**
* Initialize.
*
* https://docs.trak.io
*
* @param {Object} page
*/
Trakio.prototype.initialize = function (page) {
var self = this;
var options = this.options;
window.trak = window.trak || [];
window.trak.io = window.trak.io || {};
window.trak.io.load = function(e) {self.load(); var r = function(e) {return function() {window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); };
window.trak.io.load(options.token, alias(options, optionsAliases));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Trakio.prototype.loaded = function () {
return !! (window.trak && window.trak.loaded);
};
/**
* Load the trak.io library.
*
* @param {Function} callback
*/
Trakio.prototype.load = function (callback) {
load('//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Trakio.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
window.trak.io.page_view(props.path, name || props.title);
// named pages
if (name && this.options.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && this.options.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Trait aliases.
*
* http://docs.trak.io/properties.html#special
*/
var traitAliases = {
avatar: 'avatar_url',
firstName: 'first_name',
lastName: 'last_name'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Trakio.prototype.identify = function (identify) {
var traits = identify.traits(traitAliases);
var id = identify.userId();
if (id) {
window.trak.io.identify(id, traits);
} else {
window.trak.io.identify(traits);
}
};
/**
* Group.
*
* @param {String} id (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*
* TODO: add group
* TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special
*/
/**
* Track.
*
* @param {Track} track
*/
Trakio.prototype.track = function (track) {
window.trak.io.track(track.event(), track.properties());
};
/**
* Alias.
*
* @param {Alias} alias
*/
Trakio.prototype.alias = function (alias) {
if (!window.trak.io.distinct_id) return;
var from = alias.from();
var to = alias.to();
if (to === window.trak.io.distinct_id()) return;
if (from) {
window.trak.io.alias(from, to);
} else {
window.trak.io.alias(to);
}
};
});
require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js", function(exports, require, module){
var pixel = require('load-pixel')('//analytics.twitter.com/i/adsct');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(TwitterAds);
};
/**
* Expose `load`
*/
exports.load = pixel;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `TwitterAds`
*/
var TwitterAds = exports.Integration = integration('Twitter Ads')
.readyOnInitialize()
.option('events', {});
/**
* Track.
*
* @param {Track} track
*/
TwitterAds.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
txn_id: events[event],
p_id: 'Twitter'
});
};
});
require.register("segmentio-analytics.js-integrations/lib/usercycle.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_uc');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Usercycle);
};
/**
* Expose `Usercycle` integration.
*/
var Usercycle = exports.Integration = integration('USERcycle')
.assumesPageview()
.readyOnInitialize()
.global('_uc')
.option('key', '');
/**
* Initialize.
*
* http://docs.usercycle.com/javascript_api
*
* @param {Object} page
*/
Usercycle.prototype.initialize = function (page) {
push('_key', this.options.key);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Usercycle.prototype.loaded = function () {
return !! (window._uc && window._uc.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Usercycle.prototype.load = function (callback) {
load('//api.usercycle.com/javascripts/track.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Usercycle.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('uid', id);
// there's a special `came_back` event used for retention and traits
push('action', 'came_back', traits);
};
/**
* Track.
*
* @param {Track} track
*/
Usercycle.prototype.track = function (track) {
push('action', track.event(), track.properties({
revenue: 'revenue_amount'
}));
};
});
require.register("segmentio-analytics.js-integrations/lib/userfox.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_ufq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Userfox);
};
/**
* Expose `Userfox` integration.
*/
var Userfox = exports.Integration = integration('userfox')
.assumesPageview()
.readyOnInitialize()
.global('_ufq')
.option('clientId', '');
/**
* Initialize.
*
* https://www.userfox.com/docs/
*
* @param {Object} page
*/
Userfox.prototype.initialize = function (page) {
window._ufq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Userfox.prototype.loaded = function () {
return !! (window._ufq && window._ufq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Userfox.prototype.load = function (callback) {
load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback);
};
/**
* Identify.
*
* https://www.userfox.com/docs/#custom-data
*
* @param {Identify} identify
*/
Userfox.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'signup_date' });
var email = identify.email();
if (!email) return;
// initialize the library with the email now that we have it
push('init', {
clientId: this.options.clientId,
email: email
});
traits = convertDates(traits, formatDate);
push('track', traits);
};
/**
* Convert a `date` to a format userfox supports.
*
* @param {Date} date
* @return {String}
*/
function formatDate (date) {
return Math.round(date.getTime() / 1000).toString();
}
});
require.register("segmentio-analytics.js-integrations/lib/uservoice.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('UserVoice');
var unix = require('to-unix-timestamp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(UserVoice);
};
/**
* Expose `UserVoice` integration.
*/
var UserVoice = exports.Integration = integration('UserVoice')
.assumesPageview()
.readyOnInitialize()
.global('UserVoice')
.global('showClassicWidget')
.option('apiKey', '')
.option('classic', false)
.option('forumId', null)
.option('showWidget', true)
.option('mode', 'contact')
.option('accentColor', '#448dd6')
.option('smartvote', true)
.option('trigger', null)
.option('triggerPosition', 'bottom-right')
.option('triggerColor', '#ffffff')
.option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)')
// BACKWARDS COMPATIBILITY: classic options
.option('classicMode', 'full')
.option('primaryColor', '#cc6d00')
.option('linkColor', '#007dbf')
.option('defaultMode', 'support')
.option('tabLabel', 'Feedback & Support')
.option('tabColor', '#cc6d00')
.option('tabPosition', 'middle-right')
.option('tabInverted', false);
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
UserVoice.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.group = undefined;
integration.identify = integration.identifyClassic;
integration.initialize = integration.initializeClassic;
});
/**
* Initialize.
*
* @param {Object} page
*/
UserVoice.prototype.initialize = function (page) {
var options = this.options;
var opts = formatOptions(options);
push('set', opts);
push('autoprompt', {});
if (options.showWidget) {
options.trigger
? push('addTrigger', options.trigger, opts)
: push('addTrigger', opts);
}
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
UserVoice.prototype.loaded = function () {
return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
UserVoice.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widget.uservoice.com/' + key + '.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
UserVoice.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
UserVoice.prototype.group = function (group) {
var traits = group.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', { account: traits });
};
/**
* Initialize (classic).
*
* @param {Object} options
* @param {Function} ready
*/
UserVoice.prototype.initializeClassic = function () {
var options = this.options;
window.showClassicWidget = showClassicWidget; // part of public api
if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options));
this.load();
};
/**
* Identify (classic).
*
* @param {Identify} identify
*/
UserVoice.prototype.identifyClassic = function (identify) {
push('setCustomFields', identify.traits());
};
/**
* Format the options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatOptions (options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position'
});
}
/**
* Format the classic options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatClassicOptions (options) {
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
}
/**
* Show the classic version of the UserVoice widget. This method is usually part
* of UserVoice classic's public API.
*
* @param {String} type ('showTab' or 'showLightbox')
* @param {Object} options (optional)
*/
function showClassicWidget (type, options) {
type = type || 'showLightbox';
push(type, 'classic_widget', options);
}
});
require.register("segmentio-analytics.js-integrations/lib/vero.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_veroq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Vero);
};
/**
* Expose `Vero` integration.
*/
var Vero = exports.Integration = integration('Vero')
.readyOnInitialize()
.global('_veroq')
.option('apiKey', '');
/**
* Initialize.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md
*
* @param {Object} page
*/
Vero.prototype.initialize = function (pgae) {
push('init', { api_key: this.options.apiKey });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Vero.prototype.loaded = function () {
return !! (window._veroq && window._veroq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Vero.prototype.load = function (callback) {
load('//d3qxef4rp70elm.cloudfront.net/m.js', callback);
};
/**
* Page.
*
* https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews
*
* @param {Page} page
*/
Vero.prototype.page = function(page){
push('trackPageview');
};
/**
* Identify.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification
*
* @param {Identify} identify
*/
Vero.prototype.identify = function (identify) {
var traits = identify.traits();
var email = identify.email();
var id = identify.userId();
if (!id || !email) return; // both required
push('user', traits);
};
/**
* Track.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events
*
* @param {Track} track
*/
Vero.prototype.track = function (track) {
push('track', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", function(exports, require, module){
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(VWO);
analytics = ajs;
};
/**
* Expose `VWO` integration.
*/
var VWO = exports.Integration = integration('Visual Website Optimizer')
.readyOnInitialize()
.option('replay', true);
/**
* Initialize.
*
* http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
*/
VWO.prototype.initialize = function () {
if (this.options.replay) this.replay();
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function () {
tick(function () {
experiments(function (err, traits) {
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} callback
* @return {Object}
*/
function experiments (callback) {
enqueue(function () {
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return callback();
each(ids, function (id) {
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
callback(null, data);
});
}
/**
* Add a `fn` to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn
*/
function enqueue (fn) {
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id
* @return {String}
*/
function variation (id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
});
require.register("segmentio-analytics.js-integrations/lib/webengage.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(WebEngage);
};
/**
* Expose `WebEngage` integration
*/
var WebEngage = exports.Integration = integration('WebEngage')
.assumesPageview()
.readyOnLoad()
.global('_weq')
.global('webengage')
.option('widgetVersion', '4.0')
.option('licenseCode', '');
/**
* Initialize.
*
* @param {Object} page
*/
WebEngage.prototype.initialize = function(page){
var _weq = window._weq = window._weq || {};
_weq['webengage.licenseCode'] = this.options.licenseCode;
_weq['webengage.widgetVersion'] = this.options.widgetVersion;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
WebEngage.prototype.loaded = function(){
return !! window.webengage;
};
/**
* Load
*
* @param {Function} fn
*/
WebEngage.prototype.load = function(fn){
var path = '/js/widget/webengage-min-v-4.0.js';
load({
https: 'https://ssl.widgets.webengage.com' + path,
http: 'http://cdn.widgets.webengage.com' + path
}, fn);
};
});
require.register("segmentio-analytics.js-integrations/lib/woopra.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var snake = require('to-snake-case');
var load = require('load-script');
var isEmail = require('is-email');
var extend = require('extend');
var each = require('each');
var type = require('type');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Woopra);
};
/**
* Expose `Woopra` integration.
*/
var Woopra = exports.Integration = integration('Woopra')
.readyOnLoad()
.global('woopra')
.option('domain', '')
.option('cookieName', 'wooTracker')
.option('cookieDomain', null)
.option('cookiePath', '/')
.option('ping', true)
.option('pingInterval', 12000)
.option('idleTimeout', 300000)
.option('downloadTracking', true)
.option('outgoingTracking', true)
.option('outgoingIgnoreSubdomain', true)
.option('downloadPause', 200)
.option('outgoingPause', 400)
.option('ignoreQueryUrl', true)
.option('hideCampaign', false);
/**
* Initialize.
*
* http://www.woopra.com/docs/setup/javascript-tracking/
*
* @param {Object} page
*/
Woopra.prototype.initialize = function (page) {
(function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra');
this.load();
each(this.options, function(key, value){
key = snake(key);
if (null == value) return;
if ('' == value) return;
window.woopra.config(key, value);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Woopra.prototype.loaded = function () {
return !! (window.woopra && window.woopra.loaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Woopra.prototype.load = function (callback) {
load('//static.woopra.com/js/w.js', callback);
};
/**
* Page.
*
* @param {String} category (optional)
*/
Woopra.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
if (name) props.title = name;
window.woopra.track('pv', props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Woopra.prototype.identify = function (identify) {
window.woopra.identify(identify.traits()).push(); // `push` sends it off async
};
/**
* Track.
*
* @param {Track} track
*/
Woopra.prototype.track = function (track) {
window.woopra.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Yandex);
};
/**
* Expose `Yandex` integration.
*/
var Yandex = exports.Integration = integration('Yandex Metrica')
.assumesPageview()
.readyOnInitialize()
.global('yandex_metrika_callbacks')
.global('Ya')
.option('counterId', null);
/**
* Initialize.
*
* http://api.yandex.com/metrika/
* https://metrica.yandex.com/22522351?step=2#tab=code
*
* @param {Object} page
*/
Yandex.prototype.initialize = function (page) {
var id = this.options.counterId;
push(function () {
window['yaCounter' + id] = new window.Ya.Metrika({ id: id });
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Yandex.prototype.loaded = function () {
return !! (window.Ya && window.Ya.Metrika);
};
/**
* Load.
*
* @param {Function} callback
*/
Yandex.prototype.load = function (callback) {
load('//mc.yandex.ru/metrika/watch.js', callback);
};
/**
* Push a new callback on the global Yandex queue.
*
* @param {Function} callback
*/
function push (callback) {
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
}
});
require.register("segmentio-canonical/index.js", function(exports, require, module){
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
});
require.register("segmentio-extend/index.js", function(exports, require, module){
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
});
require.register("camshaft-require-component/index.js", function(exports, require, module){
/**
* Require a module with a fallback
*/
module.exports = function(parent) {
function require(name, fallback) {
try {
return parent(name);
}
catch (e) {
try {
return parent(fallback || name+"-component");
}
catch(e2) {
throw e;
}
}
};
// Merge the old properties
for (var key in parent) {
require[key] = parent[key];
}
return require;
};
});
require.register("segmentio-facade/lib/index.js", function(exports, require, module){
var Facade = require('./facade');
/**
* Expose `Facade` facade.
*/
module.exports = Facade;
/**
* Expose specific-method facades.
*/
Facade.Alias = require('./alias');
Facade.Group = require('./group');
Facade.Identify = require('./identify');
Facade.Track = require('./track');
Facade.Page = require('./page');
Facade.Screen = require('./screen');
});
require.register("segmentio-facade/lib/alias.js", function(exports, require, module){
/**
* Module dependencies.
*/
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
/**
* Expose `Alias` facade.
*/
module.exports = Alias;
/**
* Initialize a new `Alias` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @property {String} from
* @property {String} to
* @property {Object} options
*/
function Alias (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Alias, Facade);
/**
* Return type of facade.
*
* @return {String}
*/
Alias.prototype.type =
Alias.prototype.action = function () {
return 'alias';
};
/**
* Get `previousId`.
*
* @return {Mixed}
* @api public
*/
Alias.prototype.from =
Alias.prototype.previousId = function(){
return this.field('previousId')
|| this.field('from');
};
/**
* Get `userId`.
*
* @return {String}
* @api public
*/
Alias.prototype.to =
Alias.prototype.userId = function(){
return this.field('userId')
|| this.field('to');
};
});
require.register("segmentio-facade/lib/facade.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var isEnabled = component('./is-enabled');
var objCase = component('obj-case');
var traverse = component('isodate-traverse');
/**
* Expose `Facade`.
*/
module.exports = Facade;
/**
* Initialize a new `Facade` with an `obj` of arguments.
*
* @param {Object} obj
*/
function Facade (obj) {
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = new Date(obj.timestamp);
this.obj = obj;
}
/**
* Return a proxy function for a `field` that will attempt to first use methods,
* and fallback to accessing the underlying object directly. You can specify
* deeply nested fields too like:
*
* this.proxy('options.Librato');
*
* @param {String} field
*/
Facade.prototype.proxy = function (field) {
var fields = field.split('.');
field = fields.shift();
// Call a function at the beginning to take advantage of facaded fields
var obj = this[field] || this.field(field);
if (!obj) return obj;
if (typeof obj === 'function') obj = obj.call(this) || {};
if (fields.length === 0) return transform(obj);
obj = objCase(obj, fields.join('.'));
return transform(obj);
};
/**
* Directly access a specific `field` from the underlying object, returning a
* clone so outsiders don't mess with stuff.
*
* @param {String} field
* @return {Mixed}
*/
Facade.prototype.field = function (field) {
var obj = this.obj[field];
return transform(obj);
};
/**
* Utility method to always proxy a particular `field`. You can specify deeply
* nested fields too like:
*
* Facade.proxy('options.Librato');
*
* @param {String} field
* @return {Function}
*/
Facade.proxy = function (field) {
return function () {
return this.proxy(field);
};
};
/**
* Utility method to directly access a `field`.
*
* @param {String} field
* @return {Function}
*/
Facade.field = function (field) {
return function () {
return this.field(field);
};
};
/**
* Get the basic json object of this facade.
*
* @return {Object}
*/
Facade.prototype.json = function () {
return clone(this.obj);
};
/**
* Get the options of a call (formerly called "context"). If you pass an
* integration name, it will get the options for that specific integration, or
* undefined if the integration is not enabled.
*
* @param {String} integration (optional)
* @return {Object or Null}
*/
Facade.prototype.context =
Facade.prototype.options = function (integration) {
var options = clone(this.obj.options || this.obj.context) || {};
if (!integration) return clone(options);
if (!this.enabled(integration)) return;
var integrations = this.integrations();
var value = integrations[integration] || objCase(integrations, integration);
if ('boolean' == typeof value) value = {};
return value || {};
};
/**
* Check whether an integration is enabled.
*
* @param {String} integration
* @return {Boolean}
*/
Facade.prototype.enabled = function (integration) {
var allEnabled = this.proxy('options.providers.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all');
if (typeof allEnabled !== 'boolean') allEnabled = true;
var enabled = allEnabled && isEnabled(integration);
var options = this.integrations();
// If the integration is explicitly enabled or disabled, use that
// First, check options.providers for backwards compatibility
if (options.providers && options.providers.hasOwnProperty(integration)) {
enabled = options.providers[integration];
}
// Next, check for the integration's existence in 'options' to enable it.
// If the settings are a boolean, use that, otherwise it should be enabled.
if (options.hasOwnProperty(integration)) {
var settings = options[integration];
if (typeof settings === 'boolean') {
enabled = settings;
} else {
enabled = true;
}
}
return enabled ? true : false;
};
/**
* Get all `integration` options.
*
* @param {String} integration
* @return {Object}
* @api private
*/
Facade.prototype.integrations = function(){
return this.obj.integrations
|| this.proxy('options.providers')
|| this.options();
};
/**
* Check whether the user is active.
*
* @return {Boolean}
*/
Facade.prototype.active = function () {
var active = this.proxy('options.active');
if (active === null || active === undefined) active = true;
return active;
};
/**
* Get `sessionId / anonymousId`.
*
* @return {Mixed}
* @api public
*/
Facade.prototype.sessionId =
Facade.prototype.anonymousId = function(){
return this.field('anonymousId')
|| this.field('sessionId');
};
/**
* Add a convenient way to get the library name and version
*/
Facade.prototype.library = function(){
var library = this.proxy('options.library');
if (!library) return { name: 'unknown', version: null };
if (typeof library === 'string') return { name: library, version: null };
return library;
};
/**
* Setup some basic proxies.
*/
Facade.prototype.userId = Facade.field('userId');
Facade.prototype.channel = Facade.field('channel');
Facade.prototype.timestamp = Facade.field('timestamp');
Facade.prototype.userAgent = Facade.proxy('options.userAgent');
Facade.prototype.ip = Facade.proxy('options.ip');
/**
* Return the cloned and traversed object
*
* @param {Mixed} obj
* @return {Mixed}
*/
function transform(obj){
var cloned = clone(obj);
traverse(cloned);
return cloned;
}
});
require.register("segmentio-facade/lib/group.js", function(exports, require, module){
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
var newDate = component('new-date');
/**
* Expose `Group` facade.
*/
module.exports = Group;
/**
* Initialize a new `Group` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} groupId
* @param {Object} properties
* @param {Object} options
*/
function Group (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Group, Facade);
/**
* Get the facade's action.
*/
Group.prototype.type =
Group.prototype.action = function () {
return 'group';
};
/**
* Setup some basic proxies.
*/
Group.prototype.groupId = Facade.field('groupId');
/**
* Get created or createdAt.
*
* @return {Date}
*/
Group.prototype.created = function(){
var created = this.proxy('traits.createdAt')
|| this.proxy('traits.created')
|| this.proxy('properties.createdAt')
|| this.proxy('properties.created');
if (created) return newDate(created);
};
/**
* Get the group's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Group.prototype.traits = function (aliases) {
var ret = this.properties();
var id = this.groupId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get traits or properties.
*
* TODO: remove me
*
* @return {Object}
*/
Group.prototype.properties = function(){
return this.field('traits')
|| this.field('properties')
|| {};
};
});
require.register("segmentio-facade/lib/page.js", function(exports, require, module){
var component = require('require-component')(require);
var Facade = component('./facade');
var inherit = component('inherit');
var Track = require('./track');
/**
* Expose `Page` facade
*/
module.exports = Page;
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Page(dictionary){
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {String}
*/
Page.prototype.type =
Page.prototype.action = function(){
return 'page';
};
/**
* Proxies
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Get the page properties mixing `category` and `name`.
*
* @return {Object}
*/
Page.prototype.properties = function(){
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
if (category) props.category = category;
if (name) props.name = name;
return props;
};
/**
* Get the page fullName.
*
* @return {String}
*/
Page.prototype.fullName = function(){
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {String}
*/
Page.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {String} name
* @return {Track}
*/
Page.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
});
require.register("segmentio-facade/lib/identify.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var inherit = component('inherit');
var isEmail = component('is-email');
var newDate = component('new-date');
var trim = component('trim');
/**
* Expose `Idenfity` facade.
*/
module.exports = Identify;
/**
* Initialize a new `Identify` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} sessionId
* @param {Object} traits
* @param {Object} options
*/
function Identify (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Identify, Facade);
/**
* Get the facade's action.
*/
Identify.prototype.type =
Identify.prototype.action = function () {
return 'identify';
};
/**
* Get the user's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Identify.prototype.traits = function (aliases) {
var ret = this.field('traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {String}
*/
Identify.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the user's created date, optionally looking for `createdAt` since lots of
* people do that instead.
*
* @return {Date or Undefined}
*/
Identify.prototype.created = function () {
var created = this.proxy('traits.created') || this.proxy('traits.createdAt');
if (created) return newDate(created);
};
/**
* Get the company created date.
*
* @return {Date or undefined}
*/
Identify.prototype.companyCreated = function(){
var created = this.proxy('traits.company.created')
|| this.proxy('traits.company.createdAt');
if (created) return newDate(created);
};
/**
* Get the user's name, optionally combining a first and last name if that's all
* that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.name = function () {
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name);
var firstName = this.firstName();
var lastName = this.lastName();
if (firstName && lastName) return trim(firstName + ' ' + lastName);
};
/**
* Get the user's first name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.firstName = function () {
var firstName = this.proxy('traits.firstName');
if (typeof firstName === 'string') return trim(firstName);
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name).split(' ')[0];
};
/**
* Get the user's last name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.lastName = function () {
var lastName = this.proxy('traits.lastName');
if (typeof lastName === 'string') return trim(lastName);
var name = this.proxy('traits.name');
if (typeof name !== 'string') return;
var space = trim(name).indexOf(' ');
if (space === -1) return;
return trim(name.substr(space + 1));
};
/**
* Get the user's unique id.
*
* @return {String or undefined}
*/
Identify.prototype.uid = function(){
return this.userId()
|| this.username()
|| this.email();
};
/**
* Get description.
*
* @return {String}
*/
Identify.prototype.description = function(){
return this.proxy('traits.description')
|| this.proxy('traits.background');
};
/**
* Setup sme basic "special" trait proxies.
*/
Identify.prototype.username = Facade.proxy('traits.username');
Identify.prototype.website = Facade.proxy('traits.website');
Identify.prototype.phone = Facade.proxy('traits.phone');
Identify.prototype.address = Facade.proxy('traits.address');
Identify.prototype.avatar = Facade.proxy('traits.avatar');
});
require.register("segmentio-facade/lib/is-enabled.js", function(exports, require, module){
/**
* A few integrations are disabled by default. They must be explicitly
* enabled by setting options[Provider] = true.
*/
var disabled = {
Salesforce: true,
Marketo: true
};
/**
* Check whether an integration should be enabled by default.
*
* @param {String} integration
* @return {Boolean}
*/
module.exports = function (integration) {
return ! disabled[integration];
};
});
require.register("segmentio-facade/lib/track.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var Identify = component('./identify');
var inherit = component('inherit');
var isEmail = component('is-email');
/**
* Expose `Track` facade.
*/
module.exports = Track;
/**
* Initialize a new `Track` facade with a `dictionary` of arguments.
*
* @param {object} dictionary
* @property {String} event
* @property {String} userId
* @property {String} sessionId
* @property {Object} properties
* @property {Object} options
*/
function Track (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Track, Facade);
/**
* Return the facade's action.
*
* @return {String}
*/
Track.prototype.type =
Track.prototype.action = function () {
return 'track';
};
/**
* Setup some basic proxies.
*/
Track.prototype.event = Facade.field('event');
Track.prototype.value = Facade.proxy('properties.value');
/**
* Misc
*/
Track.prototype.category = Facade.proxy('properties.category');
Track.prototype.country = Facade.proxy('properties.country');
Track.prototype.state = Facade.proxy('properties.state');
Track.prototype.city = Facade.proxy('properties.city');
Track.prototype.zip = Facade.proxy('properties.zip');
/**
* Ecommerce
*/
Track.prototype.id = Facade.proxy('properties.id');
Track.prototype.sku = Facade.proxy('properties.sku');
Track.prototype.tax = Facade.proxy('properties.tax');
Track.prototype.name = Facade.proxy('properties.name');
Track.prototype.price = Facade.proxy('properties.price');
Track.prototype.total = Facade.proxy('properties.total');
Track.prototype.coupon = Facade.proxy('properties.coupon');
Track.prototype.shipping = Facade.proxy('properties.shipping');
/**
* Order id.
*
* @return {String}
* @api public
*/
Track.prototype.orderId = function(){
return this.proxy('properties.id')
|| this.proxy('properties.orderId');
};
/**
* Get subtotal.
*
* @return {Number}
*/
Track.prototype.subtotal = function(){
var subtotal = this.obj.properties.subtotal;
var total = this.total();
var n;
if (subtotal) return subtotal;
if (!total) return 0;
if (n = this.tax()) total -= n;
if (n = this.shipping()) total -= n;
return total;
};
/**
* Get products.
*
* @return {Array}
*/
Track.prototype.products = function(){
var props = this.obj.properties || {};
return props.products || [];
};
/**
* Get quantity.
*
* @return {Number}
*/
Track.prototype.quantity = function(){
var props = this.obj.properties || {};
return props.quantity || 1;
};
/**
* Get currency.
*
* @return {String}
*/
Track.prototype.currency = function(){
var props = this.obj.properties || {};
return props.currency || 'USD';
};
/**
* BACKWARDS COMPATIBILITY: should probably re-examine where these come from.
*/
Track.prototype.referrer = Facade.proxy('properties.referrer');
Track.prototype.query = Facade.proxy('options.query');
/**
* Get the call's properties.
*
* @param {Object} aliases
* @return {Object}
*/
Track.prototype.properties = function (aliases) {
var ret = this.field('properties') || {};
aliases = aliases || {};
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('properties.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the call's "super properties" which are just traits that have been
* passed in as if from an identify call.
*
* @return {Object}
*/
Track.prototype.traits = function () {
return this.proxy('options.traits') || {};
};
/**
* Get the call's username.
*
* @return {String or Undefined}
*/
Track.prototype.username = function () {
return this.proxy('traits.username') ||
this.proxy('properties.username') ||
this.userId() ||
this.sessionId();
};
/**
* Get the call's email, using an the user ID if it's a valid email.
*
* @return {String or Undefined}
*/
Track.prototype.email = function () {
var email = this.proxy('traits.email');
email = email || this.proxy('properties.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the call's revenue, parsing it from a string with an optional leading
* dollar sign.
*
* For products/services that don't have shipping and are not directly taxed,
* they only care about tracking `revenue`. These are things like
* SaaS companies, who sell monthly subscriptions. The subscriptions aren't
* taxed directly, and since it's a digital product, it has no shipping.
*
* The only case where there's a difference between `revenue` and `total`
* (in the context of analytics) is on ecommerce platforms, where they want
* the `revenue` function to actually return the `total` (which includes
* tax and shipping, total = subtotal + tax + shipping). This is probably
* because on their backend they assume tax and shipping has been applied to
* the value, and so can get the revenue on their own.
*
* @return {Number}
*/
Track.prototype.revenue = function () {
var revenue = this.proxy('properties.revenue');
var event = this.event();
// it's always revenue, unless it's called during an order completion.
if (!revenue && event && event.match(/completed ?order/i)) {
revenue = this.proxy('properties.total');
}
return currency(revenue);
};
/**
* Get cents.
*
* @return {Number}
*/
Track.prototype.cents = function(){
var revenue = this.revenue();
return 'number' != typeof revenue
? this.value() || 0
: revenue * 100;
};
/**
* A utility to turn the pieces of a track call into an identify. Used for
* integrations with super properties or rate limits.
*
* TODO: remove me.
*
* @return {Facade}
*/
Track.prototype.identify = function () {
var json = this.json();
json.traits = this.traits();
return new Identify(json);
};
/**
* Get float from currency value.
*
* @param {Mixed} val
* @return {Number}
*/
function currency(val) {
if (!val) return;
if (typeof val === 'number') return val;
if (typeof val !== 'string') return;
val = val.replace(/\$/g, '');
val = parseFloat(val);
if (!isNaN(val)) return val;
}
});
require.register("segmentio-facade/lib/screen.js", function(exports, require, module){
var component = require('require-component')(require);
var inherit = component('inherit');
var Page = component('./page');
var Track = require('./track');
/**
* Expose `Screen` facade
*/
module.exports = Screen;
/**
* Initialize new `Screen` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Screen(dictionary){
Page.call(this, dictionary);
}
/**
* Inherit from `Page`
*/
inherit(Screen, Page);
/**
* Get the facade's action.
*
* @return {String}
* @api public
*/
Screen.prototype.type =
Screen.prototype.action = function(){
return 'screen';
};
/**
* Get event with `name`.
*
* @param {String} name
* @return {String}
* @api public
*/
Screen.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Screen'
: 'Loaded a Screen';
};
/**
* Convert this Screen.
*
* @param {String} name
* @return {Track}
* @api public
*/
Screen.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
});
require.register("segmentio-is-email/index.js", function(exports, require, module){
/**
* Expose `isEmail`.
*/
module.exports = isEmail;
/**
* Email address matcher.
*/
var matcher = /.+\@.+\..+/;
/**
* Loosely validate an email address.
*
* @param {String} string
* @return {Boolean}
*/
function isEmail (string) {
return matcher.test(string);
}
});
require.register("segmentio-is-meta/index.js", function(exports, require, module){
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
});
require.register("segmentio-isodate/index.js", function(exports, require, module){
/**
* Matcher, slightly modified from:
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*/
var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
/**
* Convert an ISO date string to a date. Fallback to native `Date.parse`.
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*
* @param {String} iso
* @return {Date}
*/
exports.parse = function (iso) {
var numericKeys = [1, 5, 6, 7, 8, 11, 12];
var arr = matcher.exec(iso);
var offset = 0;
// fallback to native parsing
if (!arr) return new Date(iso);
// remove undefined values
for (var i = 0, val; val = numericKeys[i]; i++) {
arr[val] = parseInt(arr[val], 10) || 0;
}
// allow undefined days and months
arr[2] = parseInt(arr[2], 10) || 1;
arr[3] = parseInt(arr[3], 10) || 1;
// month is 0-11
arr[2]--;
// allow abitrary sub-second precision
if (arr[8]) arr[8] = (arr[8] + '00').substring(0, 3);
// apply timezone if one exists
if (arr[4] == ' ') {
offset = new Date().getTimezoneOffset();
} else if (arr[9] !== 'Z' && arr[10]) {
offset = arr[11] * 60 + arr[12];
if ('+' == arr[10]) offset = 0 - offset;
}
var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);
return new Date(millis);
};
/**
* Checks whether a `string` is an ISO date string. `strict` mode requires that
* the date string at least have a year, month and date.
*
* @param {String} string
* @param {Boolean} strict
* @return {Boolean}
*/
exports.is = function (string, strict) {
if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false;
return matcher.test(string);
};
});
require.register("segmentio-isodate-traverse/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var each;
try {
each = require('each');
} catch (err) {
each = require('each-component');
}
/**
* Expose `traverse`.
*/
module.exports = traverse;
/**
* Traverse an object or array, and return a clone with all ISO strings parsed
* into Date objects.
*
* @param {Object} obj
* @return {Object}
*/
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) {
return object(input, strict);
} else if (is.array(input)) {
return array(input, strict);
}
}
/**
* Object traverser.
*
* @param {Object} obj
* @param {Boolean} strict
* @return {Object}
*/
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
/**
* Array traverser.
*
* @param {Array} arr
* @param {Boolean} strict
* @return {Array}
*/
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
});
require.register("component-json-fallback/index.js", function(exports, require, module){
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
(function () {
'use strict';
var JSON = module.exports = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
});
require.register("segmentio-json/index.js", function(exports, require, module){
var json = window.JSON || {};
var stringify = json.stringify;
var parse = json.parse;
module.exports = parse && stringify
? JSON
: require('json-fallback');
});
require.register("segmentio-new-date/lib/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var milliseconds = require('./milliseconds');
var seconds = require('./seconds');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native Date constructor.
*
* @param {Date|String|Number} val
*/
module.exports = function newDate (val) {
if (is.date(val)) return val;
if (is.number(val)) return new Date(toMs(val));
// date strings
if (isodate.is(val)) return isodate.parse(val);
if (milliseconds.is(val)) return milliseconds.parse(val);
if (seconds.is(val)) return seconds.parse(val);
// fallback to Date.parse
return new Date(val);
};
/**
* If the number passed val is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param {Number} num
*/
function toMs (num) {
if (num < 31557600000) return num * 1000;
return num;
}
});
require.register("segmentio-new-date/lib/milliseconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{13}/;
/**
* Check whether a string is a millisecond date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a millisecond string to a date.
*
* @param {String} millis
* @return {Date}
*/
exports.parse = function (millis) {
millis = parseInt(millis, 10);
return new Date(millis);
};
});
require.register("segmentio-new-date/lib/seconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{10}/;
/**
* Check whether a string is a second date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a second string to a date.
*
* @param {String} seconds
* @return {Date}
*/
exports.parse = function (seconds) {
var millis = parseInt(seconds, 10) * 1000;
return new Date(millis);
};
});
require.register("segmentio-store.js/store.js", function(exports, require, module){
;(function(win){
var store = {},
doc = win.document,
localStorageName = 'localStorage',
namespace = '__storejs__',
storage
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return JSON.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
if (typeof module != 'undefined' && module.exports) { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { win.store = store }
})(this.window || global);
});
require.register("segmentio-top-domain/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var parse = require('url').parse;
/**
* Expose `domain`
*/
module.exports = domain;
/**
* RegExp
*/
var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;
/**
* Get the top domain.
*
* Official Grammar: http://tools.ietf.org/html/rfc883#page-56
* Look for tlds with up to 2-6 characters.
*
* Example:
*
* domain('http://localhost:3000/baz');
* // => ''
* domain('http://dev:3000/baz');
* // => ''
* domain('http://127.0.0.1:3000/baz');
* // => ''
* domain('http://segment.io/baz');
* // => 'segment.io'
*
* @param {String} url
* @return {String}
* @api public
*/
function domain(url){
var host = parse(url).hostname;
var match = host.match(regexp);
return match ? match[0] : '';
};
});
require.register("visionmedia-debug/index.js", function(exports, require, module){
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
});
require.register("visionmedia-debug/debug.js", function(exports, require, module){
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
});
require.register("yields-prevent/index.js", function(exports, require, module){
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
});
require.register("analytics/lib/index.js", function(exports, require, module){
/**
* Analytics.js
*
* (C) 2013 Segment.io Inc.
*/
var Integrations = require('integrations');
var Analytics = require('./analytics');
var each = require('each');
/**
* Expose the `analytics` singleton.
*/
var analytics = module.exports = exports = new Analytics();
/**
* Expose require
*/
analytics.require = require;
/**
* Expose `VERSION`.
*/
exports.VERSION = '1.5.7';
/**
* Add integrations.
*/
each(Integrations, function (name, Integration) {
analytics.use(Integration);
});
});
require.register("analytics/lib/analytics.js", function(exports, require, module){
var after = require('after');
var bind = require('bind');
var callback = require('callback');
var canonical = require('canonical');
var clone = require('clone');
var cookie = require('./cookie');
var debug = require('debug');
var defaults = require('defaults');
var each = require('each');
var Emitter = require('emitter');
var group = require('./group');
var is = require('is');
var isEmail = require('is-email');
var isMeta = require('is-meta');
var newDate = require('new-date');
var on = require('event').bind;
var prevent = require('prevent');
var querystring = require('querystring');
var size = require('object').length;
var store = require('./store');
var url = require('url');
var user = require('./user');
var Facade = require('facade');
var Identify = Facade.Identify;
var Group = Facade.Group;
var Alias = Facade.Alias;
var Track = Facade.Track;
var Page = Facade.Page;
/**
* Expose `Analytics`.
*/
module.exports = Analytics;
/**
* Initialize a new `Analytics` instance.
*/
function Analytics () {
this.Integrations = {};
this._integrations = {};
this._readied = false;
this._timeout = 300;
this._user = user; // BACKWARDS COMPATIBILITY
bind.all(this);
var self = this;
this.on('initialize', function (settings, options) {
if (options.initialPageview) self.page();
});
this.on('initialize', function () {
self._parseQuery();
});
}
/**
* Event Emitter.
*/
Emitter(Analytics.prototype);
/**
* Use a `plugin`.
*
* @param {Function} plugin
* @return {Analytics}
*/
Analytics.prototype.use = function (plugin) {
plugin(this);
return this;
};
/**
* Define a new `Integration`.
*
* @param {Function} Integration
* @return {Analytics}
*/
Analytics.prototype.addIntegration = function (Integration) {
var name = Integration.prototype.name;
if (!name) throw new TypeError('attempted to add an invalid integration');
this.Integrations[name] = Integration;
return this;
};
/**
* Initialize with the given integration `settings` and `options`. Aliased to
* `init` for convenience.
*
* @param {Object} settings
* @param {Object} options (optional)
* @return {Analytics}
*/
Analytics.prototype.init =
Analytics.prototype.initialize = function (settings, options) {
settings = settings || {};
options = options || {};
this._options(options);
this._readied = false;
this._integrations = {};
// load user now that options are set
user.load();
group.load();
// clean unknown integrations from settings
var self = this;
each(settings, function (name) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
});
// make ready callback
var ready = after(size(settings), function () {
self._readied = true;
self.emit('ready');
});
// initialize integrations, passing ready
each(settings, function (name, opts) {
var Integration = self.Integrations[name];
if (options.initialPageview && opts.initialPageview === false) {
Integration.prototype.page = after(2, Integration.prototype.page);
}
var integration = new Integration(clone(opts));
integration.once('ready', ready);
integration.initialize();
self._integrations[name] = integration;
});
// backwards compat with angular plugin.
// TODO: remove
this.initialized = true;
this.emit('initialize', settings, options);
return this;
};
/**
* Identify a user by optional `id` and `traits`.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.identify = function (id, traits, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = user.id();
// clone traits before we manipulate so we don't do anything uncouth, and take
// from `user` so that we carryover anonymous traits
user.identify(id, traits);
id = user.id();
traits = user.traits();
this._invoke('identify', new Identify({
options: options,
traits: traits,
userId: id
}));
// emit
this.emit('identify', id, traits, options);
this._callback(fn);
return this;
};
/**
* Return the current user.
*
* @return {Object}
*/
Analytics.prototype.user = function () {
return user;
};
/**
* Identify a group by optional `id` and `traits`. Or, if no arguments are
* supplied, return the current group.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics or Object}
*/
Analytics.prototype.group = function (id, traits, options, fn) {
if (0 === arguments.length) return group;
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = group.id();
// grab from group again to make sure we're taking from the source
group.identify(id, traits);
id = group.id();
traits = group.traits();
this._invoke('group', new Group({
options: options,
traits: traits,
groupId: id
}));
this.emit('group', id, traits, options);
this._callback(fn);
return this;
};
/**
* Track an `event` that a user has triggered with optional `properties`.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.track = function (event, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = null, properties = null;
this._invoke('track', new Track({
properties: properties,
options: options,
event: event
}));
this.emit('track', event, properties, options);
this._callback(fn);
return this;
};
/**
* Helper method to track an outbound link that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackClick`.
*
* @param {Element or Array} links
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackClick =
Analytics.prototype.trackLink = function (links, event, properties) {
if (!links) return this;
if (is.element(links)) links = [links]; // always arrays, handles jquery
var self = this;
each(links, function (el) {
on(el, 'click', function (e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
if (el.href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function () {
window.location.href = el.href;
});
}
});
});
return this;
};
/**
* Helper method to track an outbound form that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackSubmit`.
*
* @param {Element or Array} forms
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackSubmit =
Analytics.prototype.trackForm = function (forms, event, properties) {
if (!forms) return this;
if (is.element(forms)) forms = [forms]; // always arrays, handles jquery
var self = this;
each(forms, function (el) {
function handler (e) {
prevent(e);
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
self._callback(function () {
el.submit();
});
}
// support the events happening through jQuery or Zepto instead of through
// the normal DOM API, since `el.submit` doesn't bubble up events...
var $ = window.jQuery || window.Zepto;
if ($) {
$(el).submit(handler);
} else {
on(el, 'submit', handler);
}
});
return this;
};
/**
* Trigger a pageview, labeling the current page with an optional `category`,
* `name` and `properties`.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object or String} properties (or path) (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.page = function (category, name, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = properties = null;
if (is.fn(name)) fn = name, options = properties = name = null;
if (is.object(category)) options = name, properties = category, name = category = null;
if (is.object(name)) options = properties, properties = name, name = null;
if (is.string(category) && !is.string(name)) name = category, category = null;
var defs = {
path: canonicalPath(),
referrer: document.referrer,
title: document.title,
search: location.search
};
if (name) defs.name = name;
if (category) defs.category = category;
properties = clone(properties) || {};
defaults(properties, defs);
properties.url = properties.url || canonicalUrl(properties.search);
this._invoke('page', new Page({
properties: properties,
category: category,
options: options,
name: name
}));
this.emit('page', category, name, properties, options);
this._callback(fn);
return this;
};
/**
* BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call.
*
* @param {String} url (optional)
* @param {Object} options (optional)
* @return {Analytics}
* @api private
*/
Analytics.prototype.pageview = function (url, options) {
var properties = {};
if (url) properties.path = url;
this.page(properties);
return this;
};
/**
* Merge two previously unassociated user identities.
*
* @param {String} to
* @param {String} from (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.alias = function (to, from, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(from)) fn = from, options = null, from = null;
if (is.object(from)) options = from, from = null;
this._invoke('alias', new Alias({
options: options,
from: from,
to: to
}));
this.emit('alias', to, from, options);
this._callback(fn);
return this;
};
/**
* Register a `fn` to be fired when all the analytics services are ready.
*
* @param {Function} fn
* @return {Analytics}
*/
Analytics.prototype.ready = function (fn) {
if (!is.fn(fn)) return this;
this._readied
? callback.async(fn)
: this.once('ready', fn);
return this;
};
/**
* Set the `timeout` (in milliseconds) used for callbacks.
*
* @param {Number} timeout
*/
Analytics.prototype.timeout = function (timeout) {
this._timeout = timeout;
};
/**
* Enable or disable debug.
*
* @param {String or Boolean} str
*/
Analytics.prototype.debug = function(str){
if (0 == arguments.length || str) {
debug.enable('analytics:' + (str || '*'));
} else {
debug.disable();
}
};
/**
* Apply options.
*
* @param {Object} options
* @return {Analytics}
* @api private
*/
Analytics.prototype._options = function (options) {
options = options || {};
cookie.options(options.cookie);
store.options(options.localStorage);
user.options(options.user);
group.options(options.group);
return this;
};
/**
* Callback a `fn` after our defined timeout period.
*
* @param {Function} fn
* @return {Analytics}
* @api private
*/
Analytics.prototype._callback = function (fn) {
callback.async(fn, this._timeout);
return this;
};
/**
* Call `method` with `facade` on all enabled integrations.
*
* @param {String} method
* @param {Facade} facade
* @return {Analytics}
* @api private
*/
Analytics.prototype._invoke = function (method, facade) {
var options = facade.options();
this.emit('invoke', facade);
each(this._integrations, function (name, integration) {
if (!facade.enabled(name)) return;
integration.invoke.call(integration, method, facade);
});
return this;
};
/**
* Push `args`.
*
* @param {Array} args
* @api private
*/
Analytics.prototype.push = function(args){
var method = args.shift();
if (!this[method]) return;
this[method].apply(this, args);
};
/**
* Parse the query string for callable methods.
*
* @return {Analytics}
* @api private
*/
Analytics.prototype._parseQuery = function () {
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var q = querystring.parse(window.location.search);
if (q.ajs_uid) this.identify(q.ajs_uid);
if (q.ajs_event) this.track(q.ajs_event);
return this;
};
/**
* Return the canonical path for the page.
*
* @return {String}
*/
function canonicalPath () {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
/**
* Return the canonical URL for the page concat the given `search`
* and strip the hash.
*
* @param {String} search
* @return {String}
*/
function canonicalUrl (search) {
var canon = canonical();
if (canon) return ~canon.indexOf('?') ? canon : canon + search;
var url = window.location.href;
var i = url.indexOf('#');
return -1 == i ? url : url.slice(0, i);
}
});
require.register("analytics/lib/cookie.js", function(exports, require, module){
var bind = require('bind');
var cookie = require('cookie');
var clone = require('clone');
var defaults = require('defaults');
var json = require('json');
var topDomain = require('top-domain');
/**
* Initialize a new `Cookie` with `options`.
*
* @param {Object} options
*/
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options.
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
var domain = '.' + topDomain(window.location.href);
// localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html
if ('.' == domain) domain = '';
defaults(options, {
maxage: 31536000000, // default to a year
path: '/',
domain: domain
});
this._options = options;
};
/**
* Set a `key` and `value` in our cookie.
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie by `key`.
*
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from our cookie by `key`.
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Expose the cookie singleton.
*/
module.exports = bind.all(new Cookie());
/**
* Expose the `Cookie` constructor.
*/
module.exports.Cookie = Cookie;
});
require.register("analytics/lib/entity.js", function(exports, require, module){
var traverse = require('isodate-traverse');
var defaults = require('defaults');
var cookie = require('./cookie');
var store = require('./store');
var extend = require('extend');
var clone = require('clone');
/**
* Expose `Entity`
*/
module.exports = Entity;
/**
* Initialize new `Entity` with `options`.
*
* @param {Object} options
*/
function Entity(options){
this.options(options);
}
/**
* Get or set storage `options`.
*
* @param {Object} options
* @property {Object} cookie
* @property {Object} localStorage
* @property {Boolean} persist (default: `true`)
*/
Entity.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, this.defaults || {});
this._options = options;
};
/**
* Get or set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype.id = function (id) {
switch (arguments.length) {
case 0: return this._getId();
case 1: return this._setId(id);
}
};
/**
* Get the entity's id.
*
* @return {String}
*/
Entity.prototype._getId = function () {
var ret = this._options.persist
? cookie.get(this._options.cookie.key)
: this._id;
return ret === undefined ? null : ret;
};
/**
* Set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype._setId = function (id) {
if (this._options.persist) {
cookie.set(this._options.cookie.key, id);
} else {
this._id = id;
}
};
/**
* Get or set the entity's `traits`.
*
* BACKWARDS COMPATIBILITY: aliased to `properties`
*
* @param {Object} traits
*/
Entity.prototype.properties =
Entity.prototype.traits = function (traits) {
switch (arguments.length) {
case 0: return this._getTraits();
case 1: return this._setTraits(traits);
}
};
/**
* Get the entity's traits. Always convert ISO date strings into real dates,
* since they aren't parsed back from local storage.
*
* @return {Object}
*/
Entity.prototype._getTraits = function () {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? traverse(clone(ret)) : {};
};
/**
* Set the entity's `traits`.
*
* @param {Object} traits
*/
Entity.prototype._setTraits = function (traits) {
traits || (traits = {});
if (this._options.persist) {
store.set(this._options.localStorage.key, traits);
} else {
this._traits = traits;
}
};
/**
* Identify the entity with an `id` and `traits`. If we it's the same entity,
* extend the existing `traits` instead of overwriting.
*
* @param {String} id
* @param {Object} traits
*/
Entity.prototype.identify = function (id, traits) {
traits || (traits = {});
var current = this.id();
if (current === null || current === id) traits = extend(this.traits(), traits);
if (id) this.id(id);
this.debug('identify %o, %o', id, traits);
this.traits(traits);
this.save();
};
/**
* Save the entity to local storage and the cookie.
*
* @return {Boolean}
*/
Entity.prototype.save = function () {
if (!this._options.persist) return false;
cookie.set(this._options.cookie.key, this.id());
store.set(this._options.localStorage.key, this.traits());
return true;
};
/**
* Log the entity out, reseting `id` and `traits` to defaults.
*/
Entity.prototype.logout = function () {
this.id(null);
this.traits({});
cookie.remove(this._options.cookie.key);
store.remove(this._options.localStorage.key);
};
/**
* Reset all entity state, logging out and returning options to defaults.
*/
Entity.prototype.reset = function () {
this.logout();
this.options({});
};
/**
* Load saved entity `id` or `traits` from storage.
*/
Entity.prototype.load = function () {
this.id(cookie.get(this._options.cookie.key));
this.traits(store.get(this._options.localStorage.key));
};
});
require.register("analytics/lib/group.js", function(exports, require, module){
var debug = require('debug')('analytics:group');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
/**
* Group defaults
*/
Group.defaults = {
persist: true,
cookie: {
key: 'ajs_group_id'
},
localStorage: {
key: 'ajs_group_properties'
}
};
/**
* Initialize a new `Group` with `options`.
*
* @param {Object} options
*/
function Group (options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(Group, Entity);
/**
* Expose the group singleton.
*/
module.exports = bind.all(new Group());
/**
* Expose the `Group` constructor.
*/
module.exports.Group = Group;
});
require.register("analytics/lib/store.js", function(exports, require, module){
var bind = require('bind');
var defaults = require('defaults');
var store = require('store');
/**
* Initialize a new `Store` with `options`.
*
* @param {Object} options
*/
function Store (options) {
this.options(options);
}
/**
* Set the `options` for the store.
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Set a `key` and `value` in local storage.
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Get a value from local storage by `key`.
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Remove a value from local storage by `key`.
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Expose the store singleton.
*/
module.exports = bind.all(new Store());
/**
* Expose the `Store` constructor.
*/
module.exports.Store = Store;
});
require.register("analytics/lib/user.js", function(exports, require, module){
var debug = require('debug')('analytics:user');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
var cookie = require('./cookie');
/**
* User defaults
*/
User.defaults = {
persist: true,
cookie: {
key: 'ajs_user_id',
oldKey: 'ajs_user'
},
localStorage: {
key: 'ajs_user_traits'
}
};
/**
* Initialize a new `User` with `options`.
*
* @param {Object} options
*/
function User (options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(User, Entity);
/**
* Load saved user `id` or `traits` from storage.
*/
User.prototype.load = function () {
if (this._loadOldCookie()) return;
Entity.prototype.load.call(this);
};
/**
* BACKWARDS COMPATIBILITY: Load the old user from the cookie.
*
* @return {Boolean}
* @api private
*/
User.prototype._loadOldCookie = function () {
var user = cookie.get(this._options.cookie.oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this._options.cookie.oldKey);
return true;
};
/**
* Expose the user singleton.
*/
module.exports = bind.all(new User());
/**
* Expose the `User` constructor.
*/
module.exports.User = User;
});
require.register("segmentio-analytics.js-integrations/lib/slugs.json", function(exports, require, module){
module.exports = [
"adroll",
"adwords",
"alexa",
"amplitude",
"awesm",
"awesomatic",
"bing-ads",
"bronto",
"bugherd",
"bugsnag",
"chartbeat",
"churnbee",
"clicky",
"comscore",
"crazy-egg",
"curebit",
"customerio",
"drip",
"errorception",
"evergage",
"facebook-ads",
"foxmetrics",
"frontleaf",
"gauges",
"get-satisfaction",
"google-analytics",
"google-tag-manager",
"gosquared",
"heap",
"hellobar",
"hittail",
"hubspot",
"improvely",
"inspectlet",
"intercom",
"keen-io",
"kenshoo",
"kissmetrics",
"klaviyo",
"leadlander",
"livechat",
"lucky-orange",
"lytics",
"mixpanel",
"mojn",
"mouseflow",
"mousestats",
"navilytics",
"olark",
"optimizely",
"perfect-audience",
"pingdom",
"piwik",
"preact",
"qualaroo",
"quantcast",
"rollbar",
"saasquatch",
"sentry",
"snapengage",
"spinnakr",
"tapstream",
"trakio",
"twitter-ads",
"usercycle",
"userfox",
"uservoice",
"vero",
"visual-website-optimizer",
"webengage",
"woopra",
"yandex-metrica"
]
});
require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js");
require.alias("avetisk-defaults/index.js", "defaults/index.js");
require.alias("component-clone/index.js", "analytics/deps/clone/index.js");
require.alias("component-clone/index.js", "clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js");
require.alias("component-cookie/index.js", "cookie/index.js");
require.alias("component-each/index.js", "analytics/deps/each/index.js");
require.alias("component-each/index.js", "each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-emitter/index.js", "analytics/deps/emitter/index.js");
require.alias("component-emitter/index.js", "emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("component-event/index.js", "analytics/deps/event/index.js");
require.alias("component-event/index.js", "event/index.js");
require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js");
require.alias("component-inherit/index.js", "inherit/index.js");
require.alias("component-object/index.js", "analytics/deps/object/index.js");
require.alias("component-object/index.js", "object/index.js");
require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js");
require.alias("component-querystring/index.js", "querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-type/index.js", "component-querystring/deps/type/index.js");
require.alias("component-url/index.js", "analytics/deps/url/index.js");
require.alias("component-url/index.js", "url/index.js");
require.alias("ianstormtaylor-bind/index.js", "analytics/deps/bind/index.js");
require.alias("ianstormtaylor-bind/index.js", "bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "analytics/deps/callback/index.js");
require.alias("ianstormtaylor-callback/index.js", "callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-is/index.js", "analytics/deps/is/index.js");
require.alias("ianstormtaylor-is/index.js", "is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-after/index.js", "analytics/deps/after/index.js");
require.alias("segmentio-after/index.js", "after/index.js");
require.alias("segmentio-analytics.js-integrations/index.js", "analytics/deps/integrations/index.js");
require.alias("segmentio-analytics.js-integrations/lib/adroll.js", "analytics/deps/integrations/lib/adroll.js");
require.alias("segmentio-analytics.js-integrations/lib/adwords.js", "analytics/deps/integrations/lib/adwords.js");
require.alias("segmentio-analytics.js-integrations/lib/alexa.js", "analytics/deps/integrations/lib/alexa.js");
require.alias("segmentio-analytics.js-integrations/lib/amplitude.js", "analytics/deps/integrations/lib/amplitude.js");
require.alias("segmentio-analytics.js-integrations/lib/awesm.js", "analytics/deps/integrations/lib/awesm.js");
require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js", "analytics/deps/integrations/lib/awesomatic.js");
require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js", "analytics/deps/integrations/lib/bing-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/bronto.js", "analytics/deps/integrations/lib/bronto.js");
require.alias("segmentio-analytics.js-integrations/lib/bugherd.js", "analytics/deps/integrations/lib/bugherd.js");
require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js", "analytics/deps/integrations/lib/bugsnag.js");
require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js", "analytics/deps/integrations/lib/chartbeat.js");
require.alias("segmentio-analytics.js-integrations/lib/churnbee.js", "analytics/deps/integrations/lib/churnbee.js");
require.alias("segmentio-analytics.js-integrations/lib/clicky.js", "analytics/deps/integrations/lib/clicky.js");
require.alias("segmentio-analytics.js-integrations/lib/comscore.js", "analytics/deps/integrations/lib/comscore.js");
require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js", "analytics/deps/integrations/lib/crazy-egg.js");
require.alias("segmentio-analytics.js-integrations/lib/curebit.js", "analytics/deps/integrations/lib/curebit.js");
require.alias("segmentio-analytics.js-integrations/lib/customerio.js", "analytics/deps/integrations/lib/customerio.js");
require.alias("segmentio-analytics.js-integrations/lib/drip.js", "analytics/deps/integrations/lib/drip.js");
require.alias("segmentio-analytics.js-integrations/lib/errorception.js", "analytics/deps/integrations/lib/errorception.js");
require.alias("segmentio-analytics.js-integrations/lib/evergage.js", "analytics/deps/integrations/lib/evergage.js");
require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js", "analytics/deps/integrations/lib/facebook-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js", "analytics/deps/integrations/lib/foxmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/frontleaf.js", "analytics/deps/integrations/lib/frontleaf.js");
require.alias("segmentio-analytics.js-integrations/lib/gauges.js", "analytics/deps/integrations/lib/gauges.js");
require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js", "analytics/deps/integrations/lib/get-satisfaction.js");
require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js", "analytics/deps/integrations/lib/google-analytics.js");
require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js", "analytics/deps/integrations/lib/google-tag-manager.js");
require.alias("segmentio-analytics.js-integrations/lib/gosquared.js", "analytics/deps/integrations/lib/gosquared.js");
require.alias("segmentio-analytics.js-integrations/lib/heap.js", "analytics/deps/integrations/lib/heap.js");
require.alias("segmentio-analytics.js-integrations/lib/hellobar.js", "analytics/deps/integrations/lib/hellobar.js");
require.alias("segmentio-analytics.js-integrations/lib/hittail.js", "analytics/deps/integrations/lib/hittail.js");
require.alias("segmentio-analytics.js-integrations/lib/hubspot.js", "analytics/deps/integrations/lib/hubspot.js");
require.alias("segmentio-analytics.js-integrations/lib/improvely.js", "analytics/deps/integrations/lib/improvely.js");
require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js", "analytics/deps/integrations/lib/inspectlet.js");
require.alias("segmentio-analytics.js-integrations/lib/intercom.js", "analytics/deps/integrations/lib/intercom.js");
require.alias("segmentio-analytics.js-integrations/lib/keen-io.js", "analytics/deps/integrations/lib/keen-io.js");
require.alias("segmentio-analytics.js-integrations/lib/kenshoo.js", "analytics/deps/integrations/lib/kenshoo.js");
require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js", "analytics/deps/integrations/lib/kissmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js", "analytics/deps/integrations/lib/klaviyo.js");
require.alias("segmentio-analytics.js-integrations/lib/leadlander.js", "analytics/deps/integrations/lib/leadlander.js");
require.alias("segmentio-analytics.js-integrations/lib/livechat.js", "analytics/deps/integrations/lib/livechat.js");
require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js", "analytics/deps/integrations/lib/lucky-orange.js");
require.alias("segmentio-analytics.js-integrations/lib/lytics.js", "analytics/deps/integrations/lib/lytics.js");
require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js", "analytics/deps/integrations/lib/mixpanel.js");
require.alias("segmentio-analytics.js-integrations/lib/mojn.js", "analytics/deps/integrations/lib/mojn.js");
require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js", "analytics/deps/integrations/lib/mouseflow.js");
require.alias("segmentio-analytics.js-integrations/lib/mousestats.js", "analytics/deps/integrations/lib/mousestats.js");
require.alias("segmentio-analytics.js-integrations/lib/navilytics.js", "analytics/deps/integrations/lib/navilytics.js");
require.alias("segmentio-analytics.js-integrations/lib/olark.js", "analytics/deps/integrations/lib/olark.js");
require.alias("segmentio-analytics.js-integrations/lib/optimizely.js", "analytics/deps/integrations/lib/optimizely.js");
require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js", "analytics/deps/integrations/lib/perfect-audience.js");
require.alias("segmentio-analytics.js-integrations/lib/pingdom.js", "analytics/deps/integrations/lib/pingdom.js");
require.alias("segmentio-analytics.js-integrations/lib/piwik.js", "analytics/deps/integrations/lib/piwik.js");
require.alias("segmentio-analytics.js-integrations/lib/preact.js", "analytics/deps/integrations/lib/preact.js");
require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js", "analytics/deps/integrations/lib/qualaroo.js");
require.alias("segmentio-analytics.js-integrations/lib/quantcast.js", "analytics/deps/integrations/lib/quantcast.js");
require.alias("segmentio-analytics.js-integrations/lib/rollbar.js", "analytics/deps/integrations/lib/rollbar.js");
require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js", "analytics/deps/integrations/lib/saasquatch.js");
require.alias("segmentio-analytics.js-integrations/lib/sentry.js", "analytics/deps/integrations/lib/sentry.js");
require.alias("segmentio-analytics.js-integrations/lib/snapengage.js", "analytics/deps/integrations/lib/snapengage.js");
require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js", "analytics/deps/integrations/lib/spinnakr.js");
require.alias("segmentio-analytics.js-integrations/lib/tapstream.js", "analytics/deps/integrations/lib/tapstream.js");
require.alias("segmentio-analytics.js-integrations/lib/trakio.js", "analytics/deps/integrations/lib/trakio.js");
require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js", "analytics/deps/integrations/lib/twitter-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/usercycle.js", "analytics/deps/integrations/lib/usercycle.js");
require.alias("segmentio-analytics.js-integrations/lib/userfox.js", "analytics/deps/integrations/lib/userfox.js");
require.alias("segmentio-analytics.js-integrations/lib/uservoice.js", "analytics/deps/integrations/lib/uservoice.js");
require.alias("segmentio-analytics.js-integrations/lib/vero.js", "analytics/deps/integrations/lib/vero.js");
require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", "analytics/deps/integrations/lib/visual-website-optimizer.js");
require.alias("segmentio-analytics.js-integrations/lib/webengage.js", "analytics/deps/integrations/lib/webengage.js");
require.alias("segmentio-analytics.js-integrations/lib/woopra.js", "analytics/deps/integrations/lib/woopra.js");
require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js", "analytics/deps/integrations/lib/yandex-metrica.js");
require.alias("segmentio-analytics.js-integrations/index.js", "integrations/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integrations/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integrations/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-domify/index.js", "segmentio-analytics.js-integrations/deps/domify/index.js");
require.alias("component-each/index.js", "segmentio-analytics.js-integrations/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-once/index.js", "segmentio-analytics.js-integrations/deps/once/index.js");
require.alias("component-type/index.js", "segmentio-analytics.js-integrations/deps/type/index.js");
require.alias("component-url/index.js", "segmentio-analytics.js-integrations/deps/url/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integrations/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "segmentio-analytics.js-integrations/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integrations/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-analytics.js-integrations/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "segmentio-analytics.js-integrations/deps/is-empty/index.js");
require.alias("segmentio-alias/index.js", "segmentio-analytics.js-integrations/deps/alias/index.js");
require.alias("component-clone/index.js", "segmentio-alias/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-type/index.js", "segmentio-alias/deps/type/index.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/lib/index.js");
require.alias("segmentio-analytics.js-integration/lib/protos.js", "segmentio-analytics.js-integrations/deps/integration/lib/protos.js");
require.alias("segmentio-analytics.js-integration/lib/events.js", "segmentio-analytics.js-integrations/deps/integration/lib/events.js");
require.alias("segmentio-analytics.js-integration/lib/statics.js", "segmentio-analytics.js-integrations/deps/integration/lib/statics.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "segmentio-analytics.js-integration/deps/to-no-case/index.js");
require.alias("component-type/index.js", "segmentio-analytics.js-integration/deps/type/index.js");
require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js");
require.alias("segmentio-canonical/index.js", "segmentio-analytics.js-integrations/deps/canonical/index.js");
require.alias("segmentio-convert-dates/index.js", "segmentio-analytics.js-integrations/deps/convert-dates/index.js");
require.alias("component-clone/index.js", "segmentio-convert-dates/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-convert-dates/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-extend/index.js", "segmentio-analytics.js-integrations/deps/extend/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "segmentio-analytics.js-integrations/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "segmentio-analytics.js-integrations/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "segmentio-analytics.js-integrations/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "segmentio-analytics.js-integrations/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "segmentio-analytics.js-integrations/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "segmentio-analytics.js-integrations/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/screen.js", "segmentio-analytics.js-integrations/deps/facade/lib/screen.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-global-queue/index.js", "segmentio-analytics.js-integrations/deps/global-queue/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-analytics.js-integrations/deps/is-email/index.js");
require.alias("segmentio-load-date/index.js", "segmentio-analytics.js-integrations/deps/load-date/index.js");
require.alias("segmentio-load-script/index.js", "segmentio-analytics.js-integrations/deps/load-script/index.js");
require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-analytics.js-integrations/deps/script-onload/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-analytics.js-integrations/deps/script-onload/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-script-onload/index.js");
require.alias("segmentio-on-body/index.js", "segmentio-analytics.js-integrations/deps/on-body/index.js");
require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("segmentio-on-error/index.js", "segmentio-analytics.js-integrations/deps/on-error/index.js");
require.alias("segmentio-to-iso-string/index.js", "segmentio-analytics.js-integrations/deps/to-iso-string/index.js");
require.alias("segmentio-to-unix-timestamp/index.js", "segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");
require.alias("segmentio-use-https/index.js", "segmentio-analytics.js-integrations/deps/use-https/index.js");
require.alias("segmentio-when/index.js", "segmentio-analytics.js-integrations/deps/when/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-when/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integrations/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integrations/deps/slug/index.js");
require.alias("visionmedia-batch/index.js", "segmentio-analytics.js-integrations/deps/batch/index.js");
require.alias("component-emitter/index.js", "visionmedia-batch/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integrations/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integrations/deps/debug/debug.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("component-querystring/index.js", "segmentio-load-pixel/deps/querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-type/index.js", "component-querystring/deps/type/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-substitute/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-load-pixel/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-analytics.js-integrations/deps/replace-document-write/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-analytics.js-integrations/deps/replace-document-write/index.js");
require.alias("component-domify/index.js", "segmentio-replace-document-write/deps/domify/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-replace-document-write/index.js");
require.alias("component-indexof/index.js", "segmentio-analytics.js-integrations/deps/indexof/index.js");
require.alias("component-object/index.js", "segmentio-analytics.js-integrations/deps/object/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-analytics.js-integrations/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-analytics.js-integrations/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js");
require.alias("segmentio-canonical/index.js", "canonical/index.js");
require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js");
require.alias("segmentio-extend/index.js", "extend/index.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "analytics/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "analytics/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "analytics/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "analytics/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "analytics/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "analytics/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "analytics/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/screen.js", "analytics/deps/facade/lib/screen.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/index.js");
require.alias("segmentio-facade/lib/index.js", "facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js");
require.alias("segmentio-is-email/index.js", "is-email/index.js");
require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js");
require.alias("segmentio-is-meta/index.js", "is-meta/index.js");
require.alias("segmentio-isodate-traverse/index.js", "analytics/deps/isodate-traverse/index.js");
require.alias("segmentio-isodate-traverse/index.js", "isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("segmentio-json/index.js", "analytics/deps/json/index.js");
require.alias("segmentio-json/index.js", "json/index.js");
require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "analytics/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "analytics/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/index.js");
require.alias("segmentio-new-date/lib/index.js", "new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js");
require.alias("segmentio-store.js/store.js", "store/index.js");
require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "top-domain/index.js");
require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js");
require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js");
require.alias("visionmedia-debug/index.js", "analytics/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "analytics/deps/debug/debug.js");
require.alias("visionmedia-debug/index.js", "debug/index.js");
require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js");
require.alias("yields-prevent/index.js", "prevent/index.js");
require.alias("analytics/lib/index.js", "analytics/index.js");if (typeof exports == "object") {
module.exports = require("analytics");
} else if (typeof define == "function" && define.amd) {
define([], function(){ return require("analytics"); });
} else {
this["analytics"] = require("analytics");
}})(); |
app/containers/ProfilePage/FormInput.js | VeloCloud/website-ui | import React from 'react';
// import { FormGroup, FormControl } from 'react-bootstrap';
// Will need to change div to FormControl
function ListItem(props) {
const name = props.name;
console.log('name', name, 'value', props.value);
return (
<div className="form-group">
<label className="col-sm-2 control-label" htmlFor={name}>
{name}
</label>
{/* <FormControl
type="text"
placeholder="Name"
id={name}
onChange={props.updater}
value={props.value}
/> */}
<div className="col-sm-10">
<input
type="text"
placeholder="Name"
className="form-control"
id={name}
onChange={props.updater}
value={props.value}
/>
</div>
</div>
);
}
ListItem.propTypes = {
name: React.PropTypes.string,
updater: React.PropTypes.func,
value: React.PropTypes.string,
};
export default ListItem;
|
classic/src/scenes/wbui/ACAvatarCircle/ACAvatarCircle.js | wavebox/waveboxapp | import React from 'react'
import PropTypes from 'prop-types'
import { Avatar } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import classNames from 'classnames'
let warningShown = false
const styles = {
container: {
// Makes the box-shadow render when border radius is used
transform: 'translate3d(0,0,0)',
// White ring fix part 1/3 (2-lines)
// https://css-tricks.com/forums/topic/border-radius-ugliness/
'&.with-ring': {
backgroundClip: 'content-box',
padding: 1
}
},
img: {
textIndent: -100000, // Stops showing the broken image icon if the url doesn't resolve
// White ring fix part 2/3 (3-lines)
'&.with-ring': {
margin: -1,
width: 'calc(100% + 2px)',
height: 'calc(100% + 2px)'
}
},
sleeping: {
filter: 'grayscale(100%)'
},
restricted: {
backgroundColor: '#EEE',
filter: 'grayscale(100%)'
},
restrictedCharacterDisplay: {
backgroundColor: '#BBB !important',
color: '#FFF !important'
}
}
@withStyles(styles)
class ACAvatarCircle extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
avatar: PropTypes.object.isRequired,
resolver: PropTypes.func.isRequired,
size: PropTypes.number.isRequired,
showSleeping: PropTypes.bool.isRequired,
showRestricted: PropTypes.bool.isRequired,
preferredImageSize: PropTypes.number,
borderSize: PropTypes.number
}
static defaultProps = {
size: 40,
showSleeping: false,
showRestricted: false
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
if (!warningShown) {
warningShown = true
console.warn('ACAvatarCircle has been depricated. Instead use ACAvatarCircle2')
}
const {
avatar,
resolver,
style,
size,
classes,
className,
showSleeping,
showRestricted,
preferredImageSize,
borderSize,
...otherProps
} = this.props
const generatedStyle = {
backgroundColor: 'white'
}
// Style: Border size and color
// Use a box shadow hack rather than border to fix a phantom white line
// https://stackoverflow.com/questions/31805296/why-do-i-get-a-faint-border-around-css-circles-in-internet-explorer
// This has the side effect of now overflowing the element, so try to be a bit intelligent about
// reducing the size depending on the passed props
const generatedBorderSize = typeof (borderSize) === 'number' ? borderSize : Math.round(size * 0.08)
const adjustedSize = size - (2 * generatedBorderSize)
generatedStyle.width = adjustedSize
generatedStyle.height = adjustedSize
generatedStyle.lineHeight = `${adjustedSize}px`
if (avatar.showAvatarColorRing) {
generatedStyle.boxShadow = `0 0 0 ${generatedBorderSize}px ${avatar.color}`
}
const passProps = {
...otherProps,
imgProps: {
draggable: false,
...otherProps.imgProps
},
classes: {
...otherProps.classes,
img: classNames(
classes.img,
showRestricted ? classes.restricted : undefined,
avatar.showAvatarColorRing ? 'with-ring' : undefined,
(otherProps.classes || {}).img
)
},
className: classNames(
className,
classes.container,
showSleeping ? classes.sleeping : undefined,
avatar.showAvatarColorRing ? 'with-ring' : undefined
)
}
if (avatar.hasAvatar) {
return (
<Avatar
{...passProps}
style={{ ...generatedStyle, ...style }}
src={avatar.resolveAvatar(resolver)} />
)
} else if (avatar.avatarCharacterDisplay) {
const charaterStyle = {
...generatedStyle,
backgroundColor: avatar.color,
fontSize: Math.round(adjustedSize * 0.55),
padding: 0, // White ring fix part 3/3
...style
}
if (showRestricted) {
return (
<Avatar
{...passProps}
className={classNames(passProps.className, classes.restrictedCharacterDisplay)}
style={charaterStyle}>
{avatar.avatarCharacterDisplay}
</Avatar>
)
} else {
return (
<Avatar
{...passProps}
style={charaterStyle}>
{avatar.avatarCharacterDisplay}
</Avatar>
)
}
} else if (avatar.hasServiceIcon) {
const src = typeof (preferredImageSize) === 'number'
? avatar.resolveServiceIconWithSize(preferredImageSize, resolver)
: avatar.resolveServiceIcon(resolver)
return (
<Avatar
{...passProps}
style={{ ...generatedStyle, ...style }}
src={src} />
)
} else {
return (
<Avatar
{...passProps}
style={{ ...generatedStyle, ...style }} />)
}
}
}
export default ACAvatarCircle
|
definitions/npm/styled-components_v2.x.x/flow_v0.42.x-v0.52.x/test_styled-components_v2.x.x.js | flowtype/flow-typed | // @flow
import {renderToString} from 'react-dom/server'
import styled, {
ThemeProvider,
withTheme,
keyframes,
ServerStyleSheet,
StyleSheetManager
} from 'styled-components'
import React from 'react'
import type {
Theme,
Interpolation,
// Temporary
ReactComponentFunctional,
ReactComponentClass,
ReactComponentStyled,
ReactComponentStyledTaggedTemplateLiteral,
ReactComponentUnion,
ReactComponentIntersection,
} from 'styled-components'
const TitleTaggedTemplateLiteral: ReactComponentStyledTaggedTemplateLiteral<{}> = styled.h1;
const TitleStyled: ReactComponentStyled<*> = styled.h1`
font-size: 1.5em;
`;
const TitleGeneric: ReactComponentIntersection<*> = styled.h1`
font-size: 1.5em;
`;
const TitleFunctional: ReactComponentFunctional<*> = styled.h1`
font-size: 1.5em;
`;
const TitleClass: ReactComponentClass<*> = styled.h1`
font-size: 1.5em;
`;
declare var needsReactComponentFunctional: ReactComponentFunctional<*> => void
declare var needsReactComponentClass: ReactComponentClass<*> => void
needsReactComponentFunctional(TitleStyled)
needsReactComponentClass(TitleStyled)
const ExtendedTitle: ReactComponentIntersection<*> = styled(TitleStyled)`
font-size: 2em;
`;
const Wrapper: ReactComponentIntersection<*> = styled.section`
padding: 4em;
background: ${({theme}) => theme.background};
`;
// ---- EXTEND ----
const Attrs0ReactComponent: ReactComponentStyled<*> = styled.div.extend``;
const Attrs0ExtendReactComponent: ReactComponentIntersection<*> = Attrs0ReactComponent.extend``;
const Attrs0SyledComponent: ReactComponentStyledTaggedTemplateLiteral<*> = styled.div;
const Attrs0ExtendStyledComponent: ReactComponentIntersection<*> = Attrs0SyledComponent.extend``;
// ---- ATTRIBUTES ----
const Attrs1: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section.attrs({
testProp: 'foo'
});
// $FlowExpectedError
const Attrs1Error: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section.attrs({
testProp: 'foo'
})``;
declare var needsString: string => void
needsReactComponentFunctional(styled.section.attrs({})``)
needsReactComponentClass(styled.section.attrs({})``)
// $FlowExpectedError
needsString(styled.section.attrs({})``)
const Attrs2: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section
.attrs({
testProp1: 'foo'
})
.attrs({
testProp2: 'bar'
});
const Attrs3Styled: ReactComponentStyled<*> = styled.section.attrs({
testProp: 'foo'
})`
background-color: red;
`;
const Attrs3Generic: ReactComponentIntersection<*> = styled.section.attrs({
testProp: 'foo'
})`
background-color: red;
`;
const Attrs3Functional: ReactComponentFunctional<*> = styled.section.attrs({
testProp: 'foo'
})`
background-color: red;
`;
const Attrs3Class: ReactComponentClass<*> = styled.section.attrs({
testProp: 'foo'
})`
background-color: red;
`;
const theme: Theme = {
background: "papayawhip"
};
// ---- WithComponent ----
const withComponent1: ReactComponentStyled<*> = styled.div.withComponent('a');
const withComponent2: ReactComponentStyled<*> = styled.div.withComponent(withComponent1);
const withComponent3: ReactComponentStyled<*> = styled.div.withComponent(Attrs3Class);
// $FlowExpectedError
const withComponentError1: ReactComponentStyled<*> = styled.div.withComponent(0);
// $FlowExpectedError
const withComponentError2: ReactComponentStyled<*> = styled.div.withComponent('NotHere');
// ---- WithTheme ----
const Component: ReactComponentFunctional<{ theme: Theme }> = ({ theme }) => (
<ThemeProvider theme={theme}>
<Wrapper>
<TitleStyled>Hello World, this is my first styled component!</TitleStyled>
</Wrapper>
</ThemeProvider>
);
const ComponentWithTheme: ReactComponentFunctional<{}> = withTheme(Component);
const Component2: ReactComponentFunctional<{}> = () => (
<ThemeProvider theme={outerTheme => outerTheme}>
<Wrapper>
<TitleStyled>Hello World, this is my first styled component!</TitleStyled>
</Wrapper>
</ThemeProvider>
);
const OpacityKeyFrame: string = keyframes`
0% { opacity: 0; }
100% { opacity: 1; }
`;
// $FlowExpectedError
const NoExistingElementWrapper = styled.nonexisting`
padding: 4em;
background: papayawhip;
`;
const num: 9 = 9
// $FlowExpectedError
const NoExistingComponentWrapper = styled()`
padding: 4em;
background: papayawhip;
`;
// $FlowExpectedError
const NumberWrapper = styled(num)`
padding: 4em;
background: papayawhip;
`;
const sheet = new ServerStyleSheet()
const html = renderToString(sheet.collectStyles(<ComponentWithTheme />))
const css = sheet.getStyleTags()
const sheet2 = new ServerStyleSheet()
const html2 = renderToString(
<StyleSheetManager sheet={sheet}>
<ComponentWithTheme />
</StyleSheetManager>
)
const css2 = sheet.getStyleTags()
const css3 = sheet.getStyleElement()
// ---- COMPONENT CLASS TESTS ----
class NeedsThemeReactClass extends React.Component {
props: { foo: string, theme: Theme }
render() { return <div />; }
}
class ReactClass extends React.Component {
props: { foo: string }
render() { return <div />; }
}
const StyledClass: ReactComponentClass<{ foo: string, theme: Theme }> = styled(NeedsThemeReactClass)`
color: red;
`;
const NeedsFoo1Class: ReactComponentClass<{ foo: string }, { theme: Theme }> = withTheme(NeedsThemeReactClass);
// $FlowExpectedError
const NeedsFoo0ClassError: ReactComponentClass<{ foo: string }> = withTheme(ReactClass);
// $FlowExpectedError
const NeedsFoo1ClassError: ReactComponentClass<{ foo: string }> = withTheme(NeedsFoo1Class);
// $FlowExpectedError
const NeedsFoo1ErrorClass: ReactComponentClass<{ foo: number }> = withTheme(NeedsThemeReactClass);
// $FlowExpectedError
const NeedsFoo2ErrorClass: ReactComponentClass<{ foo: string }, { theme: string }> = withTheme(NeedsThemeReactClass);
// $FlowExpectedError
const NeedsFoo3ErrorClass: ReactComponentClass<{ foo: string, theme: Theme }> = withTheme(NeedsFoo1Class);
// $FlowExpectedError
const NeedsFoo4ErrorClass: ReactComponentClass<{ foo: number }> = withTheme(NeedsFoo1Class);
// $FlowExpectedError
const NeedsFoo5ErrorClass: ReactComponentClass<{ foo: string, theme: string }> = withTheme(NeedsFoo1Class);
// ---- INTERPOLATION TESTS ----
const interpolation: Array<Interpolation> = styled.css`
background-color: red;
`;
// $FlowExpectedError
const interpolationError: Array<Interpolation | boolean> = styled.css`
background-color: red;
`;
// ---- DEFAULT COMPONENT TESTS ----
const defaultComponent: ReactComponentIntersection<{}> = styled.div`
background-color: red;
`;
// $FlowExpectedError
const defaultComponentError: {} => string = styled.div`
background-color: red;
`;
// ---- FUNCTIONAL COMPONENT TESTS ----
const FunctionalComponent: ReactComponentFunctional<{ foo: string, theme: Theme }> = props => <div />;
const NeedsFoo1: ReactComponentFunctional<{ foo: string, theme: Theme }> = styled(FunctionalComponent)`
background-color: red;
`;
// $FlowExpectedError
const NeedsFoo1Error: ReactComponentFunctional<{ foo: number }> = styled(FunctionalComponent)`
background-color: red;
`;
const NeedsFoo2: ReactComponentFunctional<{ foo: string, theme: Theme }> = styled(NeedsFoo1)`
background-color: red;
`;
// $FlowExpectedError
const NeedsFoo2Error: ReactComponentFunctional<{ foo: number }> = styled(NeedsFoo1)`
background-color: red;
`;
// ---- FUNCTIONAL COMPONENT TESTS (withTheme)----
const NeedsFoo1Functional: ReactComponentFunctional<{ foo: string }> = withTheme(FunctionalComponent);
const NeedsFoo2Functional: ReactComponentFunctional<{ foo: string }> = withTheme(NeedsFoo1Functional);
// $FlowExpectedError
const NeedsFoo1ErrorFunctional: ReactComponentFunctional<{ foo: number }> = withTheme(FunctionalComponent);
// $FlowExpectedError
const NeedsFoo2ErrorFunctional: ReactComponentFunctional<{ foo: string }, { theme: string }> = withTheme(FunctionalComponent);
// $FlowExpectedError
const NeedsFoo3ErrorFunctional: ReactComponentFunctional<{ foo: number, theme: Theme }> = withTheme(FunctionalComponent);
// $FlowExpectedError
const NeedsFoo4ErrorFunctional: ReactComponentFunctional<{ foo: number }> = withTheme(NeedsFoo1Functional);
// $FlowExpectedError
const NeedsFoo5ErrorFunctional: ReactComponentFunctional<{ foo: string }, { theme: string }> = withTheme(NeedsFoo1Functional);
// $FlowExpectedError
const NeedsFoo6ErrorFunctional: ReactComponentFunctional<{ foo: number }, { theme: Theme }> = withTheme(NeedsFoo1Functional);
|
ajax/libs/primereact/8.1.0/calendar/calendar.cjs.min.js | cdnjs/cdnjs | "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("primereact/api"),n=require("primereact/button"),a=require("primereact/hooks"),r=require("primereact/inputtext"),l=require("primereact/overlayservice"),o=require("primereact/utils"),i=require("primereact/ripple"),u=require("primereact/csstransition"),s=require("primereact/portal");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function m(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var d=m(e),p=c(t);function f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(){return g=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},g.apply(this,arguments)}function h(e){return h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h(e)}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=e[n];return a}function D(e){if(Array.isArray(e))return v(e)}function y(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function b(e,t){if(e){if("string"==typeof e)return v(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(e,t):void 0}}function M(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function w(e){return D(e)||y(e)||b(e)||M()}function k(e){if(Array.isArray(e))return e}function E(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var a,r,l=[],o=!0,i=!1;try{for(n=n.call(e);!(o=(a=n.next()).done)&&(l.push(a.value),!t||l.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==n.return||n.return()}finally{if(i)throw r}}return l}}function S(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function x(e,t){return k(e)||E(e,t)||b(e,t)||S()}var N=d.forwardRef((function(e,t){var n=d.createElement(u.CSSTransition,{nodeRef:t,classNames:"p-connected-overlay",in:e.in,timeout:{enter:120,exit:100},options:e.transitionOptions,unmountOnExit:!0,onEnter:e.onEnter,onEntered:e.onEntered,onExit:e.onExit,onExited:e.onExited},d.createElement("div",{ref:t,className:e.className,style:e.style,onClick:e.onClick,onMouseUp:e.onMouseUp},e.children));return e.inline?n:d.createElement(s.Portal,{element:n,appendTo:e.appendTo})}));function H(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=C(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var a=0,r=function(){};return{s:r,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var l,o=!0,i=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){i=!0,l=e},f:function(){try{o||null==n.return||n.return()}finally{if(i)throw l}}}}function C(e,t){if(e){if("string"==typeof e)return I(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?I(e,t):void 0}}function I(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=e[n];return a}N.displayName="CalendarPanel";var O=d.memo(d.forwardRef((function(e,u){var s,c=x(d.useState(!1),2),m=c[0],v=c[1],D=x(d.useState(!1),2),y=D[0],b=D[1],M=x(d.useState(null),2),k=M[0],E=M[1],S=d.useRef(null),C=d.useRef(null),I=d.useRef(e.inputRef),F=d.useRef(null),T=d.useRef(!1),Y=d.useRef(!1),R=d.useRef(null),A=d.useRef(!1),U=d.useRef(null),B=d.useRef(null),j=d.useRef(null),P=d.useRef(!1),K=x(d.useState("date"),2),L=K[0],q=K[1],V=x(d.useState(null),2),W=V[0],Z=V[1],_=x(d.useState(null),2),z=_[0],J=_[1],X=x(d.useState([]),2),$=X[0],G=X[1],Q=a.usePrevious(e.value),ee=e.inline||(e.onVisibleChange?e.visible:y),te=o.UniqueComponentId(),ne=x(a.useOverlayListener({target:S,overlay:C,listener:function(e,t){t.valid&&("outside"===t.type?!P.current&&!bt(e.target)&&ft("outside"):ft()),P.current=!1},when:!(e.touchUI||e.inline)&&ee}),2),ae=ne[0],re=ne[1],le=function(){return e.dateFormat||t.localeOption("dateFormat",e.locale)},oe=function(t){T.current?(v(!0),T.current=!1):(e.showOnFocus&&!ee&&pt(),v(!0),e.onFocus&&e.onFocus(t))},ie=function(t){v(!1),!e.keepInvalid&&_t(e.value),e.onBlur&&e.onBlur(t)},ue=function(t){switch(Y.current=!0,t.which){case 27:ft();break;case 9:ee&&ve(t),e.touchUI&&vt()}},se=function(t){Y.current&&(Y.current=!1,ce(t,t.target.value),e.onInput&&e.onInput(t))},ce=function(t,n){try{var a=$t(n);de(a)&&(dt(t,a),et(t,a.length?a[0]:a))}catch(a){dt(t,e.keepInvalid?n:null)}},me=function(){!e.inline&&I.current&&(T.current=!0,I.current.focus())},de=function(e){var t=!0;return Kt()?Ft(e.getDate(),e.getMonth(),e.getFullYear(),!1)&&Tt(e)||(t=!1):e.every((function(e){return Ft(e.getDate(),e.getMonth(),e.getFullYear(),!1)&&Tt(e)}))&&Lt()&&(t=e.length>1&&e[1]>e[0]),t},pe=function(){ee?ft():pt()},fe=function(e){F.current={backward:!0,button:!0},be(e)},ge=function(e){F.current={backward:!1,button:!0},Me(e)},he=function(e){switch(e.which){case 9:ve(e);break;case 27:ft(null,me),e.preventDefault()}},ve=function(e){e.preventDefault();var t=o.DomHandler.getFocusableElements(C.current);if(t&&t.length>0)if(document.activeElement){var n=t.indexOf(document.activeElement);e.shiftKey?-1===n||0===n?t[t.length-1].focus():t[n-1].focus():-1===n||n===t.length-1?t[0].focus():t[n+1].focus()}else t[0].focus()},De=function(){if(F.current){if(F.current.button)ye(),F.current.backward?o.DomHandler.findSingle(C.current,".p-datepicker-prev").focus():o.DomHandler.findSingle(C.current,".p-datepicker-next").focus();else{var e;if(F.current.backward){var t=o.DomHandler.find(C.current,".p-datepicker-calendar td span:not(.p-disabled)");e=t[t.length-1]}else e=o.DomHandler.findSingle(C.current,".p-datepicker-calendar td span:not(.p-disabled)");e&&(e.tabIndex="0",e.focus())}F.current=null}else ye()},ye=function(){var t;if("month"===e.view){var n=o.DomHandler.find(C.current,".p-monthpicker .p-monthpicker-month"),a=o.DomHandler.findSingle(C.current,".p-monthpicker .p-monthpicker-month.p-highlight");n.forEach((function(e){return e.tabIndex=-1})),t=a||n[0]}else{if(!(t=o.DomHandler.findSingle(C.current,"span.p-highlight")))t=o.DomHandler.findSingle(C.current,"td.p-datepicker-today span:not(.p-disabled)")||o.DomHandler.findSingle(C.current,".p-datepicker-calendar td span:not(.p-disabled)")}t&&(t.tabIndex="0")},be=function(t){if(e.disabled)t.preventDefault();else{var n=new Date(We().getTime());if(n.setDate(1),"date"===L)0===n.getMonth()?(n.setMonth(11),n.setFullYear(n.getFullYear()-1),Z(11),ke()):(n.setMonth(n.getMonth()-1),Z((function(e){return e-1})));else if("month"===L){var a=n.getFullYear()-1;if(e.yearNavigator){var r=parseInt(e.yearRange.split(":")[0],10);a<r&&(a=r)}n.setFullYear(a)}"month"===L?ke():"year"===L&&ot(),et(t,n),t.preventDefault()}},Me=function(t){if(e.disabled)t.preventDefault();else{var n=new Date(We().getTime());if(n.setDate(1),"date"===L)11===n.getMonth()?(n.setMonth(0),n.setFullYear(n.getFullYear()+1),Z(0),Ee()):(n.setMonth(n.getMonth()+1),Z((function(e){return e+1})));else if("month"===L){var a=n.getFullYear()+1;if(e.yearNavigator){var r=parseInt(e.yearRange.split(":")[1],10);a>r&&(a=r)}n.setFullYear(a)}"month"===L?Ee():"year"===L&&it(),et(t,n),t.preventDefault()}},we=function(e,t){for(var n=e;n<=t;n++)$.push(n);G([])},ke=function(){var t=z-1;if(J(t),e.yearNavigator&&t<$[0]){var n=$[$.length-1]-$[0];we($[0]-n,$[$.length-1]-n)}},Ee=function(){var t=z+1;if(J(t),e.yearNavigator&&t.current>$[$.length-1]){var n=$[$.length-1]-$[0];we($[0]+n,$[$.length-1]+n)}},Se=function(e,t){var n=We(),a=new Date(n.getTime());a.setMonth(parseInt(t,10)),et(e,a)},xe=function(e,t){var n=We(),a=new Date(n.getTime());a.setFullYear(parseInt(t,10)),et(e,a)},Ne=function(t){var n=new Date,a={day:n.getDate(),month:n.getMonth(),year:n.getFullYear(),today:!0,selectable:!0},r={hours:n.getHours(),minutes:n.getMinutes(),seconds:n.getSeconds(),milliseconds:n.getMilliseconds()};et(t,n),at(t,a,r),e.onTodayButtonClick&&e.onTodayButtonClick(t)},He=function(t){dt(t,null),_t(null),ft(),e.onClearButtonClick&&e.onClearButtonClick(t)},Ce=function(t){e.inline||l.OverlayService.emit("overlay-click",{originalEvent:t,target:S.current})},Ie=function(t,n,a){e.disabled||(Te(t,null,n,a),t.preventDefault())},Oe=function(){e.disabled||Ye()},Fe=function(){e.disabled||Ye()},Te=function e(t,n,a,r){switch(Ye(),R.current=setTimeout((function(){e(t,100,a,r)}),n||500),a){case 0:1===r?Re(t):Ae(t);break;case 1:1===r?Be(t):je(t);break;case 2:1===r?Pe(t):Ke(t);break;case 3:1===r?Le(t):qe(t)}},Ye=function(){R.current&&clearTimeout(R.current)},Re=function(t){var n=Ze(),a=n.getHours()+e.stepHour;ze(a=a>=24?a-24:a,n)&&(e.maxDate&&e.maxDate.toDateString()===n.toDateString()&&e.maxDate.getHours()===a&&(e.maxDate.getMinutes()<n.getMinutes()||e.maxDate.getMinutes()===n.getMinutes())?e.maxDate.getSeconds()<n.getSeconds()?e.maxDate.getMilliseconds()<n.getMilliseconds()?Qe(t,a,e.maxDate.getMinutes(),e.maxDate.getSeconds(),e.maxDate.getMilliseconds()):Qe(t,a,e.maxDate.getMinutes(),e.maxDate.getSeconds(),n.getMilliseconds()):Qe(t,a,e.maxDate.getMinutes(),n.getSeconds(),n.getMilliseconds()):Qe(t,a,n.getMinutes(),n.getSeconds(),n.getMilliseconds())),t.preventDefault()},Ae=function(t){var n=Ze(),a=n.getHours()-e.stepHour;ze(a=a<0?a+24:a,n)&&(e.minDate&&e.minDate.toDateString()===n.toDateString()&&e.minDate.getHours()===a&&(e.minDate.getMinutes()>n.getMinutes()||e.minDate.getMinutes()===n.getMinutes())?e.minDate.getSeconds()>n.getSeconds()?e.minDate.getMilliseconds()>n.getMilliseconds()?Qe(t,a,e.minDate.getMinutes(),e.minDate.getSeconds(),e.minDate.getMilliseconds()):Qe(t,a,e.minDate.getMinutes(),e.minDate.getSeconds(),n.getMilliseconds()):Qe(t,a,e.minDate.getMinutes(),n.getSeconds(),n.getMilliseconds()):Qe(t,a,n.getMinutes(),n.getSeconds(),n.getMilliseconds())),t.preventDefault()},Ue=function(t,n){return e.stepMinute<=1?n?t+n:t:n||t%(n=e.stepMinute)!=0?Math.floor((t+n)/n)*n:t},Be=function(t){var n=Ze(),a=n.getMinutes(),r=Ue(a,e.stepMinute);Je(r=r>59?r-60:r,n)&&(e.maxDate&&e.maxDate.toDateString()===n.toDateString()&&e.maxDate.getMinutes()===r&&e.maxDate.getSeconds()<n.getSeconds()?e.maxDate.getMilliseconds()<n.getMilliseconds()?Qe(t,n.getHours(),r,e.maxDate.getSeconds(),e.maxDate.getMilliseconds()):Qe(t,n.getHours(),r,e.maxDate.getSeconds(),n.getMilliseconds()):Qe(t,n.getHours(),r,n.getSeconds(),n.getMilliseconds())),t.preventDefault()},je=function(t){var n=Ze(),a=n.getMinutes(),r=Ue(a,-e.stepMinute);Je(r=r<0?r+60:r,n)&&(e.minDate&&e.minDate.toDateString()===n.toDateString()&&e.minDate.getMinutes()===r&&e.minDate.getSeconds()>n.getSeconds()?e.minDate.getMilliseconds()>n.getMilliseconds()?Qe(t,n.getHours(),r,e.minDate.getSeconds(),e.minDate.getMilliseconds()):Qe(t,n.getHours(),r,e.minDate.getSeconds(),n.getMilliseconds()):Qe(t,n.getHours(),r,n.getSeconds(),n.getMilliseconds())),t.preventDefault()},Pe=function(t){var n=Ze(),a=n.getSeconds()+e.stepSecond;Xe(a=a>59?a-60:a,n)&&(e.maxDate&&e.maxDate.toDateString()===n.toDateString()&&e.maxDate.getSeconds()===a&&e.maxDate.getMilliseconds()<n.getMilliseconds()?Qe(t,n.getHours(),n.getMinutes(),a,e.maxDate.getMilliseconds()):Qe(t,n.getHours(),n.getMinutes(),a,n.getMilliseconds())),t.preventDefault()},Ke=function(t){var n=Ze(),a=n.getSeconds()-e.stepSecond;Xe(a=a<0?a+60:a,n)&&(e.minDate&&e.minDate.toDateString()===n.toDateString()&&e.minDate.getSeconds()===a&&e.minDate.getMilliseconds()>n.getMilliseconds()?Qe(t,n.getHours(),n.getMinutes(),a,e.minDate.getMilliseconds()):Qe(t,n.getHours(),n.getMinutes(),a,n.getMilliseconds())),t.preventDefault()},Le=function(t){var n=Ze(),a=n.getMilliseconds()+e.stepMillisec;$e(a=a>999?a-1e3:a,n)&&Qe(t,n.getHours(),n.getMinutes(),n.getSeconds(),a),t.preventDefault()},qe=function(t){var n=Ze(),a=n.getMilliseconds()-e.stepMillisec;$e(a=a<0?a+999:a,n)&&Qe(t,n.getHours(),n.getMinutes(),n.getSeconds(),a),t.preventDefault()},Ve=function(e){var t=Ze(),n=t.getHours();Qe(e,n>=12?n-12:n+12,t.getMinutes(),t.getSeconds(),t.getMilliseconds()),e.preventDefault()},We=function(t){var n=e.value,a=t||(e.onViewDateChange?e.viewDate:k);return Array.isArray(n)&&(n=n[0]),a&&_e(a)?a:n&&_e(n)?n:new Date},Ze=function(){if(Kt())return e.value&&e.value instanceof Date?e.value:We();if(qt()){if(e.value&&e.value.length)return e.value[e.value.length-1]}else if(Lt()){if(e.value&&e.value.length)return e.value[1]||e.value[0]}return new Date},_e=function(e){return e instanceof Date&&!isNaN(e)},ze=function(t,n){var a=!0,r=n?n.toDateString():null;return e.minDate&&r&&e.minDate.toDateString()===r&&e.minDate.getHours()>t&&(a=!1),e.maxDate&&r&&e.maxDate.toDateString()===r&&e.maxDate.getHours()<t&&(a=!1),a},Je=function(t,n){var a=!0,r=n?n.toDateString():null;return e.minDate&&r&&e.minDate.toDateString()===r&&n.getHours()===e.minDate.getHours()&&e.minDate.getMinutes()>t&&(a=!1),e.maxDate&&r&&e.maxDate.toDateString()===r&&n.getHours()===e.maxDate.getHours()&&e.maxDate.getMinutes()<t&&(a=!1),a},Xe=function(t,n){var a=!0,r=n?n.toDateString():null;return e.minDate&&r&&e.minDate.toDateString()===r&&n.getHours()===e.minDate.getHours()&&n.getMinutes()===e.minDate.getMinutes()&&e.minDate.getSeconds()>t&&(a=!1),e.maxDate&&r&&e.maxDate.toDateString()===r&&n.getHours()===e.maxDate.getHours()&&n.getMinutes()===e.maxDate.getMinutes()&&e.maxDate.getSeconds()<t&&(a=!1),a},$e=function(t,n){var a=!0,r=n?n.toDateString():null;return e.minDate&&r&&e.minDate.toDateString()===r&&n.getHours()===e.minDate.getHours()&&n.getSeconds()===e.minDate.getSeconds()&&n.getMinutes()===e.minDate.getMinutes()&&e.minDate.getMilliseconds()>t&&(a=!1),e.maxDate&&r&&e.maxDate.toDateString()===r&&n.getHours()===e.maxDate.getHours()&&n.getSeconds()===e.maxDate.getSeconds()&&n.getMinutes()===e.maxDate.getMinutes()&&e.maxDate.getMilliseconds()<t&&(a=!1),a},Ge=function(t){if(e.yearNavigator){var n=t.getFullYear(),a=e.yearRange?parseInt(e.yearRange.split(":")[0],10):null,r=e.yearRange?parseInt(e.yearRange.split(":")[1],10):null,l=e.minDate&&null!=a?Math.max(e.minDate.getFullYear(),a):e.minDate||a,o=e.maxDate&&null!=r?Math.min(e.maxDate.getFullYear(),r):e.maxDate||r;l&&l>n&&(n=l),o&&o<n&&(n=o),t.setFullYear(n)}if(e.monthNavigator&&"month"!==e.view){var i=t.getMonth(),u=parseInt(nn(t)&&Math.max(e.minDate.getMonth(),i).toString()||an(t)&&Math.min(e.maxDate.getMonth(),i).toString()||i);t.setMonth(u)}},Qe=function(t,n,a,r,l){var o=Ze();if(o.setHours(n),o.setMinutes(a),o.setSeconds(r),o.setMilliseconds(l),qt())if(e.value&&e.value.length){var i=w(e.value);i[i.length-1]=o,o=i}else o=[o];else if(Lt()){if(e.value&&e.value.length)o=e.value[1]?[e.value[0],o]:[o,null];else o=[o,null]}dt(t,o),e.onSelect&&e.onSelect({originalEvent:t,value:o}),_t(o)},et=function(t,n){Ge(n),e.onViewDateChange?e.onViewDateChange({originalEvent:t,value:n}):(A.current=!0,E(n))},tt=function(e,t,n){var a=e.currentTarget,r=a.parentElement;switch(e.which){case 40:a.tabIndex="-1";var l=o.DomHandler.index(r),i=r.parentElement.nextElementSibling;if(i)o.DomHandler.hasClass(i.children[l].children[0],"p-disabled")?(F.current={backward:!1},Me(e)):(i.children[l].children[0].tabIndex="0",i.children[l].children[0].focus());else F.current={backward:!1},Me(e);e.preventDefault();break;case 38:a.tabIndex="-1";var u=o.DomHandler.index(r),s=r.parentElement.previousElementSibling;if(s){var c=s.children[u].children[0];o.DomHandler.hasClass(c,"p-disabled")?(F.current={backward:!0},be(e)):(c.tabIndex="0",c.focus())}else F.current={backward:!0},be(e);e.preventDefault();break;case 37:a.tabIndex="-1";var m=r.previousElementSibling;if(m){var d=m.children[0];o.DomHandler.hasClass(d,"p-disabled")?nt(!0,n,e):(d.tabIndex="0",d.focus())}else nt(!0,n,e);e.preventDefault();break;case 39:a.tabIndex="-1";var p=r.nextElementSibling;if(p){var f=p.children[0];o.DomHandler.hasClass(f,"p-disabled")?nt(!1,n,e):(f.tabIndex="0",f.focus())}else nt(!1,n,e);e.preventDefault();break;case 13:at(e,t),e.preventDefault();break;case 27:ft(null,me),e.preventDefault();break;case 9:ve(e)}},nt=function(t,n,a){if(t)if(1===e.numberOfMonths||0===n)F.current={backward:!0},be(a);else{var r=o.DomHandler.find(C.current.children[n-1],".p-datepicker-calendar td span:not(.p-disabled)"),l=r[r.length-1];l.tabIndex="0",l.focus()}else if(1===e.numberOfMonths||n===e.numberOfMonths-1)F.current={backward:!1},Me(a);else{var i=o.DomHandler.findSingle(C.current.children[n+1],".p-datepicker-calendar td span:not(.p-disabled)");i.tabIndex="0",i.focus()}},at=function(t,n,a){if(!e.disabled&&n.selectable){if(o.DomHandler.find(C.current,".p-datepicker-calendar td span:not(.p-disabled)").forEach((function(e){return e.tabIndex=-1})),t.currentTarget.focus(),qt())if(Yt(n)){var r=e.value.filter((function(e,t){return!jt(e,n)}));dt(t,r),_t(r)}else(!e.maxDateCount||!e.value||e.maxDateCount>e.value.length)&<(t,n,a);else lt(t,n,a);e.inline||!Kt()||e.showTime&&!e.hideOnDateTimeSelect||(setTimeout((function(){ft("dateselect")}),100),U.current&&vt()),t.preventDefault()}else t.preventDefault()},rt=function(t,n){if(e.showTime){var a,r,l,o;if(n)a=n.hours,r=n.minutes,l=n.seconds,o=n.milliseconds;else{var i=Ze(),u=[i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()];a=u[0],r=u[1],l=u[2],o=u[3]}t.setHours(a),t.setMinutes(r),t.setSeconds(l),t.setMilliseconds(o)}},lt=function(t,n,a){var r=new Date(n.year,n.month,n.day);rt(r,a),e.minDate&&e.minDate>r&&(r=e.minDate),e.maxDate&&e.maxDate<r&&(r=e.maxDate);var l=r;if(Kt())dt(t,r);else if(qt())l=e.value?[].concat(w(e.value),[r]):[r],dt(t,l);else if(Lt())if(e.value&&e.value.length){var o=e.value[0],i=e.value[1];i?(o=r,i=null):r.getTime()>=o.getTime()?i=r:(i=o,o=r),dt(t,l=[o,i])}else dt(t,l=[r,null]);e.onSelect&&e.onSelect({originalEvent:t,value:r}),_t(l)},ot=function(){J((function(e){return e-10}))},it=function(){J((function(e){return e+10}))},ut=function(e){q("month"),e.preventDefault()},st=function(e){q("year"),e.preventDefault()},ct=function(t,n){if("month"===e.view)at(t,{year:z,month:n,day:1,selectable:!0}),t.preventDefault();else{Z(n),Ct(n,z);var a=new Date(Ze().getTime());a.setMonth(n),a.setYear(z),E(a),q("date"),e.onMonthChange&&e.onMonthChange({month:n+1,year:z})}},mt=function(t,n){"year"===e.view?at(t,{year:n,month:0,day:1,selectable:!0}):(J(n),q("month"),e.onMonthChange&&e.onMonthChange({month:W+1,year:n}))},dt=function(t,n){if(e.onChange){var a=n&&n instanceof Date?new Date(n.getTime()):n;A.current=!0,e.onChange({originalEvent:t,value:a,stopPropagation:function(){},preventDefault:function(){},target:{name:e.name,id:e.id,value:a}})}},pt=function(t){e.onVisibleChange?e.onVisibleChange({visible:!0,type:t}):(b(!0),B.current=function(e){yt(e)||(P.current=!0)},l.OverlayService.on("overlay-click",B.current))},ft=function(t,n){var a=function(){A.current=!1,T.current=!1,P.current=!1,n&&n(),l.OverlayService.off("overlay-click",B.current),B.current=null};e.onVisibleChange?e.onVisibleChange({visible:!1,type:t,callback:a}):(b(!1),a())},gt=function(){e.touchUI?ht():C&&C.current&&I&&I.current&&(o.DomHandler.alignOverlay(C.current,I.current,e.appendTo||p.default.appendTo),"self"===e.appendTo||e.inline?o.DomHandler.relativePosition(C.current,I.current):("date"===L?(C.current.style.width=o.DomHandler.getOuterWidth(C.current)+"px",C.current.style.minWidth=o.DomHandler.getOuterWidth(I.current)+"px"):C.current.style.width=o.DomHandler.getOuterWidth(I.current)+"px",o.DomHandler.absolutePosition(C.current,I.current)))},ht=function(){U.current||(U.current=document.createElement("div"),U.current.style.zIndex=String(o.ZIndexUtils.get(C.current)-1),o.DomHandler.addMultipleClasses(U.current,"p-component-overlay p-datepicker-mask p-datepicker-mask-scrollblocker p-component-overlay-enter"),j.current=function(){vt()},U.current.addEventListener("click",j.current),document.body.appendChild(U.current),o.DomHandler.addClass(document.body,"p-overflow-hidden"))},vt=function(){U.current&&(o.DomHandler.addClass(U.current,"p-component-overlay-leave"),U.current.addEventListener("animationend",(function(){Dt()})))},Dt=function(){U.current.removeEventListener("click",j.current),j.current=null,document.body.removeChild(U.current),U.current=null;for(var e,t=document.body.children,n=0;n<t.length;n++){if(o.DomHandler.hasClass(t[n],"p-datepicker-mask-scrollblocker")){e=!0;break}}e||o.DomHandler.removeClass(document.body,"p-overflow-hidden")},yt=function(e){return S.current&&!(S.current.isSameNode(e.target)||bt(e.target)||S.current.contains(e.target)||C.current&&C.current.contains(e.target))},bt=function(e){return o.DomHandler.hasClass(e,"p-datepicker-prev")||o.DomHandler.hasClass(e,"p-datepicker-prev-icon")||o.DomHandler.hasClass(e,"p-datepicker-next")||o.DomHandler.hasClass(e,"p-datepicker-next-icon")},Mt=function(e,t){var n=new Date;n.setDate(1),n.setMonth(e),n.setFullYear(t);var a=n.getDay()+Nt();return a>=7?a-7:a},wt=function(e,t){return 32-Et(new Date(t,e,32)).getDate()},kt=function(e,t){var n=St(e,t);return wt(n.month,n.year)},Et=function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},St=function(e,t){var n,a;return 0===e?(n=11,a=t-1):(n=e-1,a=t),{month:n,year:a}},xt=function(e,t){var n,a;return 11===e?(n=0,a=t+1):(n=e+1,a=t),{month:n,year:a}},Nt=function(){var n=t.localeOption("firstDayOfWeek",e.locale);return n>0?7-n:0},Ht=function(){for(var n=[],a=t.localeOptions(e.locale),r=a.firstDayOfWeek,l=a.dayNamesMin,o=0;o<7;o++)n.push(l[r]),r=6===r?0:++r;return n},Ct=function(t,n){for(var a=[],r=0;r<e.numberOfMonths;r++){var l=t+r,o=n;l>11&&(l=l%11-1,o=n+1),a.push(It(l,o))}return a},It=function(t,n){for(var a=[],r=Mt(t,n),l=wt(t,n),o=kt(t,n),i=1,u=new Date,s=[],c=Math.ceil((l+r)/7),m=0;m<c;m++){var d=[];if(0===m){for(var p=o-r+1;p<=o;p++){var f=St(t,n);d.push({day:p,month:f.month,year:f.year,otherMonth:!0,today:Vt(u,p,f.month,f.year),selectable:Ft(p,f.month,f.year,!0)})}for(var g=7-d.length,h=0;h<g;h++)d.push({day:i,month:t,year:n,today:Vt(u,i,t,n),selectable:Ft(i,t,n,!1)}),i++}else for(var v=0;v<7;v++){if(i>l){var D=xt(t,n);d.push({day:i-l,month:D.month,year:D.year,otherMonth:!0,today:Vt(u,i-l,D.month,D.year),selectable:Ft(i-l,D.month,D.year,!0)})}else d.push({day:i,month:t,year:n,today:Vt(u,i,t,n),selectable:Ft(i,t,n,!1)});i++}e.showWeek&&s.push(Ot(new Date(d[0].year,d[0].month,d[0].day))),a.push(d)}return{month:t,year:n,dates:a,weekNumbers:s}},Ot=function(e){var t=new Date(e.getTime());t.setDate(t.getDate()+4-(t.getDay()||7));var n=t.getTime();return t.setMonth(0),t.setDate(1),Math.floor(Math.round((n-t.getTime())/864e5)/7)+1},Ft=function(t,n,a,r){var l=!0,o=!0,i=!0,u=!0,s=!0;return e.minDate&&(e.minDate.getFullYear()>a||e.minDate.getFullYear()===a&&(e.minDate.getMonth()>n||e.minDate.getMonth()===n&&e.minDate.getDate()>t))&&(l=!1),e.maxDate&&(e.maxDate.getFullYear()<a||e.maxDate.getFullYear()===a&&(e.maxDate.getMonth()<n||e.maxDate.getMonth()===n&&e.maxDate.getDate()<t))&&(o=!1),e.disabledDates&&(i=!Wt(t,n,a)),e.disabledDays&&(u=!Zt(t,n,a)),!1===e.selectOtherMonths&&r&&(s=!1),l&&o&&i&&u&&s},Tt=function(t){var n=!0,a=!0;return e.minDate&&e.minDate.toDateString()===t.toDateString()&&(e.minDate.getHours()>t.getHours()||e.minDate.getHours()===t.getHours()&&(e.minDate.getMinutes()>t.getMinutes()||e.minDate.getMinutes()===t.getMinutes()&&(e.minDate.getSeconds()>t.getSeconds()||e.minDate.getSeconds()===t.getSeconds()&&e.minDate.getMilliseconds()>t.getMilliseconds())))&&(n=!1),e.maxDate&&e.maxDate.toDateString()===t.toDateString()&&(e.maxDate.getHours()<t.getHours()||e.maxDate.getHours()===t.getHours()&&(e.maxDate.getMinutes()<t.getMinutes()||e.maxDate.getMinutes()===t.getMinutes()&&(e.maxDate.getSeconds()<t.getSeconds()||e.maxDate.getSeconds()===t.getSeconds()&&e.maxDate.getMilliseconds()<t.getMilliseconds())))&&(a=!1),n&&a},Yt=function(t){if(!e.value)return!1;if(Kt())return jt(e.value,t);if(qt()){var n,a=!1,r=H(e.value);try{for(r.s();!(n=r.n()).done;){if(a=jt(n.value,t))break}}catch(e){r.e(e)}finally{r.f()}return a}return Lt()?e.value[1]?jt(e.value[0],t)||jt(e.value[1],t)||Pt(e.value[0],e.value[1],t):jt(e.value[0],t):void 0},Rt=function(){return null!=e.value&&"string"!=typeof e.value},At=function(t){if(Rt()){var n=Lt()?e.value[0]:e.value;return!qt()&&(n.getMonth()===t&&n.getFullYear()===z)}return!1},Ut=function(t){if(Rt()){var n=Lt()?e.value[0]:e.value;return!(qt()||!Rt())&&n.getFullYear()===t}return!1},Bt=function(){return e.numberOfMonths>1||e.disabled},jt=function(e,t){return!!(e&&e instanceof Date)&&(e.getDate()===t.day&&e.getMonth()===t.month&&e.getFullYear()===t.year)},Pt=function(e,t,n){if(e&&t){var a=new Date(n.year,n.month,n.day);return e.getTime()<=a.getTime()&&t.getTime()>=a.getTime()}return!1},Kt=function(){return"single"===e.selectionMode},Lt=function(){return"range"===e.selectionMode},qt=function(){return"multiple"===e.selectionMode},Vt=function(e,t,n,a){return e.getDate()===t&&e.getMonth()===n&&e.getFullYear()===a},Wt=function(t,n,a){return!!e.disabledDates&&e.disabledDates.some((function(e){return e.getFullYear()===a&&e.getMonth()===n&&e.getDate()===t}))},Zt=function(t,n,a){if(e.disabledDays){var r=new Date(a,n,t).getDay();return-1!==e.disabledDays.indexOf(r)}return!1},_t=function(e){if(I.current){var t="";if(e)try{if(Kt())t=_e(e)?zt(e):"";else if(qt())for(var n=0;n<e.length;n++){var a=e[n];t+=_e(a)?zt(a):"",n!==e.length-1&&(t+=", ")}else if(Lt()&&e&&e.length){var r=e[0],l=e[1];t=_e(r)?zt(r):"",l&&(t+=_e(l)?" - "+zt(l):"")}}catch(n){t=e}I.current.value=t}},zt=function(t){var n=null;return t&&(e.timeOnly?n=Xt(t):(n=Jt(t,le()),e.showTime&&(n+=" "+Xt(t)))),n},Jt=function(n,a){if(!n)return"";var r,l=function(e){var t=r+1<a.length&&a.charAt(r+1)===e;return t&&r++,t},o=function(e,t,n){var a=""+t;if(l(e))for(;a.length<n;)a="0"+a;return a},i=function(e,t,n,a){return l(e)?a[t]:n[t]},u="",s=!1,c=t.localeOptions(e.locale),m=c.dayNamesShort,d=c.dayNames,p=c.monthNamesShort,f=c.monthNames;if(n)for(r=0;r<a.length;r++)if(s)"'"!==a.charAt(r)||l("'")?u+=a.charAt(r):s=!1;else switch(a.charAt(r)){case"d":u+=o("d",n.getDate(),2);break;case"D":u+=i("D",n.getDay(),m,d);break;case"o":u+=o("o",Math.round((new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()-new Date(n.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=o("m",n.getMonth()+1,2);break;case"M":u+=i("M",n.getMonth(),p,f);break;case"y":u+=l("y")?n.getFullYear():(n.getFullYear()%100<10?"0":"")+n.getFullYear()%100;break;case"@":u+=n.getTime();break;case"!":u+=1e4*n.getTime()+ticksTo1970;break;case"'":l("'")?u+="'":s=!0;break;default:u+=a.charAt(r)}return u},Xt=function(t){if(!t)return"";var n="",a=t.getHours(),r=t.getMinutes(),l=t.getSeconds(),o=t.getMilliseconds();return"12"===e.hourFormat&&a>11&&12!==a&&(a-=12),n+="12"===e.hourFormat&&0===a?12:a<10?"0"+a:a,n+=":",n+=r<10?"0"+r:r,e.showSeconds&&(n+=":",n+=l<10?"0"+l:l),e.showMillisec&&(n+=".",n+=o<100?(o<10?"00":"0")+o:o),"12"===e.hourFormat&&(n+=t.getHours()>11?" PM":" AM"),n},$t=function(e){if(!e||0===e.trim().length)return null;var t;if(Kt())t=Gt(e);else if(qt()){t=[];var n,a=H(e.split(","));try{for(a.s();!(n=a.n()).done;){t.push(Gt(n.value.trim()))}}catch(e){a.e(e)}finally{a.f()}}else if(Lt()){var r=e.split(" - ");t=[];for(var l=0;l<r.length;l++)t[l]=Gt(r[l].trim())}return t},Gt=function(t){var n,a=t.split(" ");return e.timeOnly?(n=new Date,Qt(n,a[0],a[1])):e.showTime?(n=tn(a[0],le()),Qt(n,a[1],a[2])):n=tn(t,le()),n},Qt=function(t,n,a){if("12"===e.hourFormat&&"PM"!==a&&"AM"!==a)throw new Error("Invalid Time");var r=en(n,a);t.setHours(r.hour),t.setMinutes(r.minute),t.setSeconds(r.second),t.setMilliseconds(r.millisecond)},en=function(t,n){var a=(t=e.showMillisec?t.replace(".",":"):t).split(":"),r=e.showSeconds?3:2;if(a.length!==(r=e.showMillisec?r+1:r)||2!==a[0].length||2!==a[1].length||e.showSeconds&&2!==a[2].length||e.showMillisec&&3!==a[3].length)throw new Error("Invalid time");var l=parseInt(a[0],10),o=parseInt(a[1],10),i=e.showSeconds?parseInt(a[2],10):null,u=e.showMillisec?parseInt(a[3],10):null;if(isNaN(l)||isNaN(o)||l>23||o>59||"12"===e.hourFormat&&l>12||e.showSeconds&&(isNaN(i)||i>59)||e.showMillisec&&(isNaN(i)||i>1e3))throw new Error("Invalid time");return"12"===e.hourFormat&&12!==l&&"PM"===n&&(l+=12),{hour:l,minute:o,second:i,millisecond:u}},tn=function(n,a){if(null==a||null==n)throw new Error("Invalid arguments");if(""===(n="object"===h(n)?n.toString():n+""))return null;var r,l,o,i,u=0,s="string"!=typeof e.shortYearCutoff?e.shortYearCutoff:(new Date).getFullYear()%100+parseInt(e.shortYearCutoff,10),c=-1,m=-1,d=-1,p=-1,f=!1,g=function(e){var t=r+1<a.length&&a.charAt(r+1)===e;return t&&r++,t},v=function(e){var t=g(e),a="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,r=new RegExp("^\\d{"+("y"===e?a:1)+","+a+"}"),l=n.substring(u).match(r);if(!l)throw new Error("Missing number at position "+u);return u+=l[0].length,parseInt(l[0],10)},D=function(e,t,a){for(var r=-1,l=g(e)?a:t,o=[],i=0;i<l.length;i++)o.push([i,l[i]]);o.sort((function(e,t){return-(e[1].length-t[1].length)}));for(var s=0;s<o.length;s++){var c=o[s][1];if(n.substr(u,c.length).toLowerCase()===c.toLowerCase()){r=o[s][0],u+=c.length;break}}if(-1!==r)return r+1;throw new Error("Unknown name at position "+u)},y=function(){if(n.charAt(u)!==a.charAt(r))throw new Error("Unexpected literal at position "+u);u++};"month"===e.view&&(d=1);var b=t.localeOptions(e.locale),M=b.dayNamesShort,w=b.dayNames,k=b.monthNamesShort,E=b.monthNames;for(r=0;r<a.length;r++)if(f)"'"!==a.charAt(r)||g("'")?y():f=!1;else switch(a.charAt(r)){case"d":d=v("d");break;case"D":D("D",M,w);break;case"o":p=v("o");break;case"m":m=v("m");break;case"M":m=D("M",k,E);break;case"y":c=v("y");break;case"@":c=(i=new Date(v("@"))).getFullYear(),m=i.getMonth()+1,d=i.getDate();break;case"!":c=(i=new Date((v("!")-ticksTo1970)/1e4)).getFullYear(),m=i.getMonth()+1,d=i.getDate();break;case"'":g("'")?y():f=!0;break;default:y()}if(u<n.length&&(o=n.substr(u),!/^\s+/.test(o)))throw new Error("Extra/unparsed characters found in date: "+o);if(-1===c?c=(new Date).getFullYear():c<100&&(c+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c<=s?0:-100)),p>-1)for(m=1,d=p;;){if(d<=(l=wt(c,m-1)))break;m++,d-=l}if((i=Et(new Date(c,m-1,d))).getFullYear()!==c||i.getMonth()+1!==m||i.getDate()!==d)throw new Error("Invalid date");return i},nn=function(t){return e.minDate&&e.minDate.getFullYear()===t.getFullYear()},an=function(t){return e.maxDate&&e.maxDate.getFullYear()===t.getFullYear()};d.useEffect((function(){o.ObjectUtils.combinedRefs(I,e.inputRef)}),[I,e.inputRef]),a.useMountEffect((function(){var t=We(e.viewDate);Ge(t),E(t),Z(t.getMonth()),J(t.getFullYear()),q(e.view),e.inline?(C&&C.current.setAttribute(te,""),e.disabled||(ye(),1===e.numberOfMonths&&(C.current.style.width=o.DomHandler.getOuterWidth(C.current)+"px"))):e.mask&&o.mask(I.current,{mask:e.mask,readOnly:e.readOnlyInput||e.disabled,onChange:function(e){return ce(e.originalEvent,e.value)}}),e.value&&_t(e.value)})),a.useUpdateEffect((function(){if(!e.onViewDateChange&&!A.current){var t=e.value;Array.isArray(t)&&(t=t[0]);var n=Q;if(Array.isArray(n)&&(n=n[0]),!n&&t||t&&t instanceof Date&&t.getTime()!==n.getTime()){var a=e.viewDate&&_e(e.viewDate)?e.viewDate:t&&_e(t)?t:new Date;Ge(a),E(a),A.current=!0}}}),[e.onViewDateChange,e.value]),a.useUpdateEffect((function(){Q===e.value||A&&ee||_t(e.value)}),[e.value,ee]),a.useUpdateEffect((function(){_t(e.value)}),[e.dateFormat,e.hourFormat,e.timeOnly,e.showSeconds,e.showMillisec]),a.useUpdateEffect((function(){C.current&&De()})),a.useUnmountEffect((function(){U.current&&(vt(),U.current=null),o.ZIndexUtils.clear(C.current)})),d.useImperativeHandle(u,(function(){return{show:pt,hide:ft,getCurrentDateTime:Ze,getViewDate:We,updateViewDate:et}}));var rn,ln,on,un,sn,cn,mn,dn,pn=function(e){return d.createElement("button",g({type:"button",className:"p-datepicker-prev"},e?{onClick:fe,onKeyDown:function(e){return he(e)}}:{style:{visibility:"hidden"}}),d.createElement("span",{className:"p-datepicker-prev-icon pi pi-chevron-left"}),d.createElement(i.Ripple,null))},fn=function(e){return d.createElement("button",g({type:"button",className:"p-datepicker-next"},e?{onClick:ge,onKeyDown:function(e){return he(e)}}:{style:{visibility:"hidden"}}),d.createElement("span",{className:"p-datepicker-next-icon pi pi-chevron-right"}),d.createElement(i.Ripple,null))},gn=function(n){var a=t.localeOption("monthNames",e.locale);if(e.monthNavigator&&"month"!==e.view){var r=We(),l=r.getMonth(),i=a.map((function(t,n){return(!nn(r)||n>=e.minDate.getMonth())&&(!an(r)||n<=e.maxDate.getMonth())?{label:t,value:n,index:n}:null})).filter((function(e){return!!e})),u=i.map((function(e){return e.label})),s=d.createElement("select",{className:"p-datepicker-month",onChange:function(e){return Se(e,e.target.value)},value:l},i.map((function(e){return d.createElement("option",{key:e.label,value:e.value},e.label)})));return e.monthNavigatorTemplate?o.ObjectUtils.getJSXElement(e.monthNavigatorTemplate,{onChange:Se,className:"p-datepicker-month",value:l,names:u,options:i,element:s,props:e}):s}return"date"===L&&d.createElement("button",{className:"p-datepicker-month p-link",onClick:ut,disabled:Bt()},a[n])},hn=function(){if(e.yearNavigator){for(var t=[],n=e.yearRange.split(":"),a=parseInt(n[0],10),r=parseInt(n[1],10),l=a;l<=r;l++)t.push(l);var i=We().getFullYear(),u=t.filter((function(t){return!(e.minDate&&e.minDate.getFullYear()>t||e.maxDate&&e.maxDate.getFullYear()<t)})),s=d.createElement("select",{className:"p-datepicker-year",onChange:function(e){return xe(e,e.target.value)},value:i},u.map((function(e){return d.createElement("option",{key:e,value:e},e)})));if(e.yearNavigatorTemplate){var c=u.map((function(e,t){return{label:e,value:e,index:t}}));return o.ObjectUtils.getJSXElement(e.yearNavigatorTemplate,{onChange:xe,className:"p-datepicker-year",value:i,names:u,options:c,element:s,props:e})}return s}return"year"!==L&&d.createElement("button",{className:"p-datepicker-year p-link",onClick:st,disabled:Bt()},z)},vn=function(){var t=Nn();return"year"===L?d.createElement("span",{className:"p-datepicker-decade"},e.decadeTemplate?e.decadeTemplate(t):d.createElement("span",null,"".concat(Nn()[0]," - ").concat(Nn()[Nn().length-1]))):null},Dn=function(e){var t=gn(e.month),n=hn(),a=vn();return d.createElement("div",{className:"p-datepicker-title"},t,n,a)},yn=function(n){var a=n.map((function(e,t){return d.createElement("th",{key:"".concat(e,"-").concat(t),scope:"col"},d.createElement("span",null,e))}));return e.showWeek?[d.createElement("th",{scope:"col",key:"wn",className:"p-datepicker-weekheader p-disabled"},d.createElement("span",null,t.localeOption("weekHeader",e.locale)))].concat(w(a)):a},bn=function(t,n,a){var r=e.dateTemplate?e.dateTemplate(t):t.day;return d.createElement("span",{className:n,onClick:function(e){return at(e,t)},onKeyDown:function(e){return tt(e,t,a)}},r,d.createElement(i.Ripple,null))},Mn=function(t,n,a){var r=t.map((function(t){var n=Yt(t),r=o.classNames({"p-datepicker-other-month":t.otherMonth,"p-datepicker-today":t.today}),l=o.classNames({"p-highlight":n,"p-disabled":!t.selectable}),i=t.otherMonth&&!e.showOtherMonths?null:bn(t,l,a);return d.createElement("td",{key:t.day,className:r},i)}));return e.showWeek?[d.createElement("td",{key:"wn"+n,className:"p-datepicker-weeknumber"},d.createElement("span",{className:"p-disabled"},n))].concat(w(r)):r},wn=function(e,t){return e.dates.map((function(n,a){return d.createElement("tr",{key:a},Mn(n,e.weekNumbers[a],t))}))},kn=function(e,t,n){var a=yn(t),r=wn(e,n);return"date"===L&&d.createElement("div",{className:"p-datepicker-calendar-container"},d.createElement("table",{className:"p-datepicker-calendar"},d.createElement("thead",null,d.createElement("tr",null,a)),d.createElement("tbody",null,r)))},En=function(t,n){var a=Ht(),r=pn(0===n),l=fn(1===e.numberOfMonths||n===e.numberOfMonths-1),o=Dn(t),i=kn(t,a,n),u=e.headerTemplate?e.headerTemplate():null;return d.createElement("div",{key:t.month,className:"p-datepicker-group"},d.createElement("div",{className:"p-datepicker-header"},u,r,o,l),i)},Sn=function(e){var t=e.map(En);return d.createElement("div",{className:"p-datepicker-group-container"},t)},xn=function(){for(var n=[],a=t.localeOption("monthNamesShort",e.locale),r=0;r<=11;r++)n.push(a[r]);return n},Nn=function(){for(var e=[],t=z-z%10,n=0;n<10;n++)e.push(t+n);return e},Hn=function(){var t=Ze().getHours();"12"===e.hourFormat&&(0===t?t=12:t>11&&12!==t&&(t-=12));var n=t<10?"0"+t:t;return d.createElement("div",{className:"p-hour-picker"},d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,0,1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-up"}),d.createElement(i.Ripple,null)),d.createElement("span",null,n),d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,0,-1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-down"}),d.createElement(i.Ripple,null)))},Cn=function(){if(e.showSeconds){var t=Ze().getSeconds(),n=t<10?"0"+t:t;return d.createElement("div",{className:"p-second-picker"},d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,2,1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-up"}),d.createElement(i.Ripple,null)),d.createElement("span",null,n),d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,2,-1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-down"}),d.createElement(i.Ripple,null)))}return null},In=function(){if(e.showMillisec){var t=Ze().getMilliseconds(),n=t<100?(t<10?"00":"0")+t:t;return d.createElement("div",{className:"p-millisecond-picker"},d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,3,1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-up"}),d.createElement(i.Ripple,null)),d.createElement("span",null,n),d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,3,-1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-down"}),d.createElement(i.Ripple,null)))}return null},On=function(){if("12"===e.hourFormat){var t=Ze().getHours()>11?"PM":"AM";return d.createElement("div",{className:"p-ampm-picker"},d.createElement("button",{type:"button",className:"p-link",onClick:Ve},d.createElement("span",{className:"pi pi-chevron-up"}),d.createElement(i.Ripple,null)),d.createElement("span",null,t),d.createElement("button",{type:"button",className:"p-link",onClick:Ve},d.createElement("span",{className:"pi pi-chevron-down"}),d.createElement(i.Ripple,null)))}return null},Fn=function(e){return d.createElement("div",{className:"p-separator"},d.createElement("span",null,e))},Tn=function(){return e.showIcon?d.createElement(n.Button,{type:"button",icon:e.icon,onClick:pe,tabIndex:"-1",disabled:e.disabled,className:"p-datepicker-trigger"}):null},Yn=o.ObjectUtils.findDiffKeys(e,O.defaultProps),Rn=o.classNames("p-calendar p-component p-inputwrapper",e.className,(f(s={},"p-calendar-w-btn p-calendar-w-btn-".concat(e.iconPos),e.showIcon),f(s,"p-calendar-disabled",e.disabled),f(s,"p-calendar-timeonly",e.timeOnly),f(s,"p-inputwrapper-filled",e.value||o.DomHandler.hasClass(I.current,"p-filled")&&""!==I.current.value),f(s,"p-inputwrapper-focus",m),s)),An=o.classNames("p-datepicker p-component",e.panelClassName,{"p-datepicker-inline":e.inline,"p-disabled":e.disabled,"p-datepicker-timeonly":e.timeOnly,"p-datepicker-multiple-month":e.numberOfMonths>1,"p-datepicker-monthpicker":"month"===L,"p-datepicker-touch-ui":e.touchUI}),Un=function(){var t=e.inline?null:d.createElement(r.InputText,{ref:I,id:e.inputId,name:e.name,type:"text",className:e.inputClassName,style:e.inputStyle,readOnly:e.readOnlyInput,disabled:e.disabled,required:e.required,autoComplete:"off",placeholder:e.placeholder,tabIndex:e.tabIndex,onInput:se,onFocus:oe,onBlur:ie,onKeyDown:ue,"aria-labelledby":e.ariaLabelledBy,inputMode:e.inputMode,tooltip:e.tooltip,tooltipOptions:e.tooltipOptions}),n=Tn();return"left"===e.iconPos?d.createElement(d.Fragment,null,n,t):d.createElement(d.Fragment,null,t,n)}(),Bn=e.timeOnly?null:"date"===e.view?(sn=We(),cn=Ct(sn.getMonth(),sn.getFullYear()),Sn(cn)):(rn=pn(!0),ln=fn(!0),on=hn(We().getFullYear()),un=vn(),d.createElement(d.Fragment,null,d.createElement("div",{className:"p-datepicker-group-container"},d.createElement("div",{className:"p-datepicker-group"},d.createElement("div",{className:"p-datepicker-header"},rn,d.createElement("div",{className:"p-datepicker-title"},on,un),ln))))),jn=(e.showTime||e.timeOnly)&&"date"===L?d.createElement("div",{className:"p-timepicker"},Hn(),Fn(":"),(mn=Ze().getMinutes(),dn=mn<10?"0"+mn:mn,d.createElement("div",{className:"p-minute-picker"},d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,1,1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-up"}),d.createElement(i.Ripple,null)),d.createElement("span",null,dn),d.createElement("button",{type:"button",className:"p-link",onMouseDown:function(e){return Ie(e,1,-1)},onMouseUp:Oe,onMouseLeave:Fe,onKeyDown:function(e){return he(e)}},d.createElement("span",{className:"pi pi-chevron-down"}),d.createElement(i.Ripple,null)))),e.showSeconds&&Fn(":"),Cn(),e.showMillisec&&Fn("."),In(),"12"===e.hourFormat&&Fn(":"),On()):null,Pn=function(){if(e.showButtonBar){var a=o.classNames("p-button-text",e.todayButtonClassName),r=o.classNames("p-button-text",e.clearButtonClassName),l=t.localeOptions(e.locale),i=l.clear;return d.createElement("div",{className:"p-datepicker-buttonbar"},d.createElement(n.Button,{type:"button",label:l.today,onClick:Ne,onKeyDown:function(e){return he(e)},className:a}),d.createElement(n.Button,{type:"button",label:i,onClick:He,onKeyDown:function(e){return he(e)},className:r}))}return null}(),Kn=function(){if(e.footerTemplate){var t=e.footerTemplate();return d.createElement("div",{className:"p-datepicker-footer"},t)}return null}(),Ln="month"===L?d.createElement("div",{className:"p-monthpicker"},xn().map((function(e,t){return d.createElement("span",{onClick:function(e){return ct(e,t)},key:"month".concat(t+1),className:o.classNames("p-monthpicker-month",{"p-highlight":At(t)})},e)}))):null,qn="year"===L?d.createElement("div",{className:"p-yearpicker"},Nn().map((function(e,t){return d.createElement("span",{onClick:function(t){return mt(t,e)},key:"year".concat(t+1),className:o.classNames("p-yearpicker-year",{"p-highlight":Ut(e)})},e)}))):null;return d.createElement("span",g({ref:S,id:e.id,className:Rn,style:e.style},Yn),Un,d.createElement(N,{ref:C,className:An,style:e.panelStyle,appendTo:e.appendTo,inline:e.inline,onClick:Ce,onMouseUp:function(e){Ce(e)},in:ee,onEnter:function(){if(e.autoZIndex){var t=e.touchUI?"modal":"overlay";o.ZIndexUtils.set(t,C.current,p.default.autoZIndex,e.baseZIndex||p.default.zIndex[t])}gt()},onEntered:function(){ae(),e.onShow&&e.onShow()},onExit:function(){re()},onExited:function(){o.ZIndexUtils.clear(C.current),e.onHide&&e.onHide()},transitionOptions:e.transitionOptions},Bn,jn,Pn,Kn,Ln,qn))})));O.displayName="Calendar",O.defaultProps={__TYPE:"Calendar",id:null,inputRef:null,name:null,value:null,visible:!1,viewDate:null,style:null,className:null,inline:!1,selectionMode:"single",inputId:null,inputStyle:null,inputClassName:null,inputMode:"none",required:!1,readOnlyInput:!1,keepInvalid:!1,mask:null,disabled:!1,tabIndex:null,placeholder:null,showIcon:!1,icon:"pi pi-calendar",iconPos:"right",showOnFocus:!0,numberOfMonths:1,view:"date",touchUI:!1,showTime:!1,timeOnly:!1,showSeconds:!1,showMillisec:!1,hourFormat:"24",stepHour:1,stepMinute:1,stepSecond:1,stepMillisec:1,shortYearCutoff:"+10",hideOnDateTimeSelect:!1,showWeek:!1,locale:null,dateFormat:null,panelStyle:null,panelClassName:null,monthNavigator:!1,yearNavigator:!1,yearRange:null,disabledDates:null,disabledDays:null,minDate:null,maxDate:null,maxDateCount:null,showOtherMonths:!0,selectOtherMonths:!1,showButtonBar:!1,todayButtonClassName:"p-button-secondary",clearButtonClassName:"p-button-secondary",autoZIndex:!0,baseZIndex:0,appendTo:null,tooltip:null,tooltipOptions:null,ariaLabelledBy:null,dateTemplate:null,decadeTemplate:null,headerTemplate:null,footerTemplate:null,monthNavigatorTemplate:null,yearNavigatorTemplate:null,transitionOptions:null,onVisibleChange:null,onFocus:null,onBlur:null,onInput:null,onSelect:null,onChange:null,onViewDateChange:null,onTodayButtonClick:null,onClearButtonClick:null,onShow:null,onHide:null,onMonthChange:null},exports.Calendar=O;
|
docs/src/examples/elements/Segment/Variations/SegmentExampleAttachedComplex.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Header, Icon, Message, Segment } from 'semantic-ui-react'
const SegmentExampleAttachedComplex = () => (
<div>
<Header as='h5' attached='top'>
Dogs
</Header>
<Segment attached>Dogs are one type of animal.</Segment>
<Header as='h5' attached>
Cats
</Header>
<Segment attached>
Cats are thought of as being related to dogs, but only humans think this.
</Segment>
<Header as='h5' attached>
Lions
</Header>
<Segment attached>
Humans don't think of lions as being like cats, but they are.
</Segment>
<Message warning attached='bottom'>
<Icon name='warning' />
You've reached the end of this content segment!
</Message>
</div>
)
export default SegmentExampleAttachedComplex
|
ajax/libs/recompose/0.20.1/Recompose.js | keicheng/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Recompose"] = factory(require("react"));
else
root["Recompose"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(29);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var createHelper = function createHelper(func, helperName) {
var setDisplayName = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
var noArgs = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
if (false) {
var _ret = function () {
/* eslint-disable global-require */
var wrapDisplayName = require('./wrapDisplayName').default;
/* eslint-enable global-require */
if (noArgs) {
return {
v: function v(BaseComponent) {
var Component = func(BaseComponent);
Component.displayName = wrapDisplayName(BaseComponent, helperName);
return Component;
}
};
}
return {
v: function v() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length > func.length) {
/* eslint-disable */
console.error(
/* eslint-enable */
'Too many arguments passed to ' + helperName + '(). It should called ' + ('like so: ' + helperName + '(...args)(BaseComponent).'));
}
return function (BaseComponent) {
var Component = func.apply(undefined, args)(BaseComponent);
Component.displayName = wrapDisplayName(BaseComponent, helperName);
return Component;
};
}
};
}();
if (typeof _ret === "object") return _ret.v;
}
return func;
};
exports.default = createHelper;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerElementUtil = __webpack_require__(18);
var _createEagerElementUtil2 = _interopRequireDefault(_createEagerElementUtil);
var _isReferentiallyTransparentFunctionComponent = __webpack_require__(16);
var _isReferentiallyTransparentFunctionComponent2 = _interopRequireDefault(_isReferentiallyTransparentFunctionComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createFactory = function createFactory(type) {
var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(type);
return function (p, c) {
return (0, _createEagerElementUtil2.default)(false, isReferentiallyTransparent, type, p, c);
};
};
exports.default = createFactory;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mapProps = function mapProps(propsMapper) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (props) {
return factory(propsMapper(props));
};
};
};
exports.default = (0, _createHelper2.default)(mapProps, 'mapProps');
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var _config = {
fromESObservable: null,
toESObservable: null
};
var configureObservable = function configureObservable(c) {
_config = c;
};
var config = exports.config = {
fromESObservable: function fromESObservable(observable) {
return typeof _config.fromESObservable === 'function' ? _config.fromESObservable(observable) : observable;
},
toESObservable: function toESObservable(stream) {
return typeof _config.toESObservable === 'function' ? _config.toESObservable(stream) : stream;
}
};
exports.default = configureObservable;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shallowEqual = __webpack_require__(49);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _shallowEqual2.default;
/***/ },
/* 7 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var getDisplayName = function getDisplayName(Component) {
if (typeof Component === 'string') {
return Component;
}
if (!Component) {
return undefined;
}
return Component.displayName || Component.name || 'Component';
};
exports.default = getDisplayName;
/***/ },
/* 8 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var isClassComponent = function isClassComponent(Component) {
return Boolean(Component && Component.prototype && typeof Component.prototype.isReactComponent === 'object');
};
exports.default = isClassComponent;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setStatic = function setStatic(key, value) {
return function (BaseComponent) {
/* eslint-disable no-param-reassign */
BaseComponent[key] = value;
/* eslint-enable no-param-reassign */
return BaseComponent;
};
};
exports.default = (0, _createHelper2.default)(setStatic, 'setStatic', false);
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var shouldUpdate = function shouldUpdate(test) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class, _Component);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
_class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return test(this.props, nextProps);
};
_class.prototype.render = function render() {
return factory(this.props);
};
return _class;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(shouldUpdate, 'shouldUpdate');
/***/ },
/* 11 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var omit = function omit(obj, keys) {
var rest = _objectWithoutProperties(obj, []);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (rest.hasOwnProperty(key)) {
delete rest[key];
}
}
return rest;
};
exports.default = omit;
/***/ },
/* 12 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var pick = function pick(obj, keys) {
var result = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj.hasOwnProperty(key)) {
result[key] = obj[key];
}
}
return result;
};
exports.default = pick;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/* global window */
'use strict';
module.exports = __webpack_require__(51)(global || window || this);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.componentFromStreamWithConfig = undefined;
var _react = __webpack_require__(3);
var _changeEmitter = __webpack_require__(19);
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var componentFromStreamWithConfig = exports.componentFromStreamWithConfig = function componentFromStreamWithConfig(config) {
return function (propsToVdom) {
return function (_Component) {
_inherits(ComponentFromStream, _Component);
function ComponentFromStream() {
var _config$fromESObserva;
var _temp, _this, _ret;
_classCallCheck(this, ComponentFromStream);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { vdom: null }, _this.propsEmitter = (0, _changeEmitter.createChangeEmitter)(), _this.props$ = config.fromESObservable((_config$fromESObserva = {
subscribe: function subscribe(observer) {
var unsubscribe = _this.propsEmitter.listen(function (props) {
return observer.next(props);
});
return { unsubscribe: unsubscribe };
}
}, _config$fromESObserva[_symbolObservable2.default] = function () {
return this;
}, _config$fromESObserva)), _this.vdom$ = config.toESObservable(propsToVdom(_this.props$)), _temp), _possibleConstructorReturn(_this, _ret);
}
// Stream of props
// Stream of vdom
ComponentFromStream.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// Subscribe to child prop changes so we know when to re-render
this.subscription = this.vdom$.subscribe({
next: function next(vdom) {
_this2.setState({ vdom: vdom });
}
});
this.propsEmitter.emit(this.props);
};
ComponentFromStream.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
// Receive new props from the owner
this.propsEmitter.emit(nextProps);
};
ComponentFromStream.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
return nextState.vdom !== this.state.vdom;
};
ComponentFromStream.prototype.componentWillUnmount = function componentWillUnmount() {
// Clean-up subscription before un-mounting
this.subscription.unsubscribe();
};
ComponentFromStream.prototype.render = function render() {
return this.state.vdom;
};
return ComponentFromStream;
}(_react.Component);
};
};
var componentFromStream = componentFromStreamWithConfig(_setObservableConfig.config);
exports.default = componentFromStream;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerElementUtil = __webpack_require__(18);
var _createEagerElementUtil2 = _interopRequireDefault(_createEagerElementUtil);
var _isReferentiallyTransparentFunctionComponent = __webpack_require__(16);
var _isReferentiallyTransparentFunctionComponent2 = _interopRequireDefault(_isReferentiallyTransparentFunctionComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEagerElement = function createEagerElement(type, props, children) {
var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(type);
/* eslint-disable */
var hasKey = props && props.hasOwnProperty('key');
/* eslint-enable */
return (0, _createEagerElementUtil2.default)(hasKey, isReferentiallyTransparent, type, props, children);
};
exports.default = createEagerElement;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isClassComponent = __webpack_require__(8);
var _isClassComponent2 = _interopRequireDefault(_isClassComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component) {
return Boolean(typeof Component === 'function' && !(0, _isClassComponent2.default)(Component) && !Component.defaultProps && !Component.contextTypes && !Component.propTypes);
};
exports.default = isReferentiallyTransparentFunctionComponent;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shouldUpdate = __webpack_require__(10);
var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) {
return (0, _shouldUpdate2.default)(function (props, nextProps) {
return !(0, _shallowEqual2.default)((0, _pick2.default)(nextProps, propKeys), (0, _pick2.default)(props, propKeys));
});
};
exports.default = (0, _createHelper2.default)(onlyUpdateForKeys, 'onlyUpdateForKeys');
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEagerElementUtil = function createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children) {
if (!hasKey && isReferentiallyTransparent) {
if (children) {
return type(_extends({}, props, { children: children }));
}
return type(props);
}
var Component = type;
if (children) {
return _react2.default.createElement(
Component,
props,
children
);
}
return _react2.default.createElement(Component, props);
};
exports.default = createEagerElementUtil;
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var createChangeEmitter = exports.createChangeEmitter = function createChangeEmitter() {
var currentListeners = [];
var nextListeners = currentListeners;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
function listen(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function () {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
function emit() {
currentListeners = nextListeners;
var listeners = currentListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i].apply(listeners, arguments);
}
}
return {
listen: listen,
emit: emit
};
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var branch = function branch(test, left, right) {
return function (BaseComponent) {
return function (_React$Component) {
_inherits(_class2, _React$Component);
function _class2(props, context) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.LeftComponent = null;
_this.RightComponent = null;
_this.computeChildComponent(_this.props);
return _this;
}
_class2.prototype.computeChildComponent = function computeChildComponent(props) {
if (test(props)) {
this.leftFactory = this.leftFactory || (0, _createEagerFactory2.default)(left(BaseComponent));
this.factory = this.leftFactory;
} else {
this.rightFactory = this.rightFactory || (0, _createEagerFactory2.default)(right(BaseComponent));
this.factory = this.rightFactory;
}
};
_class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.computeChildComponent(nextProps);
};
_class2.prototype.render = function render() {
return this.factory(this.props);
};
return _class2;
}(_react2.default.Component);
};
};
exports.default = (0, _createHelper2.default)(branch, 'branch');
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _createEagerElement = __webpack_require__(15);
var _createEagerElement2 = _interopRequireDefault(_createEagerElement);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var componentFromProp = function componentFromProp(propName) {
var Component = function Component(props) {
return (0, _createEagerElement2.default)(props[propName], (0, _omit2.default)(props, [propName]));
};
Component.displayName = 'componentFromProp(' + propName + ')';
return Component;
};
exports.default = componentFromProp;
/***/ },
/* 22 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = compose;
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
var last = funcs[funcs.length - 1];
return function () {
var result = last.apply(undefined, arguments);
for (var i = funcs.length - 2; i >= 0; i--) {
var f = funcs[i];
result = f(result);
}
return result;
};
}
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.createEventHandlerWithConfig = undefined;
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _changeEmitter = __webpack_require__(19);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEventHandlerWithConfig = exports.createEventHandlerWithConfig = function createEventHandlerWithConfig(config) {
return function () {
var _config$fromESObserva;
var emitter = (0, _changeEmitter.createChangeEmitter)();
var stream = config.fromESObservable((_config$fromESObserva = {
subscribe: function subscribe(observer) {
var unsubscribe = emitter.listen(function (value) {
return observer.next(value);
});
return { unsubscribe: unsubscribe };
}
}, _config$fromESObserva[_symbolObservable2.default] = function () {
return this;
}, _config$fromESObserva));
return {
handler: emitter.emit,
stream: stream
};
};
};
var createEventHandler = createEventHandlerWithConfig(_setObservableConfig.config);
exports.default = createEventHandler;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var createSink = function createSink(callback) {
return function (_Component) {
_inherits(Sink, _Component);
function Sink() {
_classCallCheck(this, Sink);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Sink.prototype.componentWillMount = function componentWillMount() {
callback(this.props);
};
Sink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
callback(nextProps);
};
Sink.prototype.render = function render() {
return null;
};
return Sink;
}(_react.Component);
};
exports.default = createSink;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultProps = function defaultProps(props) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var DefaultProps = function DefaultProps(ownerProps) {
return factory(ownerProps);
};
DefaultProps.defaultProps = props;
return DefaultProps;
};
};
exports.default = (0, _createHelper2.default)(defaultProps, 'defaultProps');
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var flattenProp = function flattenProp(propName) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (props) {
return factory(_extends({}, props, props[propName]));
};
};
};
exports.default = (0, _createHelper2.default)(flattenProp, 'flattenProp');
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getContext = function getContext(contextTypes) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var GetContext = function GetContext(ownerProps, context) {
return factory(_extends({}, ownerProps, context));
};
GetContext.contextTypes = contextTypes;
return GetContext;
};
};
exports.default = (0, _createHelper2.default)(getContext, 'getContext');
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _hoistNonReactStatics = __webpack_require__(50);
var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hoistStatics = function hoistStatics(higherOrderComponent) {
return function (BaseComponent) {
var NewComponent = higherOrderComponent(BaseComponent);
(0, _hoistNonReactStatics2.default)(NewComponent, BaseComponent);
return NewComponent;
};
};
exports.default = hoistStatics;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.setObservableConfig = exports.createEventHandler = exports.mapPropsStream = exports.componentFromStream = exports.hoistStatics = exports.nest = exports.componentFromProp = exports.createSink = exports.createEagerFactory = exports.createEagerElement = exports.isClassComponent = exports.shallowEqual = exports.wrapDisplayName = exports.getDisplayName = exports.compose = exports.setDisplayName = exports.setPropTypes = exports.setStatic = exports.toClass = exports.lifecycle = exports.getContext = exports.withContext = exports.onlyUpdateForPropTypes = exports.onlyUpdateForKeys = exports.pure = exports.shouldUpdate = exports.renderNothing = exports.renderComponent = exports.branch = exports.withReducer = exports.withState = exports.flattenProp = exports.renameProps = exports.renameProp = exports.defaultProps = exports.withHandlers = exports.withPropsOnChange = exports.withProps = exports.mapProps = undefined;
var _mapProps2 = __webpack_require__(4);
var _mapProps3 = _interopRequireDefault(_mapProps2);
var _withProps2 = __webpack_require__(44);
var _withProps3 = _interopRequireDefault(_withProps2);
var _withPropsOnChange2 = __webpack_require__(45);
var _withPropsOnChange3 = _interopRequireDefault(_withPropsOnChange2);
var _withHandlers2 = __webpack_require__(43);
var _withHandlers3 = _interopRequireDefault(_withHandlers2);
var _defaultProps2 = __webpack_require__(25);
var _defaultProps3 = _interopRequireDefault(_defaultProps2);
var _renameProp2 = __webpack_require__(35);
var _renameProp3 = _interopRequireDefault(_renameProp2);
var _renameProps2 = __webpack_require__(36);
var _renameProps3 = _interopRequireDefault(_renameProps2);
var _flattenProp2 = __webpack_require__(26);
var _flattenProp3 = _interopRequireDefault(_flattenProp2);
var _withState2 = __webpack_require__(47);
var _withState3 = _interopRequireDefault(_withState2);
var _withReducer2 = __webpack_require__(46);
var _withReducer3 = _interopRequireDefault(_withReducer2);
var _branch2 = __webpack_require__(20);
var _branch3 = _interopRequireDefault(_branch2);
var _renderComponent2 = __webpack_require__(37);
var _renderComponent3 = _interopRequireDefault(_renderComponent2);
var _renderNothing2 = __webpack_require__(38);
var _renderNothing3 = _interopRequireDefault(_renderNothing2);
var _shouldUpdate2 = __webpack_require__(10);
var _shouldUpdate3 = _interopRequireDefault(_shouldUpdate2);
var _pure2 = __webpack_require__(34);
var _pure3 = _interopRequireDefault(_pure2);
var _onlyUpdateForKeys2 = __webpack_require__(17);
var _onlyUpdateForKeys3 = _interopRequireDefault(_onlyUpdateForKeys2);
var _onlyUpdateForPropTypes2 = __webpack_require__(33);
var _onlyUpdateForPropTypes3 = _interopRequireDefault(_onlyUpdateForPropTypes2);
var _withContext2 = __webpack_require__(42);
var _withContext3 = _interopRequireDefault(_withContext2);
var _getContext2 = __webpack_require__(27);
var _getContext3 = _interopRequireDefault(_getContext2);
var _lifecycle2 = __webpack_require__(30);
var _lifecycle3 = _interopRequireDefault(_lifecycle2);
var _toClass2 = __webpack_require__(41);
var _toClass3 = _interopRequireDefault(_toClass2);
var _setStatic2 = __webpack_require__(9);
var _setStatic3 = _interopRequireDefault(_setStatic2);
var _setPropTypes2 = __webpack_require__(40);
var _setPropTypes3 = _interopRequireDefault(_setPropTypes2);
var _setDisplayName2 = __webpack_require__(39);
var _setDisplayName3 = _interopRequireDefault(_setDisplayName2);
var _compose2 = __webpack_require__(22);
var _compose3 = _interopRequireDefault(_compose2);
var _getDisplayName2 = __webpack_require__(7);
var _getDisplayName3 = _interopRequireDefault(_getDisplayName2);
var _wrapDisplayName2 = __webpack_require__(48);
var _wrapDisplayName3 = _interopRequireDefault(_wrapDisplayName2);
var _shallowEqual2 = __webpack_require__(6);
var _shallowEqual3 = _interopRequireDefault(_shallowEqual2);
var _isClassComponent2 = __webpack_require__(8);
var _isClassComponent3 = _interopRequireDefault(_isClassComponent2);
var _createEagerElement2 = __webpack_require__(15);
var _createEagerElement3 = _interopRequireDefault(_createEagerElement2);
var _createEagerFactory2 = __webpack_require__(2);
var _createEagerFactory3 = _interopRequireDefault(_createEagerFactory2);
var _createSink2 = __webpack_require__(24);
var _createSink3 = _interopRequireDefault(_createSink2);
var _componentFromProp2 = __webpack_require__(21);
var _componentFromProp3 = _interopRequireDefault(_componentFromProp2);
var _nest2 = __webpack_require__(32);
var _nest3 = _interopRequireDefault(_nest2);
var _hoistStatics2 = __webpack_require__(28);
var _hoistStatics3 = _interopRequireDefault(_hoistStatics2);
var _componentFromStream2 = __webpack_require__(14);
var _componentFromStream3 = _interopRequireDefault(_componentFromStream2);
var _mapPropsStream2 = __webpack_require__(31);
var _mapPropsStream3 = _interopRequireDefault(_mapPropsStream2);
var _createEventHandler2 = __webpack_require__(23);
var _createEventHandler3 = _interopRequireDefault(_createEventHandler2);
var _setObservableConfig2 = __webpack_require__(5);
var _setObservableConfig3 = _interopRequireDefault(_setObservableConfig2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.mapProps = _mapProps3.default; // Higher-order component helpers
exports.withProps = _withProps3.default;
exports.withPropsOnChange = _withPropsOnChange3.default;
exports.withHandlers = _withHandlers3.default;
exports.defaultProps = _defaultProps3.default;
exports.renameProp = _renameProp3.default;
exports.renameProps = _renameProps3.default;
exports.flattenProp = _flattenProp3.default;
exports.withState = _withState3.default;
exports.withReducer = _withReducer3.default;
exports.branch = _branch3.default;
exports.renderComponent = _renderComponent3.default;
exports.renderNothing = _renderNothing3.default;
exports.shouldUpdate = _shouldUpdate3.default;
exports.pure = _pure3.default;
exports.onlyUpdateForKeys = _onlyUpdateForKeys3.default;
exports.onlyUpdateForPropTypes = _onlyUpdateForPropTypes3.default;
exports.withContext = _withContext3.default;
exports.getContext = _getContext3.default;
exports.lifecycle = _lifecycle3.default;
exports.toClass = _toClass3.default;
// Static property helpers
exports.setStatic = _setStatic3.default;
exports.setPropTypes = _setPropTypes3.default;
exports.setDisplayName = _setDisplayName3.default;
// Composition function
exports.compose = _compose3.default;
// Other utils
exports.getDisplayName = _getDisplayName3.default;
exports.wrapDisplayName = _wrapDisplayName3.default;
exports.shallowEqual = _shallowEqual3.default;
exports.isClassComponent = _isClassComponent3.default;
exports.createEagerElement = _createEagerElement3.default;
exports.createEagerFactory = _createEagerFactory3.default;
exports.createSink = _createSink3.default;
exports.componentFromProp = _componentFromProp3.default;
exports.nest = _nest3.default;
exports.hoistStatics = _hoistStatics3.default;
// Observable helpers
exports.componentFromStream = _componentFromStream3.default;
exports.mapPropsStream = _mapPropsStream3.default;
exports.createEventHandler = _createEventHandler3.default;
exports.setObservableConfig = _setObservableConfig3.default;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lifecycle = function lifecycle(spec) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
if (false) {
console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.');
}
/* eslint-disable react/prefer-es6-class */
return (0, _react.createClass)(_extends({}, spec, {
render: function render() {
return factory(_extends({}, this.props, this.state));
}
}));
/* eslint-enable react/prefer-es6-class */
};
};
exports.default = (0, _createHelper2.default)(lifecycle, 'lifecycle');
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.mapPropsStreamWithConfig = undefined;
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _componentFromStream = __webpack_require__(14);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var identity = function identity(t) {
return t;
};
var componentFromStream = (0, _componentFromStream.componentFromStreamWithConfig)({
fromESObservable: identity,
toESObservable: identity
});
var mapPropsStreamWithConfig = exports.mapPropsStreamWithConfig = function mapPropsStreamWithConfig(config) {
return function (transform) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var fromESObservable = config.fromESObservable;
var toESObservable = config.toESObservable;
return componentFromStream(function (props$) {
var _ref;
return _ref = {
subscribe: function subscribe(observer) {
var subscription = toESObservable(transform(fromESObservable(props$))).subscribe({
next: function next(childProps) {
return observer.next(factory(childProps));
}
});
return {
unsubscribe: function unsubscribe() {
return subscription.unsubscribe();
}
};
}
}, _ref[_symbolObservable2.default] = function () {
return this;
}, _ref;
});
};
};
};
var mapPropsStream = mapPropsStreamWithConfig(_setObservableConfig.config);
exports.default = (0, _createHelper2.default)(mapPropsStream, 'mapPropsStream');
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var nest = function nest() {
for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) {
Components[_key] = arguments[_key];
}
var factories = Components.map(_createEagerFactory2.default);
var Nest = function Nest(_ref) {
var props = _objectWithoutProperties(_ref, []);
var children = _ref.children;
return factories.reduceRight(function (child, factory) {
return factory(props, child);
}, children);
};
if (false) {
/* eslint-disable global-require */
var getDisplayName = require('./getDisplayName').default;
/* eslint-enable global-require */
var displayNames = Components.map(getDisplayName);
Nest.displayName = 'nest(' + displayNames.join(', ') + ')';
}
return Nest;
};
exports.default = nest;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _onlyUpdateForKeys = __webpack_require__(17);
var _onlyUpdateForKeys2 = _interopRequireDefault(_onlyUpdateForKeys);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) {
var propTypes = BaseComponent.propTypes;
if (false) {
/* eslint-disable global-require */
var getDisplayName = require('./getDisplayName').default;
/* eslint-enable global-require */
if (!propTypes) {
/* eslint-disable */
console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".'));
/* eslint-enable */
}
}
var propKeys = Object.keys(propTypes || {});
var OnlyUpdateForPropTypes = (0, _onlyUpdateForKeys2.default)(propKeys)(BaseComponent);
return OnlyUpdateForPropTypes;
};
exports.default = (0, _createHelper2.default)(onlyUpdateForPropTypes, 'onlyUpdateForPropTypes', true, true);
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shouldUpdate = __webpack_require__(10);
var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pure = (0, _shouldUpdate2.default)(function (props, nextProps) {
return !(0, _shallowEqual2.default)(props, nextProps);
});
exports.default = (0, _createHelper2.default)(pure, 'pure', true, true);
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renameProp = function renameProp(oldName, newName) {
return (0, _mapProps2.default)(function (props) {
var _extends2;
return _extends({}, (0, _omit2.default)(props, [oldName]), (_extends2 = {}, _extends2[newName] = props[oldName], _extends2));
});
};
exports.default = (0, _createHelper2.default)(renameProp, 'renameProp');
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var keys = Object.keys;
var mapKeys = function mapKeys(obj, func) {
return keys(obj).reduce(function (result, key) {
var val = obj[key];
/* eslint-disable no-param-reassign */
result[func(val, key)] = val;
/* eslint-enable no-param-reassign */
return result;
}, {});
};
var renameProps = function renameProps(nameMap) {
return (0, _mapProps2.default)(function (props) {
return _extends({}, (0, _omit2.default)(props, keys(nameMap)), mapKeys((0, _pick2.default)(props, keys(nameMap)), function (_, oldName) {
return nameMap[oldName];
}));
});
};
exports.default = (0, _createHelper2.default)(renameProps, 'renameProps');
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import React from 'react'
var renderComponent = function renderComponent(Component) {
return function (_) {
var factory = (0, _createEagerFactory2.default)(Component);
var RenderComponent = function RenderComponent(props) {
return factory(props);
};
// const RenderComponent = props => <Component {...props} />
if (false) {
/* eslint-disable global-require */
var wrapDisplayName = require('./wrapDisplayName').default;
/* eslint-enable global-require */
RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent');
}
return RenderComponent;
};
};
exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false);
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renderNothing = function renderNothing(_) {
var Nothing = function Nothing() {
return null;
};
Nothing.displayName = 'Nothing';
return Nothing;
};
exports.default = (0, _createHelper2.default)(renderNothing, 'renderNothing', false, true);
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _setStatic = __webpack_require__(9);
var _setStatic2 = _interopRequireDefault(_setStatic);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setDisplayName = function setDisplayName(displayName) {
return (0, _setStatic2.default)('displayName', displayName);
};
exports.default = (0, _createHelper2.default)(setDisplayName, 'setDisplayName', false);
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _setStatic = __webpack_require__(9);
var _setStatic2 = _interopRequireDefault(_setStatic);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setPropTypes = function setPropTypes(propTypes) {
return (0, _setStatic2.default)('propTypes', propTypes);
};
exports.default = (0, _createHelper2.default)(setPropTypes, 'setPropTypes', false);
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _getDisplayName = __webpack_require__(7);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _isClassComponent = __webpack_require__(8);
var _isClassComponent2 = _interopRequireDefault(_isClassComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var toClass = function toClass(baseComponent) {
if ((0, _isClassComponent2.default)(baseComponent)) {
return baseComponent;
}
var ToClass = function (_Component) {
_inherits(ToClass, _Component);
function ToClass() {
_classCallCheck(this, ToClass);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
ToClass.prototype.render = function render() {
if (typeof baseComponent === 'string') {
return _react2.default.createElement('baseComponent', this.props);
}
return baseComponent(this.props, this.context);
};
return ToClass;
}(_react.Component);
ToClass.displayName = (0, _getDisplayName2.default)(baseComponent);
ToClass.propTypes = baseComponent.propTypes;
ToClass.contextTypes = baseComponent.contextTypes;
ToClass.defaultProps = baseComponent.defaultProps;
return ToClass;
};
exports.default = toClass;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withContext = function withContext(childContextTypes, getChildContext) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var WithContext = function (_Component) {
_inherits(WithContext, _Component);
function WithContext() {
var _temp, _this, _ret;
_classCallCheck(this, WithContext);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.getChildContext = function () {
return getChildContext(_this.props);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
WithContext.prototype.render = function render() {
return factory(this.props);
};
return WithContext;
}(_react.Component);
WithContext.childContextTypes = childContextTypes;
return WithContext;
};
};
exports.default = (0, _createHelper2.default)(withContext, 'withContext');
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var mapValues = function mapValues(obj, func) {
var result = [];
var i = 0;
/* eslint-disable no-restricted-syntax */
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
i += 1;
result[key] = func(obj[key], key, i);
}
}
/* eslint-enable no-restricted-syntax */
return result;
};
var withHandlers = function withHandlers(handlers) {
return function (BaseComponent) {
var _class, _temp2, _initialiseProps;
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return _temp2 = _class = function (_Component) {
_inherits(_class, _Component);
function _class() {
var _temp, _this, _ret;
_classCallCheck(this, _class);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret);
}
_class.prototype.componentWillReceiveProps = function componentWillReceiveProps() {
this.cachedHandlers = {};
};
_class.prototype.render = function render() {
return factory(_extends({}, this.props, this.handlers));
};
return _class;
}(_react.Component), _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.cachedHandlers = {};
this.handlers = mapValues(handlers, function (createHandler, handlerName) {
return function () {
var cachedHandler = _this2.cachedHandlers[handlerName];
if (cachedHandler) {
return cachedHandler.apply(undefined, arguments);
}
var handler = createHandler(_this2.props);
_this2.cachedHandlers[handlerName] = handler;
if (false) {
console.error('withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.');
}
return handler.apply(undefined, arguments);
};
});
}, _temp2;
};
};
exports.default = (0, _createHelper2.default)(withHandlers, 'withHandlers');
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var withProps = function withProps(input) {
return (0, _mapProps2.default)(function (props) {
return _extends({}, props, typeof input === 'function' ? input(props) : input);
});
};
exports.default = (0, _createHelper2.default)(withProps, 'withProps');
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) {
return !(0, _shallowEqual2.default)((0, _pick2.default)(props, shouldMapOrKeys), (0, _pick2.default)(nextProps, shouldMapOrKeys));
};
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (shouldMap(this.props, nextProps)) {
this.computedProps = propsMapper(nextProps);
}
};
_class2.prototype.render = function render() {
return factory(_extends({}, this.props, this.computedProps));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withPropsOnChange, 'withPropsOnChange');
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState
}, _this.dispatch = function (action) {
return _this.setState(function (_ref) {
var stateValue = _ref.stateValue;
return {
stateValue: reducer(stateValue, action)
};
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.render = function render() {
var _extends2;
return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[dispatchName] = this.dispatch, _extends2)));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withReducer, 'withReducer');
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withState = function withState(stateName, stateUpdaterName, initialState) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState
}, _this.updateStateValue = function (updateFn, callback) {
return _this.setState(function (_ref) {
var stateValue = _ref.stateValue;
return {
stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn
};
}, callback);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.render = function render() {
var _extends2;
return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[stateUpdaterName] = this.updateStateValue, _extends2)));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withState, 'withState');
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _getDisplayName = __webpack_require__(7);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) {
return hocName + '(' + (0, _getDisplayName2.default)(BaseComponent) + ')';
};
exports.default = wrapDisplayName;
/***/ },
/* 49 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 50 */
/***/ function(module, exports) {
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) {
if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
var keys = Object.getOwnPropertyNames(sourceComponent);
for (var i=0; i<keys.length; ++i) {
if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) {
try {
targetComponent[keys[i]] = sourceComponent[keys[i]];
} catch (error) {
}
}
}
}
return targetComponent;
};
/***/ },
/* 51 */
/***/ function(module, exports) {
'use strict';
module.exports = function symbolObservablePonyfill(root) {
var result;
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
result = Symbol.observable;
} else {
result = Symbol('observable');
Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
/***/ }
/******/ ])
});
; |
lib/components/term-group.js | stefanivic/hyper | import React from 'react';
import {connect} from 'react-redux';
import Component from '../component';
import {decorate, getTermProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
const Term = decorate(Term_, 'Term');
const SplitPane = decorate(SplitPane_, 'SplitPane');
class TermGroup_ extends Component {
constructor(props, context) {
super(props, context);
this.bound = new WeakMap();
}
bind(fn, thisObj, uid) {
if (!this.bound.has(fn)) {
this.bound.set(fn, {});
}
const map = this.bound.get(fn);
if (!map[uid]) {
map[uid] = fn.bind(thisObj, uid);
}
return map[uid];
}
renderSplit(groups) {
const [first, ...rest] = groups;
if (rest.length === 0) {
return first;
}
const direction = this.props.termGroup.direction.toLowerCase();
return (<SplitPane
direction={direction}
sizes={this.props.termGroup.sizes}
onResize={this.props.onTermGroupResize}
borderColor={this.props.borderColor}
>
{ groups }
</SplitPane>);
}
renderTerm(uid) {
const session = this.props.sessions[uid];
const termRef = this.props.terms[uid];
const props = getTermProps(uid, this.props, {
isTermActive: uid === this.props.activeSession,
term: termRef ? termRef.term : null,
customCSS: this.props.customCSS,
fontSize: this.props.fontSize,
cursorColor: this.props.cursorColor,
cursorShape: this.props.cursorShape,
cursorBlink: this.props.cursorBlink,
fontFamily: this.props.fontFamily,
uiFontFamily: this.props.uiFontFamily,
fontSmoothing: this.props.fontSmoothing,
foregroundColor: this.props.foregroundColor,
backgroundColor: this.props.backgroundColor,
modifierKeys: this.props.modifierKeys,
padding: this.props.padding,
colors: this.props.colors,
url: session.url,
cleared: session.cleared,
cols: session.cols,
rows: session.rows,
copyOnSelect: this.props.copyOnSelect,
bell: this.props.bell,
bellSoundURL: this.props.bellSoundURL,
onActive: this.bind(this.props.onActive, null, uid),
onResize: this.bind(this.props.onResize, null, uid),
onTitle: this.bind(this.props.onTitle, null, uid),
onData: this.bind(this.props.onData, null, uid),
onURLAbort: this.bind(this.props.onURLAbort, null, uid),
borderColor: this.props.borderColor,
quickEdit: this.props.quickEdit,
uid
});
// This will create a new ref_ function for every render,
// which is inefficient. Should maybe do something similar
// to this.bind.
return (<Term
ref_={term => this.props.ref_(uid, term)}
key={uid}
{...props}
/>);
}
template() {
const {childGroups, termGroup} = this.props;
if (termGroup.sessionUid) {
return this.renderTerm(termGroup.sessionUid);
}
const groups = childGroups.map(child => {
const props = Object.assign({}, this.props, {
termGroup: child
});
return (<TermGroup
key={child.uid}
{...props}
/>);
});
return this.renderSplit(groups);
}
}
const TermGroup = connect(
(state, ownProps) => ({
childGroups: ownProps.termGroup.children.map(uid =>
state.termGroups.termGroups[uid]
)
}),
(dispatch, ownProps) => ({
onTermGroupResize(splitSizes) {
dispatch(resizeTermGroup(ownProps.termGroup.uid, splitSizes));
}
})
)(TermGroup_);
export default TermGroup;
|
benchmarks/dom-comparison/src/implementations/react-jss/View.js | risetechnologies/fela | /* eslint-disable react/prop-types */
import classnames from 'classnames';
import injectSheet from 'react-jss';
import React from 'react';
class View extends React.Component {
render() {
const { classes, className, ...other } = this.props;
return <div {...other} className={classnames(classes.root, className)} />;
}
}
const styles = {
root: {
alignItems: 'stretch',
borderWidth: 0,
borderStyle: 'solid',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
margin: 0,
padding: 0,
position: 'relative',
// fix flexbox bugs
minHeight: 0,
minWidth: 0
}
};
export default injectSheet(styles)(View);
|
ajax/libs/babel-core/5.0.10/browser.min.js | magoni/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.babel=e()}}(function(){var e,t,n;return function r(e,t,n){function l(s,a){if(!t[s]){if(!e[s]){var o="function"==typeof require&&require;if(!a&&o)return o(s,!0);if(i)return i(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=t[s]={exports:{}};e[s][0].call(p.exports,function(t){var n=e[s][1][t];return l(n?n:t)},p,p.exports,r,e,t,n)}return t[s].exports}for(var i="function"==typeof require&&require,s=0;s<n.length;s++)l(n[s]);return l}({1:[function(e){"use strict";var t=e(".."),n=t.Parser.prototype,r=t.tokTypes;n.isRelational=function(e){return this.type===r.relational&&this.value===e},n.expectRelational=function(e){this.isRelational(e)?this.next():this.unexpected()},n.flow_parseDeclareClass=function(e){return this.next(),this.flow_parseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},n.flow_parseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdent(),n=this.startNode(),l=this.startNode();n.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,this.expect(r.parenL);var i=this.flow_parseFunctionTypeParams();return n.params=i.params,n.rest=i.rest,this.expect(r.parenR),this.expect(r.colon),n.returnType=this.flow_parseType(),l.typeAnnotation=this.finishNode(n,"FunctionTypeAnnotation"),t.typeAnnotation=this.finishNode(l,"TypeAnnotation"),this.finishNode(t,t.type),this.semicolon(),this.finishNode(e,"DeclareFunction")},n.flow_parseDeclare=function(e){return this.type===r._class?this.flow_parseDeclareClass(e):this.type===r._function?this.flow_parseDeclareFunction(e):this.type===r._var?this.flow_parseDeclareVariable(e):this.isContextual("module")?this.flow_parseDeclareModule(e):void this.unexpected()},n.flow_parseDeclareVariable=function(e){return this.next(),e.id=this.flow_parseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},n.flow_parseDeclareModule=function(e){this.next(),e.id=this.type===r.string?this.parseExprAtom():this.parseIdent();var t=e.body=this.startNode(),n=t.body=[];for(this.expect(r.braceL);this.type!==r.braceR;){var l=this.startNode();this.next(),n.push(this.flow_parseDeclare(l))}return this.expect(r.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},n.flow_parseInterfaceish=function(e,t){if(e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,e["extends"]=[],this.eat(r._extends))do e["extends"].push(this.flow_parseInterfaceExtends());while(this.eat(r.comma));e.body=this.flow_parseObjectType(t)},n.flow_parseInterfaceExtends=function(){var e=this.startNode();return e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterInstantiation():null,this.finishNode(e,"InterfaceExtends")},n.flow_parseInterface=function(e){return this.flow_parseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},n.flow_parseTypeAlias=function(e){return e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,this.expect(r.eq),e.right=this.flow_parseType(),this.semicolon(),this.finishNode(e,"TypeAlias")},n.flow_parseTypeParameterDeclaration=function(){var e=this.startNode();for(e.params=[],this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flow_parseTypeAnnotatableIdentifier()),this.isRelational(">")||this.expect(r.comma);return this.expectRelational(">"),this.finishNode(e,"TypeParameterDeclaration")},n.flow_parseTypeParameterInstantiation=function(){var e=this.startNode(),t=this.inType;for(e.params=[],this.inType=!0,this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flow_parseType()),this.isRelational(">")||this.expect(r.comma);return this.expectRelational(">"),this.inType=t,this.finishNode(e,"TypeParameterInstantiation")},n.flow_parseObjectPropertyKey=function(){return this.type===r.num||this.type===r.string?this.parseExprAtom():this.parseIdent(!0)},n.flow_parseObjectTypeIndexer=function(e,t){return e["static"]=t,this.expect(r.bracketL),e.id=this.flow_parseObjectPropertyKey(),this.expect(r.colon),e.key=this.flow_parseType(),this.expect(r.bracketR),this.expect(r.colon),e.value=this.flow_parseType(),this.flow_objectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},n.flow_parseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flow_parseTypeParameterDeclaration()),this.expect(r.parenL);this.type===r.name;)e.params.push(this.flow_parseFunctionTypeParam()),this.type!==r.parenR&&this.expect(r.comma);return this.eat(r.ellipsis)&&(e.rest=this.flow_parseFunctionTypeParam()),this.expect(r.parenR),this.expect(r.colon),e.returnType=this.flow_parseType(),this.finishNode(e,"FunctionTypeAnnotation")},n.flow_parseObjectTypeMethod=function(e,t,n){var r=this.startNodeAt(e);return r.value=this.flow_parseObjectTypeMethodish(this.startNodeAt(e)),r["static"]=t,r.key=n,r.optional=!1,this.flow_objectTypeSemicolon(),this.finishNode(r,"ObjectTypeProperty")},n.flow_parseObjectTypeCallProperty=function(e,t){var n=this.startNode();return e["static"]=t,e.value=this.flow_parseObjectTypeMethodish(n),this.flow_objectTypeSemicolon(),this.finishNode(e,"ObjectTypeCallProperty")},n.flow_parseObjectType=function(e){var t,n,l,i=this.startNode(),s=!1;for(i.callProperties=[],i.properties=[],i.indexers=[],this.expect(r.braceL);this.type!==r.braceR;){var a=this.markPosition();t=this.startNode(),e&&this.isContextual("static")&&(this.next(),l=!0),this.type===r.bracketL?i.indexers.push(this.flow_parseObjectTypeIndexer(t,l)):this.type===r.parenL||this.isRelational("<")?i.callProperties.push(this.flow_parseObjectTypeCallProperty(t,e)):(n=l&&this.type===r.colon?this.parseIdent():this.flow_parseObjectPropertyKey(),this.isRelational("<")||this.type===r.parenL?i.properties.push(this.flow_parseObjectTypeMethod(a,l,n)):(this.eat(r.question)&&(s=!0),this.expect(r.colon),t.key=n,t.value=this.flow_parseType(),t.optional=s,t["static"]=l,this.flow_objectTypeSemicolon(),i.properties.push(this.finishNode(t,"ObjectTypeProperty"))))}return this.expect(r.braceR),this.finishNode(i,"ObjectTypeAnnotation")},n.flow_objectTypeSemicolon=function(){this.eat(r.semi)||this.type===r.braceR||this.unexpected()},n.flow_parseGenericType=function(e,t){var n=this.startNodeAt(e);for(n.typeParameters=null,n.id=t;this.eat(r.dot);){var l=this.startNodeAt(e);l.qualification=n.id,l.id=this.parseIdent(),n.id=this.finishNode(l,"QualifiedTypeIdentifier")}return this.isRelational("<")&&(n.typeParameters=this.flow_parseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},n.flow_parseVoidType=function(){var e=this.startNode();return this.expect(r._void),this.finishNode(e,"VoidTypeAnnotation")},n.flow_parseTypeofType=function(){var e=this.startNode();return this.expect(r._typeof),e.argument=this.flow_parsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},n.flow_parseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(r.bracketL);this.pos<this.input.length&&this.type!==r.bracketR&&(e.types.push(this.flow_parseType()),this.type!==r.bracketR);)this.expect(r.comma);return this.expect(r.bracketR),this.finishNode(e,"TupleTypeAnnotation")},n.flow_parseFunctionTypeParam=function(){var e=!1,t=this.startNode();return t.name=this.parseIdent(),this.eat(r.question)&&(e=!0),this.expect(r.colon),t.optional=e,t.typeAnnotation=this.flow_parseType(),this.finishNode(t,"FunctionTypeParam")},n.flow_parseFunctionTypeParams=function(){for(var e={params:[],rest:null};this.type===r.name;)e.params.push(this.flow_parseFunctionTypeParam()),this.type!==r.parenR&&this.expect(r.comma);return this.eat(r.ellipsis)&&(e.rest=this.flow_parseFunctionTypeParam()),e},n.flow_identToTypeAnnotation=function(e,t,n){switch(n.name){case"any":return this.finishNode(t,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(t,"BooleanTypeAnnotation");case"number":return this.finishNode(t,"NumberTypeAnnotation");case"string":return this.finishNode(t,"StringTypeAnnotation");default:return this.flow_parseGenericType(e,n)}},n.flow_parsePrimaryType=function(){var e,t,n,l=this.markPosition(),i=this.startNode(),s=!1;switch(this.type){case r.name:return this.flow_identToTypeAnnotation(l,i,this.parseIdent());case r.braceL:return this.flow_parseObjectType();case r.bracketL:return this.flow_parseTupleType();case r.relational:if("<"===this.value)return i.typeParameters=this.flow_parseTypeParameterDeclaration(),this.expect(r.parenL),e=this.flow_parseFunctionTypeParams(),i.params=e.params,i.rest=e.rest,this.expect(r.parenR),this.expect(r.arrow),i.returnType=this.flow_parseType(),this.finishNode(i,"FunctionTypeAnnotation");case r.parenL:if(this.next(),this.type!==r.parenR&&this.type!==r.ellipsis)if(this.type===r.name){var t=this.lookahead().type;s=t!==r.question&&t!==r.colon}else s=!0;return s?(n=this.flow_parseType(),this.expect(r.parenR),this.eat(r.arrow)&&this.raise(i,"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"),n):(e=this.flow_parseFunctionTypeParams(),i.params=e.params,i.rest=e.rest,this.expect(r.parenR),this.expect(r.arrow),i.returnType=this.flow_parseType(),i.typeParameters=null,this.finishNode(i,"FunctionTypeAnnotation"));case r.string:return i.value=this.value,i.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(i,"StringLiteralTypeAnnotation");default:if(this.type.keyword)switch(this.type.keyword){case"void":return this.flow_parseVoidType();case"typeof":return this.flow_parseTypeofType()}}this.unexpected()},n.flow_parsePostfixType=function(){var e=this.startNode(),t=e.elementType=this.flow_parsePrimaryType();return this.type===r.bracketL?(this.expect(r.bracketL),this.expect(r.bracketR),this.finishNode(e,"ArrayTypeAnnotation")):t},n.flow_parsePrefixType=function(){var e=this.startNode();return this.eat(r.question)?(e.typeAnnotation=this.flow_parsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flow_parsePostfixType()},n.flow_parseIntersectionType=function(){var e=this.startNode(),t=this.flow_parsePrefixType();for(e.types=[t];this.eat(r.bitwiseAND);)e.types.push(this.flow_parsePrefixType());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},n.flow_parseUnionType=function(){var e=this.startNode(),t=this.flow_parseIntersectionType();for(e.types=[t];this.eat(r.bitwiseOR);)e.types.push(this.flow_parseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},n.flow_parseType=function(){var e=this.inType;this.inType=!0;var t=this.flow_parseUnionType();return this.inType=e,t},n.flow_parseTypeAnnotation=function(){var e=this.startNode(),t=this.inType;return this.inType=!0,this.expect(r.colon),e.typeAnnotation=this.flow_parseType(),this.inType=t,this.finishNode(e,"TypeAnnotation")},n.flow_parseTypeAnnotatableIdentifier=function(e,t){var n=(this.startNode(),this.parseIdent()),l=!1;return t&&this.eat(r.question)&&(this.expect(r.question),l=!0),(e||this.type===r.colon)&&(n.typeAnnotation=this.flow_parseTypeAnnotation(),this.finishNode(n,n.type)),l&&(n.optional=!0,this.finishNode(n,n.type)),n},t.plugins.flow=function(e){e.extend("parseFunctionBody",function(e){return function(t,n){return this.type===r.colon&&(t.returnType=this.flow_parseTypeAnnotation()),e.call(this,t,n)}}),e.extend("parseStatement",function(e){return function(t,n){if(this.strict&&this.type===r.name&&"interface"===this.value){var l=this.startNode();return this.next(),this.flow_parseInterface(l)}return e.call(this,t,n)}}),e.extend("parseExpressionStatement",function(e){return function(t,n){if("Identifier"===n.type)if("declare"===n.name){if(this.type===r._class||this.type===r.name||this.type===r._function||this.type===r._var)return this.flow_parseDeclare(t)}else if(this.type===r.name){if("interface"===n.name)return this.flow_parseInterface(t);if("type"===n.name)return this.flow_parseTypeAlias(t)}return e.call(this,t,n)}}),e.extend("shouldParseExportDeclaration",function(e){return function(){return this.isContextual("type")||e.call(this)}}),e.extend("parseParenItem",function(){return function(e,t){if(this.type===r.colon){var n=this.startNodeAt(t);return n.expression=e,n.typeAnnotation=this.flow_parseTypeAnnotation(),this.finishNode(n,"TypeCastExpression")}return e}}),e.extend("parseClassId",function(e){return function(t,n){e.call(this,t,n),this.isRelational("<")&&(t.typeParameters=this.flow_parseTypeParameterDeclaration())}}),e.extend("readToken",function(e){return function(t){return!this.inType||62!==t&&60!==t?e.call(this,t):this.finishOp(r.relational,1)}}),e.extend("jsx_readToken",function(e){return function(){return this.inType?void 0:e.call(this)}}),e.extend("parseParenArrowList",function(e){return function(t,n,r){for(var l=0;l<n.length;l++){var i=n[l];if("TypeCastExpression"===i.type){var s=i.expression;s.typeAnnotation=i.typeAnnotation,n[l]=s}}return e.call(this,t,n,r)}}),e.extend("parseClassProperty",function(e){return function(t){return this.type===r.colon&&(t.typeAnnotation=this.flow_parseTypeAnnotation()),e.call(this,t)}}),e.extend("isClassProperty",function(e){return function(){return this.type===r.colon||e.call(this)}}),e.extend("parseClassMethod",function(){return function(e,t,n,r){var l;this.isRelational("<")&&(l=this.flow_parseTypeParameterDeclaration()),t.value=this.parseMethod(n,r),t.value.typeParameters=l,e.body.push(this.finishNode(t,"MethodDefinition"))}}),e.extend("parseClassSuper",function(e){return function(t,n){if(e.call(this,t,n),t.superClass&&this.isRelational("<")&&(t.superTypeParameters=this.flow_parseTypeParameterInstantiation()),this.isContextual("implements")){this.next();var l=t["implements"]=[];do{var t=this.startNode();t.id=this.parseIdent(),t.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterInstantiation():null,l.push(this.finishNode(t,"ClassImplements"))}while(this.eat(r.comma))}}}),e.extend("parseObjPropValue",function(e){return function(t){var n;this.isRelational("<")&&(n=this.flow_parseTypeParameterDeclaration(),this.type!==r.parenL&&this.unexpected()),e.apply(this,arguments),t.value.typeParameters=n}}),e.extend("parseAssignableListItemTypes",function(){return function(e){return this.eat(r.question)&&(e.optional=!0),this.type===r.colon&&(e.typeAnnotation=this.flow_parseTypeAnnotation()),this.finishNode(e,e.type),e}}),e.extend("parseImportSpecifiers",function(e){return function(t){if(t.isType=!1,this.isContextual("type")){var n=this.markPosition(),l=this.parseIdent();if(this.type===r.name&&"from"!==this.value||this.type===r.braceL||this.type===r.star)t.isType=!0;else{if(t.specifiers.push(this.parseImportSpecifierDefault(l,n)),this.isContextual("from"))return;this.eat(r.comma)}}e.call(this,t)}}),e.extend("parseFunctionParams",function(e){return function(t){this.isRelational("<")&&(t.typeParameters=this.flow_parseTypeParameterDeclaration()),e.call(this,t)}}),e.extend("parseVarHead",function(e){return function(t){e.call(this,t),this.type===r.colon&&(t.id.typeAnnotation=this.flow_parseTypeAnnotation(),this.finishNode(t.id,t.id.type))}})}},{"..":5}],2:[function(e){"use strict";function t(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?t(e.object)+"."+t(e.property):void 0}var n=e(".."),r=n.tokTypes,l=n.tokContexts;l.j_oTag=new n.TokContext("<tag",!1),l.j_cTag=new n.TokContext("</tag",!1),l.j_expr=new n.TokContext("<tag>...</tag>",!0,!0),r.jsxName=new n.TokenType("jsxName"),r.jsxText=new n.TokenType("jsxText",{beforeExpr:!0}),r.jsxTagStart=new n.TokenType("jsxTagStart"),r.jsxTagEnd=new n.TokenType("jsxTagEnd"),r.jsxTagStart.updateContext=function(){this.context.push(l.j_expr),this.context.push(l.j_oTag),this.exprAllowed=!1},r.jsxTagEnd.updateContext=function(e){var t=this.context.pop();t===l.j_oTag&&e===r.slash||t===l.j_cTag?(this.context.pop(),this.exprAllowed=this.curContext()===l.j_expr):this.exprAllowed=!0};var i=n.Parser.prototype;i.jsx_readToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated JSX contents");var l=this.input.charCodeAt(this.pos);switch(l){case 60:case 123:return this.pos===this.start?60===l&&this.exprAllowed?(++this.pos,this.finishToken(r.jsxTagStart)):this.getTokenFromCode(l):(e+=this.input.slice(t,this.pos),this.finishToken(r.jsxText,e));case 38:e+=this.input.slice(t,this.pos),e+=this.jsx_readEntity(),t=this.pos;break;default:n.isNewLine(l)?(e+=this.input.slice(t,this.pos),++this.pos,13===l&&10===this.input.charCodeAt(this.pos)?(++this.pos,e+="\n"):e+=String.fromCharCode(l),this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos):++this.pos}}},i.jsx_readString=function(e){for(var t="",n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var l=this.input.charCodeAt(this.pos);if(l===e)break;38===l?(t+=this.input.slice(n,this.pos),t+=this.jsx_readEntity(),n=this.pos):++this.pos}return t+=this.input.slice(n,this.pos++),this.finishToken(r.string,t)};var s={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},a=/^[\da-fA-F]+$/,o=/^\d+$/;i.jsx_readEntity=function(){var e,t="",n=0,r=this.input[this.pos];"&"!==r&&this.raise(this.pos,"Entity must start with an ampersand");for(var l=++this.pos;this.pos<this.input.length&&n++<10;){if(r=this.input[this.pos++],";"===r){"#"===t[0]?"x"===t[1]?(t=t.substr(2),a.test(t)&&(e=String.fromCharCode(parseInt(t,16)))):(t=t.substr(1),o.test(t)&&(e=String.fromCharCode(parseInt(t,10)))):e=s[t];break}t+=r}return e?e:(this.pos=l,"&")},i.jsx_readWord=function(){var e,t=this.pos;do e=this.input.charCodeAt(++this.pos);while(n.isIdentifierChar(e)||45===e);return this.finishToken(r.jsxName,this.input.slice(t,this.pos))},i.jsx_parseIdentifier=function(){var e=this.startNode();return this.type===r.jsxName?e.name=this.value:this.type.keyword?e.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")},i.jsx_parseNamespacedName=function(){var e=this.markPosition(),t=this.jsx_parseIdentifier();if(!this.eat(r.colon))return t;var n=this.startNodeAt(e);return n.namespace=t,n.name=this.jsx_parseIdentifier(),this.finishNode(n,"JSXNamespacedName")},i.jsx_parseElementName=function(){for(var e=this.markPosition(),t=this.jsx_parseNamespacedName();this.eat(r.dot);){var n=this.startNodeAt(e);n.object=t,n.property=this.jsx_parseIdentifier(),t=this.finishNode(n,"JSXMemberExpression")}return t},i.jsx_parseAttributeValue=function(){switch(this.type){case r.braceL:var e=this.jsx_parseExpressionContainer();return"JSXEmptyExpression"===e.expression.type&&this.raise(e.start,"JSX attributes must only be assigned a non-empty expression"),e;case r.jsxTagStart:case r.string:return this.parseExprAtom();default:this.raise(this.start,"JSX value should be either an expression or a quoted JSX text")}},i.jsx_parseEmptyExpression=function(){var e=this.start;return this.start=this.lastTokEnd,this.lastTokEnd=e,e=this.startLoc,this.startLoc=this.lastTokEndLoc,this.lastTokEndLoc=e,this.finishNode(this.startNode(),"JSXEmptyExpression")},i.jsx_parseExpressionContainer=function(){var e=this.startNode();return this.next(),e.expression=this.type===r.braceR?this.jsx_parseEmptyExpression():this.parseExpression(),this.expect(r.braceR),this.finishNode(e,"JSXExpressionContainer")},i.jsx_parseAttribute=function(){var e=this.startNode();return this.eat(r.braceL)?(this.expect(r.ellipsis),e.argument=this.parseMaybeAssign(),this.expect(r.braceR),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsx_parseNamespacedName(),e.value=this.eat(r.eq)?this.jsx_parseAttributeValue():null,this.finishNode(e,"JSXAttribute"))},i.jsx_parseOpeningElementAt=function(e){var t=this.startNodeAt(e);for(t.attributes=[],t.name=this.jsx_parseElementName();this.type!==r.slash&&this.type!==r.jsxTagEnd;)t.attributes.push(this.jsx_parseAttribute());return t.selfClosing=this.eat(r.slash),this.expect(r.jsxTagEnd),this.finishNode(t,"JSXOpeningElement")},i.jsx_parseClosingElementAt=function(e){var t=this.startNodeAt(e);return t.name=this.jsx_parseElementName(),this.expect(r.jsxTagEnd),this.finishNode(t,"JSXClosingElement")},i.jsx_parseElementAt=function(e){var n=this.startNodeAt(e),l=[],i=this.jsx_parseOpeningElementAt(e),s=null;if(!i.selfClosing){e:for(;;)switch(this.type){case r.jsxTagStart:if(e=this.markPosition(),this.next(),this.eat(r.slash)){s=this.jsx_parseClosingElementAt(e);break e}l.push(this.jsx_parseElementAt(e));break;case r.jsxText:l.push(this.parseExprAtom());break;case r.braceL:l.push(this.jsx_parseExpressionContainer());break;default:this.unexpected()}t(s.name)!==t(i.name)&&this.raise(s.start,"Expected corresponding JSX closing tag for <"+t(i.name)+">")}return n.openingElement=i,n.closingElement=s,n.children=l,this.finishNode(n,"JSXElement")},i.jsx_parseElement=function(){var e=this.markPosition();return this.next(),this.jsx_parseElementAt(e)},n.plugins.jsx=function(e){e.extend("parseExprAtom",function(e){return function(t){return this.type===r.jsxText?this.parseLiteral(this.value):this.type===r.jsxTagStart?this.jsx_parseElement():e.call(this,t)}}),e.extend("readToken",function(e){return function(t){var i=this.curContext();if(i===l.j_expr)return this.jsx_readToken();if(i===l.j_oTag||i===l.j_cTag){if(n.isIdentifierStart(t))return this.jsx_readWord();if(62==t)return++this.pos,this.finishToken(r.jsxTagEnd);if((34===t||39===t)&&i==l.j_oTag)return this.jsx_readString(t)}return 60===t&&this.exprAllowed?(++this.pos,this.finishToken(r.jsxTagStart)):e.call(this,t)}}),e.extend("updateContext",function(e){return function(t){if(this.type==r.braceL){var n=this.curContext();n==l.j_oTag?this.context.push(l.b_expr):n==l.j_expr?this.context.push(l.b_tmpl):e.call(this,t),this.exprAllowed=!0}else{if(this.type!==r.slash||t!==r.jsxTagStart)return e.call(this,t);this.context.length-=2,this.context.push(l.j_cTag),this.exprAllowed=!1}}})}},{"..":5}],3:[function(e){"use strict";var t=e("./tokentype").types,n=e("./state").Parser,r=e("./identifier").reservedWords,l=e("./util").has,i=n.prototype;i.checkPropClash=function(e,t){if(!(this.options.ecmaVersion>=6)){var n=e.key,r=void 0;switch(n.type){case"Identifier":r=n.name;break;case"Literal":r=String(n.value);break;default:return}var i=e.kind||"init",s=void 0;if(l(t,r)){s=t[r];var a="init"!==i;((this.strict||a)&&s[i]||!(a^s.init))&&this.raise(n.start,"Redefinition of property")}else s=t[r]={init:!1,get:!1,set:!1};s[i]=!0}},i.parseExpression=function(e,n){var r=this.markPosition(),l=this.parseMaybeAssign(e,n);if(this.type===t.comma){var i=this.startNodeAt(r);for(i.expressions=[l];this.eat(t.comma);)i.expressions.push(this.parseMaybeAssign(e,n));return this.finishNode(i,"SequenceExpression")}return l},i.parseMaybeAssign=function(e,n,r){if(this.type==t._yield&&this.inGenerator)return this.parseYield();var l=void 0;n?l=!1:(n={start:0},l=!0);var i=this.markPosition(),s=this.parseMaybeConditional(e,n);if(r&&(s=r.call(this,s,i)),this.type.isAssign){var a=this.startNodeAt(i);return a.operator=this.value,a.left=this.type===t.eq?this.toAssignable(s):s,n.start=0,this.checkLVal(s),s.parenthesizedExpression&&("ObjectPattern"===s.type?this.raise(s.start,"You're trying to assign to a parenthesized expression, instead of `({ foo }) = {}` use `({ foo } = {})`"):this.raise(s.start,"Parenthesized left hand expressions are illegal")),this.next(),a.right=this.parseMaybeAssign(e),this.finishNode(a,"AssignmentExpression")}return l&&n.start&&this.unexpected(n.start),s},i.parseMaybeConditional=function(e,n){var r=this.markPosition(),l=this.parseExprOps(e,n);if(n&&n.start)return l;if(this.eat(t.question)){var i=this.startNodeAt(r);return i.test=l,i.consequent=this.parseMaybeAssign(),this.expect(t.colon),i.alternate=this.parseMaybeAssign(e),this.finishNode(i,"ConditionalExpression")}return l},i.parseExprOps=function(e,t){var n=this.markPosition(),r=this.parseMaybeUnary(t);return t&&t.start?r:this.parseExprOp(r,n,-1,e)},i.parseExprOp=function(e,n,r,l){var i=this.type.binop;if(null!=i&&(!l||this.type!==t._in)&&i>r){var s=this.startNodeAt(n);s.left=e,s.operator=this.value;var a=this.type;this.next();var o=this.markPosition();return s.right=this.parseExprOp(this.parseMaybeUnary(),o,a.rightAssociative?i-1:i,l),this.finishNode(s,a===t.logicalOR||a===t.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(s,n,r,l)}return e},i.parseMaybeUnary=function(e){if(this.type.prefix){var n=this.startNode(),r=this.type===t.incDec;return n.operator=this.value,n.prefix=!0,this.next(),n.argument=this.parseMaybeUnary(),e&&e.start&&this.unexpected(e.start),r?this.checkLVal(n.argument):this.strict&&"delete"===n.operator&&"Identifier"===n.argument.type&&this.raise(n.start,"Deleting local variable in strict mode"),this.finishNode(n,r?"UpdateExpression":"UnaryExpression")}var l=this.markPosition(),i=this.parseExprSubscripts(e);if(e&&e.start)return i;for(;this.type.postfix&&!this.canInsertSemicolon();){var n=this.startNodeAt(l);n.operator=this.value,n.prefix=!1,n.argument=i,this.checkLVal(i),this.next(),i=this.finishNode(n,"UpdateExpression")}return i},i.parseExprSubscripts=function(e){var t=this.markPosition(),n=this.parseExprAtom(e);return e&&e.start?n:this.parseSubscripts(n,t)},i.parseSubscripts=function(e,n,r){if(this.eat(t.dot)){var l=this.startNodeAt(n);return l.object=e,l.property=this.parseIdent(!0),l.computed=!1,this.parseSubscripts(this.finishNode(l,"MemberExpression"),n,r)}if(this.eat(t.bracketL)){var l=this.startNodeAt(n);return l.object=e,l.property=this.parseExpression(),l.computed=!0,this.expect(t.bracketR),this.parseSubscripts(this.finishNode(l,"MemberExpression"),n,r)}if(!r&&this.eat(t.parenL)){var l=this.startNodeAt(n);return l.callee=e,l.arguments=this.parseExprList(t.parenR,!1),this.parseSubscripts(this.finishNode(l,"CallExpression"),n,r)}if(this.type===t.backQuote){var l=this.startNodeAt(n);return l.tag=e,l.quasi=this.parseTemplate(),this.parseSubscripts(this.finishNode(l,"TaggedTemplateExpression"),n,r)}return e},i.parseExprAtom=function(e){var n=void 0;switch(this.type){case t._this:case t._super:var r=this.type===t._this?"ThisExpression":"Super";return n=this.startNode(),this.next(),this.finishNode(n,r);case t._yield:this.inGenerator&&this.unexpected();case t._do:if(this.options.features["es7.doExpressions"]){var l=this.startNode();return this.next(),l.body=this.parseBlock(),this.finishNode(l,"DoExpression")}case t.name:var i=this.markPosition();n=this.startNode();var s=this.parseIdent(this.type!==t.name);if(this.options.features["es7.asyncFunctions"])if("async"===s.name){if(this.type===t.parenL){var a=this.parseParenAndDistinguishExpression(i,!0);return a&&"ArrowFunctionExpression"===a.type?a:(n.callee=s,n.arguments=a?"SequenceExpression"===a.type?a.expressions:[a]:[],this.parseSubscripts(this.finishNode(n,"CallExpression"),i))}if(this.type===t.name)return s=this.parseIdent(),this.expect(t.arrow),this.parseArrowExpression(n,[s],!0);if(this.type===t._function&&!this.canInsertSemicolon())return this.next(),this.parseFunction(n,!1,!1,!0)}else if("await"===s.name&&this.inAsync)return this.parseAwait(n);return!this.canInsertSemicolon()&&this.eat(t.arrow)?this.parseArrowExpression(this.startNodeAt(i),[s]):s;case t.regexp:var o=this.value;return n=this.parseLiteral(o.value),n.regex={pattern:o.pattern,flags:o.flags},n;case t.num:case t.string:return this.parseLiteral(this.value);case t._null:case t._true:case t._false:return n=this.startNode(),n.value=this.type===t._null?null:this.type===t._true,n.raw=this.type.keyword,this.next(),this.finishNode(n,"Literal");case t.parenL:return this.parseParenAndDistinguishExpression();case t.bracketL:return n=this.startNode(),this.next(),(this.options.ecmaVersion>=7||this.options.features["es7.comprehensions"])&&this.type===t._for?this.parseComprehension(n,!1):(n.elements=this.parseExprList(t.bracketR,!0,!0,e),this.finishNode(n,"ArrayExpression"));case t.braceL:return this.parseObj(!1,e);case t._function:return n=this.startNode(),this.next(),this.parseFunction(n,!1);case t.at:this.parseDecorators();case t._class:return n=this.startNode(),this.takeDecorators(n),this.parseClass(n,!1);case t._new:return this.parseNew();case t.backQuote:return this.parseTemplate();default:this.unexpected()}},i.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(t,"Literal")},i.parseParenExpression=function(){this.expect(t.parenL);var e=this.parseExpression();return this.expect(t.parenR),e},i.parseParenAndDistinguishExpression=function(e,n){e=e||this.markPosition();var r=void 0;if(this.options.ecmaVersion>=6){if(this.next(),(this.options.features["es7.comprehensions"]||this.options.ecmaVersion>=7)&&this.type===t._for)return this.parseComprehension(this.startNodeAt(e),!0);for(var l=this.markPosition(),i=[],s=!0,a={start:0},o=void 0,u=void 0;this.type!==t.parenR;){if(s?s=!1:this.expect(t.comma),this.type===t.ellipsis){var p=this.markPosition();o=this.start,i.push(this.parseParenItem(this.parseRest(),p));break}this.type!==t.parenL||u||(u=this.start),i.push(this.parseMaybeAssign(!1,a,this.parseParenItem))}var c=this.markPosition();
if(this.expect(t.parenR),!this.canInsertSemicolon()&&this.eat(t.arrow))return u&&this.unexpected(u),this.parseParenArrowList(e,i,n);if(!i.length){if(n)return;this.unexpected(this.lastTokStart)}o&&this.unexpected(o),a.start&&this.unexpected(a.start),i.length>1?(r=this.startNodeAt(l),r.expressions=i,this.finishNodeAt(r,"SequenceExpression",c)):r=i[0]}else r=this.parseParenExpression();if(this.options.preserveParens){var d=this.startNodeAt(e);return d.expression=r,this.finishNode(d,"ParenthesizedExpression")}return r.parenthesizedExpression=!0,r},i.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e),t,n)},i.parseParenItem=function(e){return e};var s=[];i.parseNew=function(){var e=this.startNode(),n=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(t.dot))return e.meta=n,e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raise(e.property.start,"The only valid meta property for new is new.target"),this.finishNode(e,"MetaProperty");var r=this.markPosition();return e.callee=this.parseSubscripts(this.parseExprAtom(),r,!0),e.arguments=this.eat(t.parenL)?this.parseExprList(t.parenR,!1):s,this.finishNode(e,"NewExpression")},i.parseTemplateElement=function(){var e=this.startNode();return e.value={raw:this.input.slice(this.start,this.end),cooked:this.value},this.next(),e.tail=this.type===t.backQuote,this.finishNode(e,"TemplateElement")},i.parseTemplate=function(){var e=this.startNode();this.next(),e.expressions=[];var n=this.parseTemplateElement();for(e.quasis=[n];!n.tail;)this.expect(t.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(t.braceR),e.quasis.push(n=this.parseTemplateElement());return this.next(),this.finishNode(e,"TemplateLiteral")},i.parseObj=function(e,n){var r=this.startNode(),l=!0,i={};for(r.properties=[],this.next();!this.eat(t.braceR);){if(l)l=!1;else if(this.expect(t.comma),this.afterTrailingComma(t.braceR))break;var s=this.startNode(),a=!1,o=!1,u=void 0;if(this.options.features["es7.objectRestSpread"]&&this.type===t.ellipsis)s=this.parseSpread(),s.type="SpreadProperty",r.properties.push(s);else{if(this.options.ecmaVersion>=6&&(s.method=!1,s.shorthand=!1,(e||n)&&(u=this.markPosition()),e||(a=this.eat(t.star))),this.options.features["es7.asyncFunctions"]&&this.isContextual("async")){(a||e)&&this.unexpected();var p=this.parseIdent();this.type===t.colon||this.type===t.parenL?s.key=p:(o=!0,this.parsePropertyName(s))}else this.parsePropertyName(s);this.parseObjPropValue(s,u,a,o,e,n),this.checkPropClash(s,i),r.properties.push(this.finishNode(s,"Property"))}}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")},i.parseObjPropValue=function(e,n,l,i,s,a){this.eat(t.colon)?(e.value=s?this.parseMaybeDefault():this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===t.parenL?(s&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(l,i)):this.options.ecmaVersion>=5&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&this.type!=t.comma&&this.type!=t.braceR?((l||i||s)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1)):this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?(e.kind="init",s?((this.isKeyword(e.key.name)||this.strict&&(r.strictBind(e.key.name)||r.strict(e.key.name))||!this.options.allowReserved&&this.isReservedWord(e.key.name))&&this.raise(e.key.start,"Binding "+e.key.name),e.value=this.parseMaybeDefault(n,e.key)):this.type===t.eq&&a?(a.start||(a.start=this.start),e.value=this.parseMaybeDefault(n,e.key)):e.value=e.key,e.shorthand=!0):this.unexpected()},i.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(t.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),void this.expect(t.bracketR);e.computed=!1}e.key=this.type===t.num||this.type===t.string?this.parseExprAtom():this.parseIdent(!0)},i.initFunction=function(e,t){e.id=null,this.options.ecmaVersion>=6&&(e.generator=!1,e.expression=!1),this.options.features["es7.asyncFunctions"]&&(e.async=!!t)},i.parseMethod=function(e,n){var r=this.startNode();return this.initFunction(r,n),this.expect(t.parenL),r.params=this.parseBindingList(t.parenR,!1,!1),this.options.ecmaVersion>=6&&(r.generator=e),this.parseFunctionBody(r),this.finishNode(r,"FunctionExpression")},i.parseArrowExpression=function(e,t,n){return this.initFunction(e,n),e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0),this.finishNode(e,"ArrowFunctionExpression")},i.parseFunctionBody=function(e,n){var r=n&&this.type!==t.braceL,l=this.inAsync;if(this.inAsync=e.async,r)e.body=this.parseMaybeAssign(),e.expression=!0;else{var i=this.inFunction,s=this.inGenerator,a=this.labels;this.inFunction=!0,this.inGenerator=e.generator,this.labels=[],e.body=this.parseBlock(!0),e.expression=!1,this.inFunction=i,this.inGenerator=s,this.labels=a}if(this.inAsync=l,this.strict||!r&&e.body.body.length&&this.isUseStrict(e.body.body[0])){var o={},u=this.strict;this.strict=!0,e.id&&this.checkLVal(e.id,!0);for(var p=0;p<e.params.length;p++)this.checkLVal(e.params[p],!0,o);this.strict=u}},i.parseExprList=function(e,n,r,l){for(var i=[],s=!0;!this.eat(e);){if(s)s=!1;else if(this.expect(t.comma),n&&this.afterTrailingComma(e))break;i.push(r&&this.type===t.comma?null:this.type===t.ellipsis?this.parseSpread(l):this.parseMaybeAssign(!1,l))}return i},i.parseIdent=function(e){var n=this.startNode();return e&&"never"==this.options.allowReserved&&(e=!1),this.type===t.name?(!e&&(!this.options.allowReserved&&this.isReservedWord(this.value)||this.strict&&r.strict(this.value)&&(this.options.ecmaVersion>=6||-1==this.input.slice(this.start,this.end).indexOf("\\")))&&this.raise(this.start,"The keyword '"+this.value+"' is reserved"),n.name=this.value):e&&this.type.keyword?n.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(n,"Identifier")},i.parseAwait=function(e){return(this.eat(t.semi)||this.canInsertSemicolon())&&this.unexpected(),e.all=this.eat(t.star),e.argument=this.parseMaybeAssign(!0),this.finishNode(e,"AwaitExpression")},i.parseYield=function(){var e=this.startNode();return this.next(),this.type==t.semi||this.canInsertSemicolon()||this.type!=t.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(t.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")},i.parseComprehension=function(e,n){for(e.blocks=[];this.type===t._for;){var r=this.startNode();this.next(),this.expect(t.parenL),r.left=this.parseBindingAtom(),this.checkLVal(r.left,!0),this.expectContextual("of"),r.right=this.parseExpression(),this.expect(t.parenR),e.blocks.push(this.finishNode(r,"ComprehensionBlock"))}return e.filter=this.eat(t._if)?this.parseParenExpression():null,e.body=this.parseExpression(),this.expect(n?t.parenR:t.bracketR),e.generator=n,this.finishNode(e,"ComprehensionExpression")}},{"./identifier":4,"./state":12,"./tokentype":16,"./util":17}],4:[function(e,t,n){"use strict";function r(e){function t(e){if(1==e.length)return n+="return str === "+JSON.stringify(e[0])+";";n+="switch(str){";for(var t=0;t<e.length;++t)n+="case "+JSON.stringify(e[t])+":";n+="return true}return false;"}e=e.split(" ");var n="",r=[];e:for(var l=0;l<e.length;++l){for(var i=0;i<r.length;++i)if(r[i][0].length==e[l].length){r[i].push(e[l]);continue e}r.push([e[l]])}if(r.length>3){r.sort(function(e,t){return t.length-e.length}),n+="switch(str.length){";for(var l=0;l<r.length;++l){var s=r[l];n+="case "+s[0].length+":",t(s)}n+="}"}else t(e);return new Function("str",n)}function l(e,t){for(var n=65536,r=0;r<t.length;r+=2){if(n+=t[r],n>e)return!1;if(n+=t[r+1],n>=e)return!0}}function i(e,t){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:65535>=e?e>=170&&d.test(String.fromCharCode(e)):t===!1?!1:l(e,h)}function s(e,t){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:65535>=e?e>=170&&f.test(String.fromCharCode(e)):t===!1?!1:l(e,h)||l(e,m)}n.isIdentifierStart=i,n.isIdentifierChar=s,n.__esModule=!0;var a={3:r("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),5:r("class enum extends super const export import"),6:r("enum await"),strict:r("implements interface let package private protected public static yield"),strictBind:r("eval arguments")};n.reservedWords=a;var o="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",u={5:r(o),6:r(o+" let const class extends export import yield super")};n.keywords=u;var p="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",c="·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_",d=new RegExp("["+p+"]"),f=new RegExp("["+p+c+"]");p=c=null;var h=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541],m=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239]},{}],5:[function(e,t,n){"use strict";function r(e,t){var n=s(t,e),r=n.options.locations?[n.pos,n.curPosition()]:n.pos;return n.nextToken(),n.parseTopLevel(n.options.program||n.startNodeAt(r))}function l(e,t,n){var r=s(n,e,t);return r.nextToken(),r.parseExpression()}function i(e,t){return s(t,e)}function s(e,t){return new o(p(e),String(t))}n.parse=r,n.parseExpressionAt=l,n.tokenizer=i,n.__esModule=!0;var a=e("./state"),o=a.Parser,u=e("./options"),p=u.getOptions;e("./parseutil"),e("./statement"),e("./lval"),e("./expression"),e("./lookahead"),n.Parser=a.Parser,n.plugins=a.plugins,n.defaultOptions=u.defaultOptions;var c=e("./location");n.SourceLocation=c.SourceLocation,n.getLineInfo=c.getLineInfo,n.Node=e("./node").Node;var d=e("./tokentype");n.TokenType=d.TokenType,n.tokTypes=d.types;var f=e("./tokencontext");n.TokContext=f.TokContext,n.tokContexts=f.types;var h=e("./identifier");n.isIdentifierChar=h.isIdentifierChar,n.isIdentifierStart=h.isIdentifierStart,n.Token=e("./tokenize").Token;var m=e("./whitespace");n.isNewLine=m.isNewLine,n.lineBreak=m.lineBreak,n.lineBreakG=m.lineBreakG,e("../plugins/flow"),e("../plugins/jsx");var g="1.0.0";n.version=g},{"../plugins/flow":1,"../plugins/jsx":2,"./expression":3,"./identifier":4,"./location":6,"./lookahead":7,"./lval":8,"./node":9,"./options":10,"./parseutil":11,"./state":12,"./statement":13,"./tokencontext":14,"./tokenize":15,"./tokentype":16,"./whitespace":18}],6:[function(e,t,n){"use strict";function r(e,t){for(var n=1,r=0;;){s.lastIndex=r;var l=s.exec(e);if(!(l&&l.index<t))return new a(n,t-r);++n,r=l.index+l[0].length}}var l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.getLineInfo=r,n.__esModule=!0;var i=e("./state").Parser,s=e("./whitespace").lineBreakG,a=n.Position=function(){function e(t,n){l(this,e),this.line=t,this.column=n}return e.prototype.offset=function(t){return new e(this.line,this.column+t)},e}(),o=(n.SourceLocation=function u(e,t,n){l(this,u),this.start=t,this.end=n,null!==e.sourceFile&&(this.source=e.sourceFile)},i.prototype);o.raise=function(e,t){var n=r(this.input,e);t+=" ("+n.line+":"+n.column+")";var l=new SyntaxError(t);throw l.pos=e,l.loc=n,l.raisedAt=this.pos,l},o.curPosition=function(){return new a(this.curLine,this.pos-this.lineStart)},o.markPosition=function(){return this.options.locations?[this.start,this.startLoc]:this.start}},{"./state":12,"./whitespace":18}],7:[function(e){"use strict";var t=e("./state").Parser,n=t.prototype,r=["lastTokStartLoc","lastTokEndLoc","lastTokStart","lastTokEnd","lineStart","startLoc","endLoc","start","pos","end","type","value"];n.getState=function(){for(var e={},t=0;t<r.length;t++){var n=r[t];e[n]=this[n]}return e},n.lookahead=function(){var e=this.getState();this.next();var t=this.getState();for(var n in e)this[n]=e[n];return t}},{"./state":12}],8:[function(e){"use strict";var t=e("./tokentype").types,n=e("./state").Parser,r=e("./identifier").reservedWords,l=e("./util").has,i=n.prototype;i.toAssignable=function(e,t){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=0;n<e.properties.length;n++){var r=e.properties[n];"init"!==r.kind&&this.raise(r.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(r.value,t)}break;case"ArrayExpression":e.type="ArrayPattern",this.toAssignableList(e.elements,t);break;case"AssignmentExpression":"="===e.operator?e.type="AssignmentPattern":this.raise(e.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!t)break;default:this.raise(e.start,"Assigning to rvalue")}return e},i.toAssignableList=function(e,t){var n=e.length;if(n){var r=e[n-1];if(r&&"RestElement"==r.type)--n;else if(r&&"SpreadElement"==r.type){r.type="RestElement";var l=r.argument;this.toAssignable(l,t),"Identifier"!==l.type&&"MemberExpression"!==l.type&&"ArrayPattern"!==l.type&&this.unexpected(l.start),--n}}for(var i=0;n>i;i++){var s=e[i];s&&this.toAssignable(s,t)}return e},i.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(e),this.finishNode(t,"SpreadElement")},i.parseRest=function(){var e=this.startNode();return this.next(),e.argument=this.type===t.name||this.type===t.bracketL?this.parseBindingAtom():this.unexpected(),this.finishNode(e,"RestElement")},i.parseBindingAtom=function(){if(this.options.ecmaVersion<6)return this.parseIdent();switch(this.type){case t.name:return this.parseIdent();case t.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(t.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case t.braceL:return this.parseObj(!0);default:this.unexpected()}},i.parseBindingList=function(e,n,r){for(var l=[],i=!0;!this.eat(e);)if(i?i=!1:this.expect(t.comma),n&&this.type===t.comma)l.push(null);else{if(r&&this.afterTrailingComma(e))break;if(this.type===t.ellipsis){l.push(this.parseAssignableListItemTypes(this.parseRest())),this.expect(e);break}var s=this.parseMaybeDefault();this.parseAssignableListItemTypes(s),l.push(this.parseMaybeDefault(null,s))}return l},i.parseAssignableListItemTypes=function(e){return e},i.parseMaybeDefault=function(e,n){if(e=e||this.markPosition(),n=n||this.parseBindingAtom(),!this.eat(t.eq))return n;var r=this.startNodeAt(e);return r.operator="=",r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,"AssignmentPattern")},i.checkLVal=function(e,t,n){switch(e.type){case"Identifier":this.strict&&(r.strictBind(e.name)||r.strict(e.name))&&this.raise(e.start,(t?"Binding ":"Assigning to ")+e.name+" in strict mode"),n&&(l(n,e.name)&&this.raise(e.start,"Argument name clash in strict mode"),n[e.name]=!0);break;case"MemberExpression":t&&this.raise(e.start,(t?"Binding":"Assigning to")+" member expression");break;case"ObjectPattern":for(var i=0;i<e.properties.length;i++){var s=e.properties[i];"Property"===s.type&&(s=s.value),this.checkLVal(s,t,n)}break;case"ArrayPattern":for(var i=0;i<e.elements.length;i++){var a=e.elements[i];a&&this.checkLVal(a,t,n)}break;case"AssignmentPattern":this.checkLVal(e.left,t,n);break;case"SpreadProperty":case"RestElement":this.checkLVal(e.argument,t,n);break;default:this.raise(e.start,(t?"Binding":"Assigning to")+" rvalue")}}},{"./identifier":4,"./state":12,"./tokentype":16,"./util":17}],9:[function(e,t,n){"use strict";var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.__esModule=!0;var l=e("./state").Parser,i=e("./location").SourceLocation,s=l.prototype,a=n.Node=function o(){r(this,o)};s.startNode=function(){var e=new a;return e.start=this.start,this.options.locations&&(e.loc=new i(this,this.startLoc)),this.options.directSourceFile&&(e.sourceFile=this.options.directSourceFile),this.options.ranges&&(e.range=[this.start,0]),e},s.startNodeAt=function(e){var t=new a,n=e;return this.options.locations&&(t.loc=new i(this,n[1]),n=e[0]),t.start=n,this.options.directSourceFile&&(t.sourceFile=this.options.directSourceFile),this.options.ranges&&(t.range=[n,0]),t},s.finishNode=function(e,t){return e.type=t,e.end=this.lastTokEnd,this.options.locations&&(e.loc.end=this.lastTokEndLoc),this.options.ranges&&(e.range[1]=this.lastTokEnd),e},s.finishNodeAt=function(e,t,n){return this.options.locations&&(e.loc.end=n[1],n=n[0]),e.type=t,e.end=n,this.options.ranges&&(e.range[1]=n),e}},{"./location":6,"./state":12}],10:[function(e,t,n){"use strict";function r(e){var t={};for(var n in u)t[n]=e&&s(e,n)?e[n]:u[n];return a(t.onToken)&&!function(){var e=t.onToken;t.onToken=function(t){return e.push(t)}}(),a(t.onComment)&&(t.onComment=l(t,t.onComment)),t}function l(e,t){return function(n,r,l,i,s,a){var u={type:n?"Block":"Line",value:r,start:l,end:i};e.locations&&(u.loc=new o(this,s,a)),e.ranges&&(u.range=[l,i]),t.push(u)}}n.getOptions=r,n.__esModule=!0;var i=e("./util"),s=i.has,a=i.isArray,o=e("./location").SourceLocation,u={ecmaVersion:5,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:!0,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{},features:{},strictMode:null};n.defaultOptions=u},{"./location":6,"./util":17}],11:[function(e){"use strict";var t=e("./tokentype").types,n=e("./state").Parser,r=e("./whitespace").lineBreak,l=n.prototype;l.isUseStrict=function(e){return this.options.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value},l.eat=function(e){return this.type===e?(this.next(),!0):!1},l.isContextual=function(e){return this.type===t.name&&this.value===e},l.eatContextual=function(e){return this.value===e&&this.eat(t.name)},l.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},l.canInsertSemicolon=function(){return this.type===t.eof||this.type===t.braceR||r.test(this.input.slice(this.lastTokEnd,this.start))},l.insertSemicolon=function(){return this.canInsertSemicolon()?(this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0):void 0},l.semicolon=function(){this.eat(t.semi)||this.insertSemicolon()||this.unexpected()},l.afterTrailingComma=function(e){return this.type==e?(this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),this.next(),!0):void 0},l.expect=function(e){this.eat(e)||this.unexpected()},l.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")}},{"./state":12,"./tokentype":16,"./whitespace":18}],12:[function(e,t,n){"use strict";function r(e,t,n){this.options=e,this.loadPlugins(this.options.plugins),this.sourceFile=this.options.sourceFile||null,this.isKeyword=s[this.options.ecmaVersion>=6?6:5],this.isReservedWord=i[this.options.ecmaVersion],this.input=t,n?(this.pos=n,this.lineStart=Math.max(0,this.input.lastIndexOf("\n",n)),this.curLine=this.input.slice(0,this.lineStart).split(u).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=o.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=null,this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===this.options.sourceType,this.strict=this.options.strictMode===!1?!1:this.inModule,this.inFunction=this.inGenerator=!1,this.labels=[],this.decorators=[],0===this.pos&&this.options.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2)}n.Parser=r,n.__esModule=!0;var l=e("./identifier"),i=l.reservedWords,s=l.keywords,a=e("./tokentype"),o=a.types,u=a.lineBreak;r.prototype.extend=function(e,t){this[e]=t(this[e])};var p={};n.plugins=p,r.prototype.loadPlugins=function(e){for(var t in e){var r=n.plugins[t];if(!r)throw new Error("Plugin '"+t+"' not found");r(this,e[t])}}},{"./identifier":4,"./tokentype":16}],13:[function(e){"use strict";var t=e("./tokentype").types,n=e("./state").Parser,r=e("./whitespace").lineBreak,l=n.prototype;l.parseTopLevel=function(e){var n=!0;for(e.body||(e.body=[]);this.type!==t.eof;){var r=this.parseStatement(!0,!0);e.body.push(r),n&&this.isUseStrict(r)&&this.setStrict(!0),n=!1}return this.next(),this.options.ecmaVersion>=6&&(e.sourceType=this.options.sourceType),this.finishNode(e,"Program")};var i={kind:"loop"},s={kind:"switch"};l.parseStatement=function(e,n){this.type===t.at&&this.parseDecorators(!0);var r=this.type,l=this.startNode();switch(r){case t._break:case t._continue:return this.parseBreakContinueStatement(l,r.keyword);case t._debugger:return this.parseDebuggerStatement(l);case t._do:return this.parseDoStatement(l);case t._for:return this.parseForStatement(l);case t._function:return!e&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(l);case t._class:return e||this.unexpected(),this.takeDecorators(l),this.parseClass(l,!0);case t._if:return this.parseIfStatement(l);case t._return:return this.parseReturnStatement(l);case t._switch:return this.parseSwitchStatement(l);case t._throw:return this.parseThrowStatement(l);case t._try:return this.parseTryStatement(l);case t._let:case t._const:e||this.unexpected();case t._var:return this.parseVarStatement(l,r);case t._while:return this.parseWhileStatement(l);case t._with:return this.parseWithStatement(l);case t.braceL:return this.parseBlock();case t.semi:return this.parseEmptyStatement(l);case t._export:case t._import:return this.options.allowImportExportEverywhere||(n||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),r===t._import?this.parseImport(l):this.parseExport(l);case t.name:if(this.options.features["es7.asyncFunctions"]&&"async"===this.value&&this.lookahead().type===t._function)return this.next(),this.expect(t._function),this.parseFunction(l,!0,!1,!0);default:var i=this.value,s=this.parseExpression();return r===t.name&&"Identifier"===s.type&&this.eat(t.colon)?this.parseLabeledStatement(l,i,s):this.parseExpressionStatement(l,s)}},l.takeDecorators=function(e){this.decorators.length&&(e.decorators=this.decorators,this.decorators=[])},l.parseDecorators=function(e){for(;this.type===t.at;)this.decorators.push(this.parseDecorator());e&&this.type===t._export||this.type!==t._class&&this.raise(this.start,"Leading decorators must be attached to a class declaration")},l.parseDecorator=function(){this.options.features["es7.decorators"]||this.unexpected();var e=this.startNode();return this.next(),e.expression=this.parseMaybeAssign(),this.finishNode(e,"Decorator")},l.parseBreakContinueStatement=function(e,n){var r="break"==n;this.next(),this.eat(t.semi)||this.insertSemicolon()?e.label=null:this.type!==t.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var l=0;l<this.labels.length;++l){var i=this.labels[l];if(null==e.label||i.name===e.label.name){if(null!=i.kind&&(r||"loop"===i.kind))break;if(e.label&&r)break}}return l===this.labels.length&&this.raise(e.start,"Unsyntactic "+n),this.finishNode(e,r?"BreakStatement":"ContinueStatement")},l.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")},l.parseDoStatement=function(e){var n=this.markPosition();if(this.next(),this.labels.push(i),e.body=this.parseStatement(!1),this.labels.pop(),this.options.features["es7.doExpressions"]&&this.type!==t._while){var r=this.startNodeAt(n);return r.expression=this.finishNode(e,"DoExpression"),this.semicolon(),this.finishNode(r,"ExpressionStatement")}return this.expect(t._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(t.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},l.parseForStatement=function(e){if(this.next(),this.labels.push(i),this.expect(t.parenL),this.type===t.semi)return this.parseFor(e,null);if(this.type===t._var||this.type===t._let||this.type===t._const){var n=this.startNode(),r=this.type;return this.next(),this.parseVar(n,!0,r),this.finishNode(n,"VariableDeclaration"),!(this.type===t._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==n.declarations.length||r!==t._var&&n.declarations[0].init?this.parseFor(e,n):this.parseForIn(e,n)}var l={start:0},s=this.parseExpression(!0,l);return this.type===t._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.toAssignable(s),this.checkLVal(s),this.parseForIn(e,s)):(l.start&&this.unexpected(l.start),this.parseFor(e,s))},l.parseFunctionStatement=function(e){return this.next(),this.parseFunction(e,!0)},l.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(!1),e.alternate=this.eat(t._else)?this.parseStatement(!1):null,this.finishNode(e,"IfStatement")},l.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(t.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},l.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(t.braceL),this.labels.push(s);for(var n,r;this.type!=t.braceR;)if(this.type===t._case||this.type===t._default){var l=this.type===t._case;n&&this.finishNode(n,"SwitchCase"),e.cases.push(n=this.startNode()),n.consequent=[],this.next(),l?n.test=this.parseExpression():(r&&this.raise(this.lastTokStart,"Multiple default clauses"),r=!0,n.test=null),this.expect(t.colon)}else n||this.unexpected(),n.consequent.push(this.parseStatement(!0));return n&&this.finishNode(n,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},l.parseThrowStatement=function(e){return this.next(),r.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var a=[];l.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===t._catch){var n=this.startNode();this.next(),this.expect(t.parenL),n.param=this.parseBindingAtom(),this.checkLVal(n.param,!0),this.expect(t.parenR),n.guard=null,n.body=this.parseBlock(),e.handler=this.finishNode(n,"CatchClause")}return e.guardedHandlers=a,e.finalizer=this.eat(t._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},l.parseVarStatement=function(e,t){return this.next(),this.parseVar(e,!1,t),this.semicolon(),this.finishNode(e,"VariableDeclaration")},l.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(i),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"WhileStatement")},l.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(!1),this.finishNode(e,"WithStatement")},l.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},l.parseLabeledStatement=function(e,n,r){for(var l=0;l<this.labels.length;++l)this.labels[l].name===n&&this.raise(r.start,"Label '"+n+"' is already declared");var i=this.type.isLoop?"loop":this.type===t._switch?"switch":null;return this.labels.push({name:n,kind:i}),e.body=this.parseStatement(!0),this.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},l.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},l.parseBlock=function(e){var n=this.startNode(),r=!0,l=void 0;for(n.body=[],this.expect(t.braceL);!this.eat(t.braceR);){var i=this.parseStatement(!0);n.body.push(i),r&&e&&this.isUseStrict(i)&&(l=this.strict,this.setStrict(this.strict=!0)),r=!1}return l===!1&&this.setStrict(!1),this.finishNode(n,"BlockStatement")},l.parseFor=function(e,n){return e.init=n,this.expect(t.semi),e.test=this.type===t.semi?null:this.parseExpression(),this.expect(t.semi),e.update=this.type===t.parenR?null:this.parseExpression(),this.expect(t.parenR),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"ForStatement")},l.parseForIn=function(e,n){var r=this.type===t._in?"ForInStatement":"ForOfStatement";return this.next(),e.left=n,e.right=this.parseExpression(),this.expect(t.parenR),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,r)},l.parseVar=function(e,n,r){for(e.declarations=[],e.kind=r.keyword;;){var l=this.startNode();if(this.parseVarHead(l),this.eat(t.eq)?l.init=this.parseMaybeAssign(n):r!==t._const||this.type===t._in||this.options.ecmaVersion>=6&&this.isContextual("of")?"Identifier"==l.id.type||n&&(this.type===t._in||this.isContextual("of"))?l.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(l,"VariableDeclarator")),!this.eat(t.comma))break}return e},l.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0)},l.parseFunction=function(e,n,r,l){return this.initFunction(e,l),this.options.ecmaVersion>=6&&(e.generator=this.eat(t.star)),(n||this.type===t.name)&&(e.id=this.parseIdent()),this.parseFunctionParams(e),this.parseFunctionBody(e,r),this.finishNode(e,n?"FunctionDeclaration":"FunctionExpression")},l.parseFunctionParams=function(e){this.expect(t.parenL),e.params=this.parseBindingList(t.parenR,!1,!1)
},l.parseClass=function(e,n){this.next(),this.parseClassId(e,n),this.parseClassSuper(e);var r=this.startNode();for(r.body=[],this.expect(t.braceL);!this.eat(t.braceR);)if(!this.eat(t.semi))if(this.type!==t.at){var l=this.startNode();this.takeDecorators(l);var i=this.eat(t.star),s=!1;this.parsePropertyName(l),this.type===t.parenL||l.computed||"Identifier"!==l.key.type||"static"!==l.key.name?l["static"]=!1:(i&&this.unexpected(),l["static"]=!0,i=this.eat(t.star),this.parsePropertyName(l)),i||"Identifier"!==l.key.type||l.computed||!this.isClassProperty()?(this.options.features["es7.asyncFunctions"]&&this.type!==t.parenL&&!l.computed&&"Identifier"===l.key.type&&"async"===l.key.name&&(s=!0,this.parsePropertyName(l)),l.kind="method",l.computed||i||("Identifier"===l.key.type?this.type===t.parenL||"get"!==l.key.name&&"set"!==l.key.name?l["static"]||"constructor"!==l.key.name||(l.kind="constructor"):(l.kind=l.key.name,this.parsePropertyName(l)):l["static"]||"Literal"!==l.key.type||"constructor"!==l.key.value||(l.kind="constructor")),"constructor"===l.kind&&l.decorators&&this.raise(l.start,"You can't attach decorators to a class constructor"),this.parseClassMethod(r,l,i,s)):r.body.push(this.parseClassProperty(l))}else this.decorators.push(this.parseDecorator());return this.decorators.length&&this.raise(this.start,"You have trailing decorators with no method"),e.body=this.finishNode(r,"ClassBody"),this.finishNode(e,n?"ClassDeclaration":"ClassExpression")},l.isClassProperty=function(){return this.type===t.eq||this.type===t.semi||this.canInsertSemicolon()},l.parseClassProperty=function(e){return this.type===t.eq?(this.options.features["es7.classProperties"]||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.finishNode(e,"ClassProperty")},l.parseClassMethod=function(e,t,n,r){t.value=this.parseMethod(n,r),e.body.push(this.finishNode(t,"MethodDefinition"))},l.parseClassId=function(e,n){e.id=this.type===t.name?this.parseIdent():n?this.unexpected():null},l.parseClassSuper=function(e){e.superClass=this.eat(t._extends)?this.parseExprSubscripts():null},l.parseExport=function(e){if(this.next(),this.type===t.star){var n=this.startNode();if(this.next(),!this.options.features["es7.exportExtensions"]||!this.eatContextual("as"))return this.parseExportFrom(e),this.finishNode(e,"ExportAllDeclaration");n.exported=this.parseIdent(),e.specifiers=[this.finishNode(n,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(e),this.parseExportFrom(e)}else if(this.isExportDefaultSpecifier()){var n=this.startNode();if(n.exported=this.parseIdent(!0),e.specifiers=[this.finishNode(n,"ExportDefaultSpecifier")],this.type===t.comma&&this.lookahead().type===t.star){this.expect(t.comma);var r=this.startNode();this.expect(t.star),this.expectContextual("as"),r.exported=this.parseIdent(),e.specifiers.push(this.finishNode(r,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(e);this.parseExportFrom(e)}else{if(this.eat(t._default)){var l=this.parseMaybeAssign(),i=!0;return("FunctionExpression"==l.type||"ClassExpression"==l.type)&&(i=!1,l.id&&(l.type="FunctionExpression"==l.type?"FunctionDeclaration":"ClassDeclaration")),e.declaration=l,i&&this.semicolon(),this.checkExport(e),this.finishNode(e,"ExportDefaultDeclaration")}this.type.keyword||this.shouldParseExportDeclaration()?(e.declaration=this.parseStatement(!0),e.specifiers=[],e.source=null):(e.declaration=null,e.specifiers=this.parseExportSpecifiers(),e.source=this.eatContextual("from")?this.type===t.string?this.parseExprAtom():this.unexpected():null,this.semicolon())}return this.checkExport(e),this.finishNode(e,"ExportNamedDeclaration")},l.isExportDefaultSpecifier=function(){if(this.type===t.name)return"type"!==this.value&&"async"!==this.value;if(this.type!==t._default)return!1;var e=this.lookahead();return e.type===t.comma||e.type===t.name&&"from"===e.value},l.parseExportSpecifiersMaybe=function(e){this.eat(t.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},l.parseExportFrom=function(e){this.expectContextual("from"),e.source=this.type===t.string?this.parseExprAtom():this.unexpected(),this.semicolon(),this.checkExport(e)},l.shouldParseExportDeclaration=function(){return this.options.features["es7.asyncFunctions"]&&this.isContextual("async")},l.checkExport=function(e){if(this.decorators.length){var t=e.declaration&&("ClassDeclaration"===e.declaration.type||"ClassExpression"===e.declaration.type);e.declaration&&t||this.raise(e.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(e.declaration)}},l.parseExportSpecifiers=function(){var e=[],n=!0;for(this.expect(t.braceL);!this.eat(t.braceR);){if(n)n=!1;else if(this.expect(t.comma),this.afterTrailingComma(t.braceR))break;var r=this.startNode();r.local=this.parseIdent(this.type===t._default),r.exported=this.eatContextual("as")?this.parseIdent(!0):r.local,e.push(this.finishNode(r,"ExportSpecifier"))}return e},l.parseImport=function(e){return this.next(),this.type===t.string?(e.specifiers=a,e.source=this.parseExprAtom(),e.kind=""):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.type===t.string?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},l.parseImportSpecifiers=function(e){var n=!0;if(this.type===t.name){var r=this.markPosition();if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdent(),r)),!this.eat(t.comma))return}if(this.type===t.star){var l=this.startNode();return this.next(),this.expectContextual("as"),l.local=this.parseIdent(),this.checkLVal(l.local,!0),void e.specifiers.push(this.finishNode(l,"ImportNamespaceSpecifier"))}for(this.expect(t.braceL);!this.eat(t.braceR);){if(n)n=!1;else if(this.expect(t.comma),this.afterTrailingComma(t.braceR))break;var l=this.startNode();l.imported=this.parseIdent(!0),l.local=this.eatContextual("as")?this.parseIdent():l.imported,this.checkLVal(l.local,!0),e.specifiers.push(this.finishNode(l,"ImportSpecifier"))}},l.parseImportSpecifierDefault=function(e,t){var n=this.startNodeAt(t);return n.local=e,this.checkLVal(n.local,!0),this.finishNode(n,"ImportDefaultSpecifier")}},{"./state":12,"./tokentype":16,"./whitespace":18}],14:[function(e,t,n){"use strict";var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.__esModule=!0;var l=e("./state").Parser,i=e("./tokentype").types,s=e("./whitespace").lineBreak,a=n.TokContext=function p(e,t,n,l){r(this,p),this.token=e,this.isExpr=t,this.preserveSpace=n,this.override=l},o={b_stat:new a("{",!1),b_expr:new a("{",!0),b_tmpl:new a("${",!0),p_stat:new a("(",!1),p_expr:new a("(",!0),q_tmpl:new a("`",!0,!0,function(e){return e.readTmplToken()}),f_expr:new a("function",!0)};n.types=o;var u=l.prototype;u.initialContext=function(){return[o.b_stat]},u.braceIsBlock=function(e){var t=void 0;return e===i.colon&&"{"==(t=this.curContext()).token?!t.isExpr:e===i._return?s.test(this.input.slice(this.lastTokEnd,this.start)):e===i._else||e===i.semi||e===i.eof?!0:e==i.braceL?this.curContext()===o.b_stat:!this.exprAllowed},u.updateContext=function(e){var t=void 0,n=this.type;n.keyword&&e==i.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},i.parenR.updateContext=i.braceR.updateContext=function(){if(1==this.context.length)return void(this.exprAllowed=!0);var e=this.context.pop();e===o.b_stat&&this.curContext()===o.f_expr?(this.context.pop(),this.exprAllowed=!1):this.exprAllowed=e===o.b_tmpl?!0:!e.isExpr},i.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?o.b_stat:o.b_expr),this.exprAllowed=!0},i.dollarBraceL.updateContext=function(){this.context.push(o.b_tmpl),this.exprAllowed=!0},i.parenL.updateContext=function(e){var t=e===i._if||e===i._for||e===i._with||e===i._while;this.context.push(t?o.p_stat:o.p_expr),this.exprAllowed=!0},i.incDec.updateContext=function(){},i._function.updateContext=function(){this.curContext()!==o.b_stat&&this.context.push(o.f_expr),this.exprAllowed=!1},i.backQuote.updateContext=function(){this.curContext()===o.q_tmpl?this.context.pop():this.context.push(o.q_tmpl),this.exprAllowed=!1}},{"./state":12,"./tokentype":16,"./whitespace":18}],15:[function(e,t,n){"use strict";function r(e){return 65535>=e?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}var l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.__esModule=!0;var i=e("./identifier"),s=i.isIdentifierStart,a=i.isIdentifierChar,o=e("./tokentype"),u=o.types,p=o.keywords,c=e("./state").Parser,d=e("./location").SourceLocation,f=e("./whitespace"),h=f.lineBreak,m=f.lineBreakG,g=f.isNewLine,y=f.nonASCIIwhitespace,b=n.Token=function S(e){l(this,S),this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new d(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},v=c.prototype;v.next=function(){this.options.onToken&&this.options.onToken(new b(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},v.getToken=function(){return this.next(),new b(this)},"undefined"!=typeof Symbol&&(v[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===u.eof,value:t}}}}),v.setStrict=function(e){if(this.strict=e,this.type===u.num||this.type===u.string){if(this.pos=this.start,this.options.locations)for(;this.pos<this.lineStart;)this.lineStart=this.input.lastIndexOf("\n",this.lineStart-2)+1,--this.curLine;this.nextToken()}},v.curContext=function(){return this.context[this.context.length-1]},v.nextToken=function(){var e=this.curContext();return e&&e.preserveSpace||this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length?this.finishToken(u.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},v.readToken=function(e){return s(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},v.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(55295>=e||e>=57344)return e;var t=this.input.charCodeAt(this.pos+1);return(e<<10)+t-56613888},v.skipBlockComment=function(){var e=this.options.onComment&&this.options.locations&&this.curPosition(),t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(-1===n&&this.raise(this.pos-2,"Unterminated comment"),this.pos=n+2,this.options.locations){m.lastIndex=t;for(var r=void 0;(r=m.exec(this.input))&&r.index<this.pos;)++this.curLine,this.lineStart=r.index+r[0].length}this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,n),t,this.pos,e,this.options.locations&&this.curPosition())},v.skipLineComment=function(e){for(var t=this.pos,n=this.options.onComment&&this.options.locations&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&10!==r&&13!==r&&8232!==r&&8233!==r;)++this.pos,r=this.input.charCodeAt(this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,n,this.options.locations&&this.curPosition())},v.skipSpace=function(){for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);if(32===e)++this.pos;else if(13===e){++this.pos;var t=this.input.charCodeAt(this.pos);10===t&&++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos)}else if(10===e||8232===e||8233===e)++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);else if(e>8&&14>e)++this.pos;else if(47===e){var t=this.input.charCodeAt(this.pos+1);if(42===t)this.skipBlockComment();else{if(47!==t)break;this.skipLineComment(2)}}else if(160===e)++this.pos;else{if(!(e>=5760&&y.test(String.fromCharCode(e))))break;++this.pos}}},v.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},v.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&57>=e)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(u.ellipsis)):(++this.pos,this.finishToken(u.dot))},v.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(u.assign,2):this.finishOp(u.slash,1)},v.readToken_mult_modulo=function(e){var t=42===e?u.star:u.modulo,n=1,r=this.input.charCodeAt(this.pos+1);return 42===r&&(n++,r=this.input.charCodeAt(this.pos+2),t=u.exponent),61===r&&(n++,t=u.assign),this.finishOp(t,n)},v.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.finishOp(124===e?u.logicalOR:u.logicalAND,2):61===t?this.finishOp(u.assign,2):this.finishOp(124===e?u.bitwiseOR:u.bitwiseAND,1)},v.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);return 61===e?this.finishOp(u.assign,2):this.finishOp(u.bitwiseXOR,1)},v.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45==t&&62==this.input.charCodeAt(this.pos+2)&&h.test(this.input.slice(this.lastTokEnd,this.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(u.incDec,2):61===t?this.finishOp(u.assign,2):this.finishOp(u.plusMin,1)},v.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+n)?this.finishOp(u.assign,n+1):this.finishOp(u.bitShift,n)):33==t&&60==e&&45==this.input.charCodeAt(this.pos+2)&&45==this.input.charCodeAt(this.pos+3)?(this.inModule&&unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===t&&(n=61===this.input.charCodeAt(this.pos+2)?3:2),this.finishOp(u.relational,n))},v.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(u.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(u.arrow)):this.finishOp(61===e?u.eq:u.prefix,1)},v.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(u.parenL);case 41:return++this.pos,this.finishToken(u.parenR);case 59:return++this.pos,this.finishToken(u.semi);case 44:return++this.pos,this.finishToken(u.comma);case 91:return++this.pos,this.finishToken(u.bracketL);case 93:return++this.pos,this.finishToken(u.bracketR);case 123:return++this.pos,this.finishToken(u.braceL);case 125:return++this.pos,this.finishToken(u.braceR);case 58:return++this.pos,this.finishToken(u.colon);case 63:return++this.pos,this.finishToken(u.question);case 64:return++this.pos,this.finishToken(u.at);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(u.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(u.prefix,1)}this.raise(this.pos,"Unexpected character '"+r(e)+"'")},v.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)};var x=!1;try{new RegExp("","u"),x=!0}catch(E){}v.readRegexp=function(){for(var e=void 0,t=void 0,n=this.pos;;){this.pos>=this.input.length&&this.raise(n,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(h.test(r)&&this.raise(n,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var l=this.input.slice(n,this.pos);++this.pos;var i=this.readWord1(),s=l;if(i){var a=/^[gmsiy]*$/;this.options.ecmaVersion>=6&&(a=/^[gmsiyu]*$/),a.test(i)||this.raise(n,"Invalid regular expression flag"),i.indexOf("u")>=0&&!x&&(s=s.replace(/\\u([a-fA-F0-9]{4})|\\u\{([0-9a-fA-F]+)\}|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"))}try{new RegExp(s)}catch(o){o instanceof SyntaxError&&this.raise(n,"Error parsing regular expression: "+o.message),this.raise(o)}var p=void 0;try{p=new RegExp(l,i)}catch(c){p=null}return this.finishToken(u.regexp,{pattern:l,flags:i,value:p})},v.readInt=function(e,t){for(var n=this.pos,r=0,l=0,i=null==t?1/0:t;i>l;++l){var s=this.input.charCodeAt(this.pos),a=void 0;if(a=s>=97?s-97+10:s>=65?s-65+10:s>=48&&57>=s?s-48:1/0,a>=e)break;++this.pos,r=r*e+a}return this.pos===n||null!=t&&this.pos-n!==t?null:r},v.readRadixNumber=function(e){this.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.start+2,"Expected number in radix "+e),s(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,t)},v.readNumber=function(e){var t=this.pos,n=!1,r=48===this.input.charCodeAt(this.pos);e||null!==this.readInt(10)||this.raise(t,"Invalid number"),46===this.input.charCodeAt(this.pos)&&(++this.pos,this.readInt(10),n=!0);var l=this.input.charCodeAt(this.pos);(69===l||101===l)&&(l=this.input.charCodeAt(++this.pos),(43===l||45===l)&&++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),n=!0),s(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i=this.input.slice(t,this.pos),a=void 0;return n?a=parseFloat(i):r&&1!==i.length?/[89]/.test(i)||this.strict?this.raise(t,"Invalid number"):a=parseInt(i,8):a=parseInt(i,10),this.finishToken(u.num,a)},v.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t=void 0;return 123===e?(this.options.ecmaVersion<6&&this.unexpected(),++this.pos,t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,t>1114111&&this.unexpected()):t=this.readHexChar(4),t},v.readString=function(e){for(var t="",n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(),n=this.pos):(g(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(u.string,t)},v.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var n=this.input.charCodeAt(this.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.pos+1))return this.pos===this.start&&this.type===u.template?36===n?(this.pos+=2,this.finishToken(u.dollarBraceL)):(++this.pos,this.finishToken(u.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(u.template,e));92===n?(e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(),t=this.pos):g(n)?(e+=this.input.slice(t,this.pos),++this.pos,13===n&&10===this.input.charCodeAt(this.pos)?(++this.pos,e+="\n"):e+=String.fromCharCode(n),this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos):++this.pos}},v.readEscapedChar=function(){var e=this.input.charCodeAt(++this.pos),t=/^[0-7]+/.exec(this.input.slice(this.pos,this.pos+3));for(t&&(t=t[0]);t&&parseInt(t,8)>255;)t=t.slice(0,-1);if("0"===t&&(t=null),++this.pos,t)return this.strict&&this.raise(this.pos-2,"Octal literal in strict mode"),this.pos+=t.length-1,String.fromCharCode(parseInt(t,8));switch(e){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return r(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";default:return String.fromCharCode(e)}},v.readHexChar=function(e){var t=this.readInt(16,e);return null===t&&this.raise(this.start,"Bad character escape sequence"),t};var _;v.readWord1=function(){_=!1;for(var e="",t=!0,n=this.pos,l=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(a(i,l))this.pos+=65535>=i?1:2;else{if(92!==i)break;_=!0,e+=this.input.slice(n,this.pos);var o=this.pos;117!=this.input.charCodeAt(++this.pos)&&this.raise(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var u=this.readCodePoint();(t?s:a)(u,l)||this.raise(o,"Invalid Unicode escape"),e+=r(u),n=this.pos}t=!1}return e+this.input.slice(n,this.pos)},v.readWord=function(){var e=this.readWord1(),t=u.name;return(this.options.ecmaVersion>=6||!_)&&this.isKeyword(e)&&(t=p[e]),this.finishToken(t,e)}},{"./identifier":4,"./location":6,"./state":12,"./tokentype":16,"./whitespace":18}],16:[function(e,t,n){"use strict";function r(e,t){return new s(e,{beforeExpr:!0,binop:t})}function l(e){var t=void 0===arguments[1]?{}:arguments[1];t.keyword=e,p[e]=u["_"+e]=new s(e,t)}var i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.__esModule=!0;var s=n.TokenType=function c(e){var t=void 0===arguments[1]?{}:arguments[1];i(this,c),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.rightAssociative=!!t.rightAssociative,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null},a={beforeExpr:!0},o={startsExpr:!0},u={num:new s("num",o),regexp:new s("regexp",o),string:new s("string",o),name:new s("name",o),eof:new s("eof"),bracketL:new s("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new s("]"),braceL:new s("{",{beforeExpr:!0,startsExpr:!0}),braceR:new s("}"),parenL:new s("(",{beforeExpr:!0,startsExpr:!0}),parenR:new s(")"),comma:new s(",",a),semi:new s(";",a),colon:new s(":",a),dot:new s("."),question:new s("?",a),arrow:new s("=>",a),template:new s("template"),ellipsis:new s("...",a),backQuote:new s("`",o),dollarBraceL:new s("${",{beforeExpr:!0,startsExpr:!0}),at:new s("@"),eq:new s("=",{beforeExpr:!0,isAssign:!0}),assign:new s("_=",{beforeExpr:!0,isAssign:!0}),incDec:new s("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new s("prefix",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:r("||",1),logicalAND:r("&&",2),bitwiseOR:r("|",3),bitwiseXOR:r("^",4),bitwiseAND:r("&",5),equality:r("==/!=",6),relational:r("</>",7),bitShift:r("<</>>",8),plusMin:new s("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:r("%",10),star:r("*",10),slash:r("/",10),exponent:new s("**",{beforeExpr:!0,binop:11,rightAssociative:!0})};n.types=u;var p={};n.keywords=p,l("break"),l("case",a),l("catch"),l("continue"),l("debugger"),l("default"),l("do",{isLoop:!0}),l("else",a),l("finally"),l("for",{isLoop:!0}),l("function"),l("if"),l("return",a),l("switch"),l("throw",a),l("try"),l("var"),l("let"),l("const"),l("while",{isLoop:!0}),l("with"),l("new",{beforeExpr:!0,startsExpr:!0}),l("this",o),l("super",o),l("class"),l("extends",a),l("export"),l("import"),l("yield",{beforeExpr:!0,startsExpr:!0}),l("null",o),l("true",o),l("false",o),l("in",{beforeExpr:!0,binop:7}),l("instanceof",{beforeExpr:!0,binop:7}),l("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),l("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),l("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},{}],17:[function(e,t,n){"use strict";function r(e){return"[object Array]"===Object.prototype.toString.call(e)}function l(e,t){return Object.prototype.hasOwnProperty.call(e,t)}n.isArray=r,n.has=l,n.__esModule=!0},{}],18:[function(e,t,n){"use strict";function r(e){return 10===e||13===e||8232===e||8233==e}n.isNewLine=r,n.__esModule=!0;var l=/\r\n?|\n|\u2028|\u2029/;n.lineBreak=l;var i=new RegExp(l.source,"g");n.lineBreakG=i;var s=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;n.nonASCIIwhitespace=s},{}],19:[function(e,t){(function(n){"use strict";var r=t.exports=e("../transformation");r.options=e("../transformation/file/options"),r.version=e("../../../package").version,r.transform=r,r.run=function(e){var t=void 0===arguments[1]?{}:arguments[1];return t.sourceMaps="inline",new Function(r(e,t).code)()},r.load=function(e,t,l,i){var s=void 0===arguments[2]?{}:arguments[2],a=s;a.filename||(a.filename=e);var o=n.ActiveXObject?new n.ActiveXObject("Microsoft.XMLHTTP"):new n.XMLHttpRequest;o.open("GET",e,!0),"overrideMimeType"in o&&o.overrideMimeType("text/plain"),o.onreadystatechange=function(){if(4===o.readyState){var n=o.status;if(0!==n&&200!==n)throw new Error("Could not load "+e);var l=[o.responseText,s];i||r.run.apply(r,l),t&&t(l)}},o.send(null)};var l=function(){for(var e=[],t=["text/ecmascript-6","text/6to5","text/babel","module"],l=0,i=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(){var t=e[l];t instanceof Array&&(r.run.apply(r,t),l++,i())}),s=function(t,n){var l={};t.src?r.load(t.src,function(t){e[n]=t,i()},l,!0):(l.filename="embedded",e[n]=[t.innerHTML,l])},a=n.document.getElementsByTagName("script"),o=0;o<a.length;++o){var u=a[o];t.indexOf(u.type)>=0&&e.push(u)}for(o in e)s(e[o],o);i()};n.addEventListener?n.addEventListener("DOMContentLoaded",l,!1):n.attachEvent&&n.attachEvent("onload",l)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../../package":454,"../transformation":63,"../transformation/file/options":49}],20:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("repeating")),i=n(e("trim-right")),s=n(e("lodash/lang/isBoolean")),a=n(e("lodash/collection/includes")),o=n(e("lodash/lang/isNumber")),u=function(){function e(t,n){r(this,e),this.position=t,this._indent=n.indent.base,this.format=n,this.buf=""}return e.prototype.get=function(){return i(this.buf)},e.prototype.getIndent=function(){return this.format.compact||this.format.concise?"":l(this.format.indent.style,this._indent)},e.prototype.indentSize=function(){return this.getIndent().length},e.prototype.indent=function(){this._indent++},e.prototype.dedent=function(){this._indent--},e.prototype.semicolon=function(){this.push(";")},e.prototype.ensureSemicolon=function(){this.isLast(";")||this.semicolon()},e.prototype.rightBrace=function(){this.newline(!0),this.push("}")},e.prototype.keyword=function(e){this.push(e),this.space()},e.prototype.space=function(){this.format.compact||!this.buf||this.isLast(" ")||this.isLast("\n")||this.push(" ")},e.prototype.removeLast=function(e){this.format.compact||this.isLast(e)&&(this.buf=this.buf.substr(0,this.buf.length-1),this.position.unshift(e))},e.prototype.newline=function(e,t){if(!this.format.compact){if(this.format.concise)return void this.space();if(t||(t=!1),o(e)){if(e=Math.min(2,e),(this.endsWith("{\n")||this.endsWith(":\n"))&&e--,0>=e)return;for(;e>0;)this._newline(t),e--}else s(e)&&(t=e),this._newline(t)}},e.prototype._newline=function(e){this.endsWith("\n\n")||(e&&this.isLast("\n")&&this.removeLast("\n"),this.removeLast(" "),this._removeSpacesAfterLastNewline(),this._push("\n"))},e.prototype._removeSpacesAfterLastNewline=function(){var e=this.buf.lastIndexOf("\n");if(-1!==e){for(var t=this.buf.length-1;t>e&&" "===this.buf[t];)t--;t===e&&(this.buf=this.buf.substring(0,t+1))}},e.prototype.push=function(e,t){if(!this.format.compact&&this._indent&&!t&&"\n"!==e){var n=this.getIndent();e=e.replace(/\n/g,"\n"+n),this.isLast("\n")&&this._push(n)}this._push(e)},e.prototype._push=function(e){this.position.push(e),this.buf+=e},e.prototype.endsWith=function(e){return this.buf.slice(-e.length)===e},e.prototype.isLast=function(e){if(this.format.compact)return!1;var t=this.buf,n=t[t.length-1];return Array.isArray(e)?a(e,n):e===n},e}();t.exports=u},{"lodash/collection/includes":319,"lodash/lang/isBoolean":393,"lodash/lang/isNumber":397,repeating:437,"trim-right":453}],21:[function(e,t,n){"use strict";function r(e,t){t(e.program)}function l(e,t){t.sequence(e.body)}function i(e,t){0===e.body.length?this.push("{}"):(this.push("{"),this.newline(),t.sequence(e.body,{indent:!0}),this.removeLast("\n"),this.rightBrace())}n.File=r,n.Program=l,n.BlockStatement=i,n.__esModule=!0},{}],22:[function(e,t,n){"use strict";function r(e,t){t.list(e.decorators),this.push("class"),e.id&&(this.space(),t(e.id)),t(e.typeParameters),e.superClass&&(this.push(" extends "),t(e.superClass),t(e.superTypeParameters)),e["implements"]&&(this.push(" implements "),t.join(e["implements"],{separator:", "})),this.space(),t(e.body)}function l(e,t){0===e.body.length?this.push("{}"):(this.push("{"),this.newline(),this.indent(),t.sequence(e.body),this.dedent(),this.rightBrace())}function i(e,t){t.list(e.decorators),e["static"]&&this.push("static "),t(e.key),t(e.typeAnnotation),e.value&&(this.space(),this.push("="),this.space(),t(e.value)),this.semicolon()}function s(e,t){t.list(e.decorators),e["static"]&&this.push("static "),this._method(e,t)}n.ClassDeclaration=r,n.ClassBody=l,n.ClassProperty=i,n.MethodDefinition=s,n.__esModule=!0,n.ClassExpression=r},{}],23:[function(e,t,n){"use strict";function r(e,t){this.keyword("for"),this.push("("),t(e.left),this.push(" of "),t(e.right),this.push(")")}function l(e,t){this.push(e.generator?"(":"["),t.join(e.blocks,{separator:" "}),this.space(),e.filter&&(this.keyword("if"),this.push("("),t(e.filter),this.push(")"),this.space()),t(e.body),this.push(e.generator?")":"]")}n.ComprehensionBlock=r,n.ComprehensionExpression=l,n.__esModule=!0},{}],24:[function(e,t,n){"use strict";function r(e,t){var n=/[a-z]$/.test(e.operator),r=e.argument;(E.isUpdateExpression(r)||E.isUnaryExpression(r))&&(n=!0),E.isUnaryExpression(r)&&"!"===r.operator&&(n=!1),this.push(e.operator),n&&this.push(" "),t(e.argument)}function l(e,t){this.push("do"),this.space(),t(e.body)}function i(e,t){e.prefix?(this.push(e.operator),t(e.argument)):(t(e.argument),this.push(e.operator))}function s(e,t){t(e.test),this.space(),this.push("?"),this.space(),t(e.consequent),this.space(),this.push(":"),this.space(),t(e.alternate)}function a(e,t){this.push("new "),t(e.callee),this.push("("),t.list(e.arguments),this.push(")")}function o(e,t){t.list(e.expressions)}function u(){this.push("this")}function p(){this.push("super")}function c(e,t){this.push("@"),t(e.expression)}function d(e,t){t(e.callee),this.push("(");var n=",";e._prettyCall?(n+="\n",this.newline(),this.indent()):n+=" ",t.list(e.arguments,{separator:n}),e._prettyCall&&(this.newline(),this.dedent()),this.push(")")}function f(){this.semicolon()}function h(e,t){t(e.expression),this.semicolon()}function m(e,t){t(e.left),this.push(" "),this.push(e.operator),this.push(" "),t(e.right)}function g(e,t){var n=e.object;if(t(n),!e.computed&&E.isMemberExpression(e.property))throw new TypeError("Got a MemberExpression for MemberExpression property");var r=e.computed;E.isLiteral(e.property)&&x(e.property.value)&&(r=!0),r?(this.push("["),t(e.property),this.push("]")):(E.isLiteral(n)&&v(n.value)&&!w.test(n.value.toString())&&this.push("."),this.push("."),t(e.property))}var y=function(e){return e&&e.__esModule?e:{"default":e}},b=function(e){return e&&e.__esModule?e["default"]:e};n.UnaryExpression=r,n.DoExpression=l,n.UpdateExpression=i,n.ConditionalExpression=s,n.NewExpression=a,n.SequenceExpression=o,n.ThisExpression=u,n.Super=p,n.Decorator=c,n.CallExpression=d,n.EmptyStatement=f,n.ExpressionStatement=h,n.AssignmentExpression=m,n.MemberExpression=g,n.__esModule=!0;var v=b(e("is-integer")),x=b(e("lodash/lang/isNumber")),E=y(e("../../types")),_=function(e){return function(t,n){this.push(e),(t.delegate||t.all)&&this.push("*"),t.argument&&(this.space(),n(t.argument))}},S=_("yield");
n.YieldExpression=S;var I=_("await");n.AwaitExpression=I,n.BinaryExpression=m,n.LogicalExpression=m,n.AssignmentPattern=m;var w=/e/i;n.MetaProperty=g},{"../../types":153,"is-integer":303,"lodash/lang/isNumber":397}],25:[function(e,t,n){"use strict";function r(){this.push("any")}function l(e,t){t(e.elementType),this.push("["),this.push("]")}function i(){this.push("bool")}function s(e,t){this.push("declare class "),this._interfaceish(e,t)}function a(e,t){this.push("declare function "),t(e.id),t(e.id.typeAnnotation.typeAnnotation),this.semicolon()}function o(e,t){this.push("declare module "),t(e.id),this.space(),t(e.body)}function u(e,t){this.push("declare var "),t(e.id),t(e.id.typeAnnotation),this.semicolon()}function p(e,t,n){t(e.typeParameters),this.push("("),t.list(e.params),e.rest&&(e.params.length&&(this.push(","),this.space()),this.push("..."),t(e.rest)),this.push(")"),"ObjectTypeProperty"===n.type||"ObjectTypeCallProperty"===n.type||"DeclareFunction"===n.type?this.push(":"):(this.space(),this.push("=>")),this.space(),t(e.returnType)}function c(e,t){t(e.name),e.optional&&this.push("?"),this.push(":"),this.space(),t(e.typeAnnotation)}function d(e,t){t(e.id),t(e.typeParameters)}function f(e,t){t(e.id),t(e.typeParameters),e["extends"].length&&(this.push(" extends "),t.join(e["extends"],{separator:", "})),this.space(),t(e.body)}function h(e,t){this.push("interface "),this._interfaceish(e,t)}function m(e,t){t.join(e.types,{separator:" & "})}function g(e,t){this.push("?"),t(e.typeAnnotation)}function y(){this.push("number")}function b(e){this._stringLiteral(e.value)}function v(){this.push("string")}function x(e,t){this.push("["),t.join(e.types,{separator:", "}),this.push("]")}function E(e,t){this.push("typeof "),t(e.argument)}function _(e,t){this.push("type "),t(e.id),t(e.typeParameters),this.space(),this.push("="),this.space(),t(e.right),this.semicolon()}function S(e,t){this.push(":"),this.space(),e.optional&&this.push("?"),t(e.typeAnnotation)}function I(e,t){this.push("<"),t.join(e.params,{separator:", "}),this.push(">")}function w(e,t){var n=this;this.push("{");var r=e.properties.concat(e.callProperties,e.indexers);r.length&&(this.space(),t.list(r,{separator:!1,indent:!0,iterator:function(){1!==r.length&&(n.semicolon(),n.space())}}),this.space()),this.push("}")}function k(e,t){e["static"]&&this.push("static "),t(e.value)}function A(e,t){e["static"]&&this.push("static "),this.push("["),t(e.id),this.push(":"),this.space(),t(e.key),this.push("]"),this.push(":"),this.space(),t(e.value)}function C(e,t){e["static"]&&this.push("static "),t(e.key),e.optional&&this.push("?"),O.isFunctionTypeAnnotation(e.value)||(this.push(":"),this.space()),t(e.value)}function T(e,t){t(e.qualification),this.push("."),t(e.id)}function j(e,t){t.join(e.types,{separator:" | "})}function M(e,t){this.push("("),t(e.expression),t(e.typeAnnotation),this.push(")")}function P(){this.push("void")}var L=function(e){return e&&e.__esModule?e:{"default":e}};n.AnyTypeAnnotation=r,n.ArrayTypeAnnotation=l,n.BooleanTypeAnnotation=i,n.DeclareClass=s,n.DeclareFunction=a,n.DeclareModule=o,n.DeclareVariable=u,n.FunctionTypeAnnotation=p,n.FunctionTypeParam=c,n.InterfaceExtends=d,n._interfaceish=f,n.InterfaceDeclaration=h,n.IntersectionTypeAnnotation=m,n.NullableTypeAnnotation=g,n.NumberTypeAnnotation=y,n.StringLiteralTypeAnnotation=b,n.StringTypeAnnotation=v,n.TupleTypeAnnotation=x,n.TypeofTypeAnnotation=E,n.TypeAlias=_,n.TypeAnnotation=S,n.TypeParameterInstantiation=I,n.ObjectTypeAnnotation=w,n.ObjectTypeCallProperty=k,n.ObjectTypeIndexer=A,n.ObjectTypeProperty=C,n.QualifiedTypeIdentifier=T,n.UnionTypeAnnotation=j,n.TypeCastExpression=M,n.VoidTypeAnnotation=P,n.__esModule=!0;var O=L(e("../../types"));n.ClassImplements=d,n.GenericTypeAnnotation=d,n.TypeParameterDeclaration=I},{"../../types":153}],26:[function(e,t,n){"use strict";function r(e,t){t(e.name),e.value&&(this.push("="),t(e.value))}function l(e){this.push(e.name)}function i(e,t){t(e.namespace),this.push(":"),t(e.name)}function s(e,t){t(e.object),this.push("."),t(e.property)}function a(e,t){this.push("{..."),t(e.argument),this.push("}")}function o(e,t){this.push("{"),t(e.expression),this.push("}")}function u(e,t){var n=this,r=e.openingElement;t(r),r.selfClosing||(this.indent(),m(e.children,function(e){g.isLiteral(e)?n.push(e.value):t(e)}),this.dedent(),t(e.closingElement))}function p(e,t){this.push("<"),t(e.name),e.attributes.length>0&&(this.push(" "),t.join(e.attributes,{separator:" "})),this.push(e.selfClosing?" />":">")}function c(e,t){this.push("</"),t(e.name),this.push(">")}function d(){}var f=function(e){return e&&e.__esModule?e:{"default":e}},h=function(e){return e&&e.__esModule?e["default"]:e};n.JSXAttribute=r,n.JSXIdentifier=l,n.JSXNamespacedName=i,n.JSXMemberExpression=s,n.JSXSpreadAttribute=a,n.JSXExpressionContainer=o,n.JSXElement=u,n.JSXOpeningElement=p,n.JSXClosingElement=c,n.JSXEmptyExpression=d,n.__esModule=!0;var m=h(e("lodash/collection/each")),g=f(e("../../types"))},{"../../types":153,"lodash/collection/each":316}],27:[function(e,t,n){"use strict";function r(e,t){var n=this;t(e.typeParameters),this.push("("),t.list(e.params,{iterator:function(e){e.optional&&n.push("?"),t(e.typeAnnotation)}}),this.push(")"),e.returnType&&t(e.returnType)}function l(e,t){var n=e.value,r=e.kind,l=e.key;("method"===r||"init"===r)&&n.generator&&this.push("*"),("get"===r||"set"===r)&&this.push(r+" "),n.async&&this.push("async "),e.computed?(this.push("["),t(l),this.push("]")):t(l),this._params(n,t),this.push(" "),t(n.body)}function i(e,t){e.async&&this.push("async "),this.push("function"),e.generator&&this.push("*"),e.id?(this.push(" "),t(e.id)):this.space(),this._params(e,t),this.space(),t(e.body)}function s(e,t){e.async&&this.push("async "),1===e.params.length&&o.isIdentifier(e.params[0])?t(e.params[0]):this._params(e,t),this.push(" => "),t(e.body)}var a=function(e){return e&&e.__esModule?e:{"default":e}};n._params=r,n._method=l,n.FunctionExpression=i,n.ArrowFunctionExpression=s,n.__esModule=!0;var o=a(e("../../types"));n.FunctionDeclaration=i},{"../../types":153}],28:[function(e,t,n){"use strict";function r(e,t){t(e.imported),e.local&&e.local!==e.imported&&(this.push(" as "),t(e.local))}function l(e,t){t(e.local)}function i(e,t){t(e.exported)}function s(e,t){t(e.local),e.exported&&e.local!==e.exported&&(this.push(" as "),t(e.exported))}function a(e,t){this.push("* as "),t(e.exported)}function o(e,t){this.push("export *"),e.exported&&(this.push(" as "),t(e.exported)),this.push(" from "),t(e.source),this.semicolon()}function u(e,t){this.push("export "),c.call(this,e,t)}function p(e,t){this.push("export default "),c.call(this,e,t)}function c(e,t){var n=e.specifiers;if(e.declaration){var r=e.declaration;if(t(r),g.isStatement(r)||g.isFunction(r)||g.isClass(r))return}else{var l=n[0],i=!1;(g.isExportDefaultSpecifier(l)||g.isExportNamespaceSpecifier(l))&&(i=!0,t(n.shift()),n.length&&this.push(", ")),(n.length||!n.length&&!i)&&(this.push("{"),n.length&&(this.space(),t.join(n,{separator:", "}),this.space()),this.push("}")),e.source&&(this.push(" from "),t(e.source))}this.ensureSemicolon()}function d(e,t){this.push("import "),e.isType&&this.push("type ");var n=e.specifiers;if(n&&n.length){var r=e.specifiers[0];(g.isImportDefaultSpecifier(r)||g.isImportNamespaceSpecifier(r))&&(t(e.specifiers.shift()),e.specifiers.length&&this.push(", ")),e.specifiers.length&&(this.push("{"),this.space(),t.join(e.specifiers,{separator:", "}),this.space(),this.push("}")),this.push(" from ")}t(e.source),this.semicolon()}function f(e,t){this.push("* as "),t(e.local)}var h=function(e){return e&&e.__esModule?e:{"default":e}},m=function(e){return e&&e.__esModule?e["default"]:e};n.ImportSpecifier=r,n.ImportDefaultSpecifier=l,n.ExportDefaultSpecifier=i,n.ExportSpecifier=s,n.ExportNamespaceSpecifier=a,n.ExportAllDeclaration=o,n.ExportNamedDeclaration=u,n.ExportDefaultDeclaration=p,n.ImportDeclaration=d,n.ImportNamespaceSpecifier=f,n.__esModule=!0;var g=(m(e("lodash/collection/each")),h(e("../../types")))},{"../../types":153,"lodash/collection/each":316}],29:[function(e,t,n){"use strict";function r(e,t){this.keyword("with"),this.push("("),t(e.object),this.push(")"),t.block(e.body)}function l(e,t){this.keyword("if"),this.push("("),t(e.test),this.push(")"),this.space(),t.indentOnComments(e.consequent),e.alternate&&(this.isLast("}")&&this.space(),this.push("else "),t.indentOnComments(e.alternate))}function i(e,t){this.keyword("for"),this.push("("),t(e.init),this.push(";"),e.test&&(this.push(" "),t(e.test)),this.push(";"),e.update&&(this.push(" "),t(e.update)),this.push(")"),t.block(e.body)}function s(e,t){this.keyword("while"),this.push("("),t(e.test),this.push(")"),t.block(e.body)}function a(e,t){this.keyword("do"),t(e.body),this.space(),this.keyword("while"),this.push("("),t(e.test),this.push(");")}function o(e,t){t(e.label),this.push(": "),t(e.body)}function u(e,t){this.keyword("try"),t(e.block),this.space(),t(e.handlers?e.handlers[0]:e.handler),e.finalizer&&(this.space(),this.push("finally "),t(e.finalizer))}function p(e,t){this.keyword("catch"),this.push("("),t(e.param),this.push(") "),t(e.body)}function c(e,t){this.push("throw "),t(e.argument),this.semicolon()}function d(e,t){this.keyword("switch"),this.push("("),t(e.discriminant),this.push(")"),this.space(),this.push("{"),t.sequence(e.cases,{indent:!0,addNewlines:function(t,n){return t||e.cases[e.cases.length-1]!==n?void 0:-1}}),this.push("}")}function f(e,t){e.test?(this.push("case "),t(e.test),this.push(":")):this.push("default:"),e.consequent.length&&(this.newline(),t.sequence(e.consequent,{indent:!0}))}function h(){this.push("debugger;")}function m(e,t,n){this.push(e.kind+" ");var r=!1;if(!x.isFor(n))for(var l=0;l<e.declarations.length;l++)e.declarations[l].init&&(r=!0);var i=",";i+=!this.format.compact&&r?"\n"+v(" ",e.kind.length+1):" ",t.list(e.declarations,{separator:i}),(!x.isFor(n)||n.left!==e&&n.init!==e)&&this.semicolon()}function g(e,t){t(e.id),t(e.id.typeAnnotation),e.init&&(this.space(),this.push("="),this.space(),t(e.init))}var y=function(e){return e&&e.__esModule?e:{"default":e}},b=function(e){return e&&e.__esModule?e["default"]:e};n.WithStatement=r,n.IfStatement=l,n.ForStatement=i,n.WhileStatement=s,n.DoWhileStatement=a,n.LabeledStatement=o,n.TryStatement=u,n.CatchClause=p,n.ThrowStatement=c,n.SwitchStatement=d,n.SwitchCase=f,n.DebuggerStatement=h,n.VariableDeclaration=m,n.VariableDeclarator=g,n.__esModule=!0;var v=b(e("repeating")),x=y(e("../../types")),E=function(e){return function(t,n){this.keyword("for"),this.push("("),n(t.left),this.push(" "+e+" "),n(t.right),this.push(")"),n.block(t.body)}},_=E("in");n.ForInStatement=_;var S=E("of");n.ForOfStatement=S;var I=function(e,t){return function(n,r){this.push(e);var l=n[t||"label"];l&&(this.push(" "),r(l)),this.semicolon()}},w=I("continue");n.ContinueStatement=w;var k=I("return","argument");n.ReturnStatement=k;var A=I("break");n.BreakStatement=A},{"../../types":153,repeating:437}],30:[function(e,t,n){"use strict";function r(e,t){t(e.tag),t(e.quasi)}function l(e){this._push(e.value.raw)}function i(e,t){var n=this;this.push("`");var r=e.quasis,l=r.length;a(r,function(r,i){t(r),l>i+1&&(n.push("${ "),t(e.expressions[i]),n.push(" }"))}),this._push("`")}var s=function(e){return e&&e.__esModule?e["default"]:e};n.TaggedTemplateExpression=r,n.TemplateElement=l,n.TemplateLiteral=i,n.__esModule=!0;var a=s(e("lodash/collection/each"))},{"lodash/collection/each":316}],31:[function(e,t,n){"use strict";function r(e){this.push(e.name)}function l(e,t){this.push("..."),t(e.argument)}function i(e,t){var n=e.properties;n.length?(this.push("{"),this.space(),t.list(n,{indent:!0}),this.space(),this.push("}")):this.push("{}")}function s(e,t){if(e.method||"get"===e.kind||"set"===e.kind)this._method(e,t);else{if(e.computed)this.push("["),t(e.key),this.push("]");else if(t(e.key),e.shorthand)return;this.push(":"),this.space(),t(e.value)}}function a(e,t){var n=this,r=e.elements,l=r.length;this.push("["),c(r,function(e,r){e?(r>0&&n.push(" "),t(e),l-1>r&&n.push(",")):n.push(",")}),this.push("]")}function o(e){var t=e.value,n=typeof t;"string"===n?this._stringLiteral(t):"number"===n?this.push(t+""):"boolean"===n?this.push(t?"true":"false"):e.regex?this.push("/"+e.regex.pattern+"/"+e.regex.flags):null===t&&this.push("null")}function u(e){e=JSON.stringify(e),e=e.replace(/[\u000A\u000D\u2028\u2029]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}),"single"===this.format.quotes&&(e=e.slice(1,-1),e=e.replace(/\\"/g,'"'),e=e.replace(/'/g,"\\'"),e="'"+e+"'"),this.push(e)}var p=function(e){return e&&e.__esModule?e["default"]:e};n.Identifier=r,n.RestElement=l,n.ObjectExpression=i,n.Property=s,n.ArrayExpression=a,n.Literal=o,n._stringLiteral=u,n.__esModule=!0;var c=p(e("lodash/collection/each"));n.SpreadElement=l,n.SpreadProperty=l,n.ObjectPattern=i,n.ArrayPattern=a},{"lodash/collection/each":316}],32:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("detect-indent")),s=r(e("./whitespace")),a=r(e("repeating")),o=r(e("./source-map")),u=r(e("./position")),p=n(e("../messages")),c=r(e("./buffer")),d=r(e("lodash/object/extend")),f=r(e("lodash/collection/each")),h=r(e("./node")),m=n(e("../types")),g=function(){function t(e,n,r){l(this,t),n||(n={}),this.comments=e.comments||[],this.tokens=e.tokens||[],this.format=t.normalizeOptions(r,n,this.tokens),this.opts=n,this.ast=e,this.whitespace=new s(this.tokens,this.comments,this.format),this.position=new u,this.map=new o(this.position,n,r),this.buffer=new c(this.position,this.format)}return t.normalizeOptions=function(e,n,r){var l=" ";if(e){var s=i(e).indent;s&&" "!==s&&(l=s)}var a={comments:null==n.comments||n.comments,compact:n.compact,quotes:t.findCommonStringDelimeter(e,r),indent:{adjustMultilineComment:!0,style:l,base:0}};return"auto"===a.compact&&(a.compact=e.length>1e5,a.compact&&console.error(p.get("codeGeneratorDeopt",n.filename,"100KB"))),a},t.findCommonStringDelimeter=function(e,t){for(var n={single:0,"double":0},r=0,l=0;l<t.length;l++){var i=t[l];if("string"===i.type.label&&!(r>=3)){var s=e.slice(i.start,i.end);"'"===s[0]?n.single++:n.double++,r++}}return n.single>n.double?"single":"double"},t.generators={templateLiterals:e("./generators/template-literals"),comprehensions:e("./generators/comprehensions"),expressions:e("./generators/expressions"),statements:e("./generators/statements"),classes:e("./generators/classes"),methods:e("./generators/methods"),modules:e("./generators/modules"),types:e("./generators/types"),flow:e("./generators/flow"),base:e("./generators/base"),jsx:e("./generators/jsx")},t.prototype.generate=function(){var e=this.ast;this.print(e);var t=[];return f(e.comments,function(e){e._displayed||t.push(e)}),this._printComments(t),{map:this.map.get(),code:this.buffer.get()}},t.prototype.buildPrint=function(e){var t=this,n=function(n,r){return t.print(n,e,r)};return n.sequence=function(e){var r=void 0===arguments[1]?{}:arguments[1];return r.statement=!0,t.printJoin(n,e,r)},n.join=function(e,r){return t.printJoin(n,e,r)},n.list=function(e){var t=void 0===arguments[1]?{}:arguments[1];null==t.separator&&(t.separator=", "),n.join(e,t)},n.block=function(e){return t.printBlock(n,e)},n.indentOnComments=function(e){return t.printAndIndentOnComments(n,e)},n},t.prototype.print=function(e,t){var n=this,r=void 0===arguments[2]?{}:arguments[2];if(e){t&&t._compact&&(e._compact=!0);var l=this.format.concise;e._compact&&(this.format.concise=!0);var i=function(l){if(r.statement||h.isUserWhitespacable(e,t)){var i=0;if(null==e.start||e._ignoreUserWhitespace){l||i++,r.addNewlines&&(i+=r.addNewlines(l,e)||0);var s=h.needsWhitespaceAfter;l&&(s=h.needsWhitespaceBefore),s(e,t)&&i++,n.buffer.buf||(i=0)}else i=l?n.whitespace.getNewlinesBefore(e):n.whitespace.getNewlinesAfter(e);n.newline(i)}};if(!this[e.type])throw new ReferenceError("unknown node of type "+JSON.stringify(e.type)+" with constructor "+JSON.stringify(e&&e.constructor.name));var s=h.needsParensNoLineTerminator(e,t),a=s||h.needsParens(e,t);a&&this.push("("),s&&this.indent(),this.printLeadingComments(e,t),i(!0),r.before&&r.before(),this.map.mark(e,"start"),this[e.type](e,this.buildPrint(e),t),s&&(this.newline(),this.dedent()),a&&this.push(")"),this.map.mark(e,"end"),r.after&&r.after(),i(!1),this.printTrailingComments(e,t),this.format.concise=l}},t.prototype.printJoin=function(e,t){var n=this,r=void 0===arguments[2]?{}:arguments[2];if(t&&t.length){var l=t.length;r.indent&&this.indent(),f(t,function(t,i){e(t,{statement:r.statement,addNewlines:r.addNewlines,after:function(){r.iterator&&r.iterator(t,i),r.separator&&l-1>i&&n.push(r.separator)}})}),r.indent&&this.dedent()}},t.prototype.printAndIndentOnComments=function(e,t){var n=!!t.leadingComments;n&&this.indent(),e(t),n&&this.dedent()},t.prototype.printBlock=function(e,t){m.isEmptyStatement(t)?this.semicolon():(this.push(" "),e(t))},t.prototype.generateComment=function(e){var t=e.value;return t="Line"===e.type?"//"+t:"/*"+t+"*/"},t.prototype.printTrailingComments=function(e,t){this._printComments(this.getComments("trailingComments",e,t))},t.prototype.printLeadingComments=function(e,t){this._printComments(this.getComments("leadingComments",e,t))},t.prototype.getComments=function(e,t,n){var r=this;if(m.isExpressionStatement(n))return[];var l=[],i=[t];return m.isExpressionStatement(t)&&i.push(t.argument),f(i,function(t){l=l.concat(r._getComments(e,t))}),l},t.prototype._getComments=function(e,t){return t&&t[e]||[]},t.prototype._printComments=function(e){var t=this;this.format.compact||this.format.comments&&e&&e.length&&f(e,function(e){var n=!1;if(f(t.ast.comments,function(t){return t.start===e.start?(t._displayed&&(n=!0),t._displayed=!0,!1):void 0}),!n){t.newline(t.whitespace.getNewlinesBefore(e));var r=t.position.column,l=t.generateComment(e);if(r&&!t.isLast(["\n"," ","[","{"])&&(t._push(" "),r++),"Block"===e.type&&t.format.indent.adjustMultilineComment){var i=e.loc.start.column;if(i){var s=new RegExp("\\n\\s{1,"+i+"}","g");l=l.replace(s,"\n")}var o=Math.max(t.indentSize(),r);l=l.replace(/\n/g,"\n"+a(" ",o))}0===r&&(l=t.getIndent()+l),t._push(l),t.newline(t.whitespace.getNewlinesAfter(e))}})},t}();f(c.prototype,function(e,t){g.prototype[t]=function(){return e.apply(this.buffer,arguments)}}),f(g.generators,function(e){d(g.prototype,e)}),t.exports=function(e,t,n){var r=new g(e,t,n);return r.generate()},t.exports.CodeGenerator=g},{"../messages":43,"../types":153,"./buffer":20,"./generators/base":21,"./generators/classes":22,"./generators/comprehensions":23,"./generators/expressions":24,"./generators/flow":25,"./generators/jsx":26,"./generators/methods":27,"./generators/modules":28,"./generators/statements":29,"./generators/template-literals":30,"./generators/types":31,"./node":33,"./position":36,"./source-map":37,"./whitespace":38,"detect-indent":295,"lodash/collection/each":316,"lodash/object/extend":406,repeating:437}],33:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("./whitespace")),s=n(e("./parentheses")),a=r(e("lodash/collection/each")),o=r(e("lodash/collection/some")),u=n(e("../../types")),p=function(e,t,n){if(e){for(var r,l=Object.keys(e),i=0;i<l.length;i++){var s=l[i];if(u.is(s,t)){var a=e[s];if(r=a(t,n),null!=r)break}}return r}},c=function(){function e(t,n){l(this,e),this.parent=n,this.node=t}return e.isUserWhitespacable=function(e){return u.isUserWhitespacable(e)},e.needsWhitespace=function(t,n,r){if(!t)return 0;u.isExpressionStatement(t)&&(t=t.expression);var l=p(i.nodes,t,n);if(!l){var s=p(i.list,t,n);if(s)for(var a=0;a<s.length&&!(l=e.needsWhitespace(s[a],t,r));a++);}return l&&l[r]||0},e.needsWhitespaceBefore=function(t,n){return e.needsWhitespace(t,n,"before")},e.needsWhitespaceAfter=function(t,n){return e.needsWhitespace(t,n,"after")},e.needsParens=function(e,t){if(!t)return!1;if(u.isNewExpression(t)&&t.callee===e){if(u.isCallExpression(e))return!0;var n=o(e,function(e){return u.isCallExpression(e)});if(n)return!0}return p(s,e,t)},e.needsParensNoLineTerminator=function(e,t){return t&&e.leadingComments&&e.leadingComments.length?u.isYieldExpression(t)||u.isAwaitExpression(t)?!0:u.isContinueStatement(t)||u.isBreakStatement(t)||u.isReturnStatement(t)||u.isThrowStatement(t)?!0:!1:!1},e}();t.exports=c,a(c,function(e,t){c.prototype[t]=function(){var e=new Array(arguments.length+2);e[0]=this.node,e[1]=this.parent;for(var n=0;n<e.length;n++)e[n+2]=arguments[n];return c[t].apply(null,e)}})},{"../../types":153,"./parentheses":34,"./whitespace":35,"lodash/collection/each":316,"lodash/collection/some":322}],34:[function(e,t,n){"use strict";function r(e,t){return y.isArrayTypeAnnotation(t)}function l(e,t){return y.isMemberExpression(t)&&t.object===e?!0:void 0}function i(e,t){return y.isExpressionStatement(t)?!0:y.isMemberExpression(t)&&t.object===e?!0:!1}function s(e,t){if((y.isCallExpression(t)||y.isNewExpression(t))&&t.callee===e)return!0;if(y.isUnaryLike(t))return!0;if(y.isMemberExpression(t)&&t.object===e)return!0;if(y.isBinary(t)){var n=t.operator,r=b[n],l=e.operator,i=b[l];if(r>i)return!0;if(r===i&&t.right===e)return!0}}function a(e,t){if("in"===e.operator){if(y.isVariableDeclarator(t))return!0;if(y.isFor(t))return!0}}function o(e,t){return y.isForStatement(t)?!1:y.isExpressionStatement(t)&&t.expression===e?!1:!0}function u(e,t){return y.isBinary(t)||y.isUnaryLike(t)||y.isCallExpression(t)||y.isMemberExpression(t)||y.isNewExpression(t)||y.isConditionalExpression(t)||y.isYieldExpression(t)}function p(e,t){return y.isExpressionStatement(t)}function c(e,t){return y.isMemberExpression(t)&&t.object===e}function d(e,t){return y.isExpressionStatement(t)?!0:y.isMemberExpression(t)&&t.object===e?!0:y.isCallExpression(t)&&t.callee===e?!0:void 0}function f(e,t){return y.isUnaryLike(t)?!0:y.isBinary(t)?!0:(y.isCallExpression(t)||y.isNewExpression(t))&&t.callee===e?!0:y.isConditionalExpression(t)&&t.test===e?!0:y.isMemberExpression(t)&&t.object===e?!0:!1}var h=function(e){return e&&e.__esModule?e:{"default":e}},m=function(e){return e&&e.__esModule?e["default"]:e};n.NullableTypeAnnotation=r,n.UpdateExpression=l,n.ObjectExpression=i,n.Binary=s,n.BinaryExpression=a,n.SequenceExpression=o,n.YieldExpression=u,n.ClassExpression=p,n.UnaryLike=c,n.FunctionExpression=d,n.ConditionalExpression=f,n.__esModule=!0;var g=m(e("lodash/collection/each")),y=h(e("../../types")),b={};g([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(e,t){g(e,function(e){b[e]=t})}),n.FunctionTypeAnnotation=r,n.AssignmentExpression=f},{"../../types":153,"lodash/collection/each":316}],35:[function(e,t,n){"use strict";function r(e){var t=void 0===arguments[1]?{}:arguments[1];if(c.isMemberExpression(e))r(e.object,t),e.computed&&r(e.property,t);else if(c.isBinary(e)||c.isAssignmentExpression(e))r(e.left,t),r(e.right,t);else if(c.isCallExpression(e))t.hasCall=!0,r(e.callee,t);else if(c.isFunction(e))t.hasFunction=!0;else if(c.isIdentifier(e)){var n=t;n.hasHelper||(n.hasHelper=l(e.callee))}return t}function l(e){return c.isMemberExpression(e)?l(e.object)||l(e.property):c.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:c.isCallExpression(e)?l(e.callee):c.isBinary(e)||c.isAssignmentExpression(e)?c.isIdentifier(e.left)&&l(e.left)||l(e.right):!1}function i(e){return c.isLiteral(e)||c.isObjectExpression(e)||c.isArrayExpression(e)||c.isIdentifier(e)||c.isMemberExpression(e)}var s=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e},o=a(e("lodash/lang/isBoolean")),u=a(e("lodash/collection/each")),p=a(e("lodash/collection/map")),c=s(e("../../types"));n.nodes={AssignmentExpression:function(e){var t=r(e.right);return t.hasCall&&t.hasHelper||t.hasFunction?{before:t.hasFunction,after:!0}:void 0},SwitchCase:function(e,t){return{before:e.consequent.length||t.cases[0]===e}},LogicalExpression:function(e){return c.isFunction(e.left)||c.isFunction(e.right)?{after:!0}:void 0},Literal:function(e){return"use strict"===e.value?{after:!0}:void 0},CallExpression:function(e){return c.isFunction(e.callee)||l(e)?{before:!0,after:!0}:void 0},VariableDeclaration:function(e){for(var t=0;t<e.declarations.length;t++){var n=e.declarations[t],s=l(n.id)&&!i(n.init);if(!s){var a=r(n.init);s=l(n.init)&&a.hasCall||a.hasFunction}if(s)return{before:!0,after:!0}}},IfStatement:function(e){return c.isBlockStatement(e.consequent)?{before:!0,after:!0}:void 0}},n.nodes.Property=n.nodes.SpreadProperty=function(e,t){return t.properties[0]===e?{before:!0}:void 0},n.list={VariableDeclaration:function(e){return p(e.declarations,"init")},ArrayExpression:function(e){return e.elements},ObjectExpression:function(e){return e.properties}},u({Function:!0,Class:!0,Loop:!0,LabeledStatement:!0,SwitchStatement:!0,TryStatement:!0},function(e,t){o(e)&&(e={after:e,before:e}),u([t].concat(c.FLIPPED_ALIAS_KEYS[t]||[]),function(t){n.nodes[t]=function(){return e}})})},{"../../types":153,"lodash/collection/each":316,"lodash/collection/map":320,"lodash/lang/isBoolean":393}],36:[function(e,t){"use strict";var n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(){n(this,e),this.line=1,this.column=0}return e.prototype.push=function(e){for(var t=0;t<e.length;t++)"\n"===e[t]?(this.line++,this.column=0):this.column++},e.prototype.unshift=function(e){for(var t=0;t<e.length;t++)"\n"===e[t]?this.line--:this.column--},e}();t.exports=r},{}],37:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("source-map")),s=n(e("../types")),a=function(){function e(t,n,r){l(this,e),this.position=t,this.opts=n,n.sourceMaps?(this.map=new i.SourceMapGenerator({file:n.sourceMapName,sourceRoot:n.sourceRoot}),this.map.setSourceContent(n.sourceFileName,r)):this.map=null}return e.prototype.get=function(){var e=this.map;return e?e.toJSON():e},e.prototype.mark=function(e,t){var n=e.loc;if(n){var r=this.map;if(r&&!s.isProgram(e)&&!s.isFile(e)){var l=this.position,i={line:l.line,column:l.column},a=n[t];r.addMapping({source:this.opts.sourceFileName,generated:i,original:a})}}},e}();t.exports=a},{"../types":153,"source-map":441}],38:[function(e,t){"use strict";function n(e,t,n){return e+=t,e>=n&&(e-=n),e}var r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("lodash/collection/sortBy")),s=function(){function e(t,n){l(this,e),this.tokens=i(t.concat(n),"start"),this.used={},this._lastFoundIndex=0}return e.prototype.getNewlinesBefore=function(e){for(var t,r,l,i=this.tokens,s=0;s<i.length;s++){var a=n(s,this._lastFoundIndex,this.tokens.length);if(l=i[a],e.start===l.start){t=i[a-1],r=l,this._lastFoundIndex=a;break}}return this.getNewlinesBetween(t,r)},e.prototype.getNewlinesAfter=function(e){for(var t,r,l,i=this.tokens,s=0;s<i.length;s++){var a=n(s,this._lastFoundIndex,this.tokens.length);if(l=i[a],e.end===l.end){t=l,r=i[a+1],this._lastFoundIndex=a;break}}if(r&&"eof"===r.type.label)return 1;var o=this.getNewlinesBetween(t,r);return"Line"!==e.type||o?o:1},e.prototype.getNewlinesBetween=function(e,t){if(!t||!t.loc)return 0;for(var n=e?e.loc.end.line:1,r=t.loc.start.line,l=0,i=n;r>i;i++)"undefined"==typeof this.used[i]&&(this.used[i]=!0,l++);return l},e}();t.exports=s},{"lodash/collection/sortBy":323}],39:[function(e,t){"use strict";function n(e){var t=a.matchToToken(e);if("name"===t.type&&o.keyword.isReservedWordES6(t.value))return"keyword";if("punctuator"===t.type)switch(t.value){case"{":case"}":return"curly";case"(":case")":return"parens";case"[":case"]":return"square"}return t.type}function r(e){return e.replace(a,function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];var l=n(t),i=p[l];return i?t[0].split(c).map(function(e){return i(e)}).join("\n"):t[0]})}var l=function(e){return e&&e.__esModule?e["default"]:e},i=l(e("line-numbers")),s=l(e("repeating")),a=l(e("js-tokens")),o=l(e("esutils")),u=l(e("chalk")),p={string:u.red,punctuator:u.bold,curly:u.green,parens:u.blue.bold,square:u.yellow,keyword:u.cyan,number:u.magenta,regex:u.magenta,comment:u.grey,invalid:u.inverse},c=/\r\n|[\n\r\u2028\u2029]/;t.exports=function(e,t,n){var l=void 0===arguments[3]?{}:arguments[3];n=Math.max(n,0),l.highlightCode&&u.supportsColor&&(e=r(e)),e=e.split(c);var a=Math.max(t-3,0),o=Math.min(e.length,t+3);return t||n||(a=0,o=e.length),i(e.slice(a,o),{start:a+1,before:" ",after:" | ",transform:function(e){e.number===t&&(n&&(e.line+="\n"+e.before+s(" ",e.width)+e.after+s(" ",n-1)+"^"),e.before=e.before.replace(/^./,">"))}}).join("\n")}},{chalk:200,esutils:300,"js-tokens":306,"line-numbers":308,repeating:437}],40:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../types"));t.exports=function(e,t,n){if(e&&"Program"===e.type)return r.file(e,t||[],n||[]);throw new Error("Not a valid ast?")}},{"../types":153}],41:[function(e,t){"use strict";t.exports=function(){return Object.create(null)}},{}],42:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("./normalize-ast")),i=r(e("estraverse")),s=r(e("./code-frame")),a=n(e("../../acorn"));t.exports=function(e,t,n){try{var r=[],o=[],u={allowImportExportEverywhere:e.looseModules,allowReturnOutsideFunction:e.looseModules,ecmaVersion:6,strictMode:e.strictMode,sourceType:e.sourceType,onComment:r,locations:!0,features:e.features||{},plugins:e.plugins||{},onToken:o,ranges:!0};e.nonStandard&&(u.plugins.jsx=!0,u.plugins.flow=!0);var p=a.parse(t,u);return i.attachComments(p,r,o),p=l(p,r,o),n?n(p):p}catch(c){if(!c._babel){c._babel=!0;var d=c.message=""+e.filename+": "+c.message,f=c.loc;if(f&&(c.codeFrame=s(t,f.line,f.column+1,e),d+="\n"+c.codeFrame),c.stack){var h=c.stack.replace(c.message,d);try{c.stack=h}catch(m){}}}throw c}}},{"../../acorn":5,"./code-frame":39,"./normalize-ast":40,estraverse:296}],43:[function(e,t,n){"use strict";function r(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;t>r;r++)n[r-1]=arguments[r];var i=a[e];if(!i)throw new ReferenceError("Unknown message "+JSON.stringify(e));return n=l(n),i.replace(/\$(\d+)/g,function(e,t){return n[--t]})}function l(e){return e.map(function(e){if(null!=e&&e.inspect)return e.inspect();try{return JSON.stringify(e)||e+""}catch(t){return s.inspect(e)}})}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.get=r,n.parseArgs=l,n.__esModule=!0;var s=i(e("util")),a={tailCallReassignmentDeopt:"Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",JSXNamespacedTags:"Namespace tags are not supported. ReactJSX is not XML.",classesIllegalBareSuper:"Illegal use of bare super",classesIllegalSuperCall:"Direct super call is illegal in non-constructor, use super.$1() instead",classesIllegalConstructorKind:"Illegal kind for constructor method",scopeDuplicateDeclaration:"Duplicate declaration $1",undeclaredVariable:"Reference to undeclared variable $1",undeclaredVariableSuggestion:"Reference to undeclared variable $1 - did you mean $2?",settersInvalidParamLength:"Setters must have exactly one parameter",settersNoRest:"Setters aren't allowed to have a rest",noAssignmentsInForHead:"No assignments allowed in for-in/of head",expectedMemberExpressionOrIdentifier:"Expected type MemeberExpression or Identifier",invalidParentForThisNode:"We don't know how to handle this node within the current parent - please open an issue",readOnly:"$1 is read-only",modulesIllegalExportName:"Illegal export $1",unknownForHead:"Unknown node type $1 in ForStatement",didYouMean:"Did you mean $1?",evalInStrictMode:"eval is not allowed in strict mode",codeGeneratorDeopt:"Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",missingTemplatesDirectory:"no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",unsupportedOutputType:"Unsupported output type $1",illegalMethodName:"Illegal method name $1"};
n.MESSAGES=a},{util:199}],44:[function(e){"use strict";var t=function(e){return e&&e.__esModule?e:{"default":e}},n=function(e){return e&&e.__esModule?e["default"]:e},r=n(e("estraverse")),l=n(e("lodash/object/extend")),i=n(e("ast-types")),s=t(e("./types"));l(r.VisitorKeys,s.VISITOR_KEYS);var a=i.Type.def,o=i.Type.or;a("File").bases("Node").build("program").field("program",a("Program")),a("AssignmentPattern").bases("Pattern").build("left","right").field("left",a("Pattern")).field("right",a("Expression")),a("RestElement").bases("Pattern").build("argument").field("argument",a("expression")),a("DoExpression").bases("Expression").build("body").field("body",[a("Statement")]),a("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration",o(a("Declaration"),a("Expression"),null)),a("ExportNamedDeclaration").bases("Declaration").build("declaration").field("declaration",o(a("Declaration"),a("Expression"),null)).field("specifiers",[o(a("ExportSpecifier"))]).field("source",o(a("ModuleSpecifier"),null)),i.finalize()},{"./types":153,"ast-types":171,estraverse:296,"lodash/object/extend":406}],45:[function(e,t){"use strict";function n(e){if(!s.existsSync)return!1;var t=a[e];return null!=t?t:a[e]=s.existsSync(e)}var r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("lodash/object/merge")),i=r(e("path")),s=r(e("fs")),a={},o={};t.exports=function(e){function t(e,a){var u=i.join(e,a);if(n(u)){var p,c=s.readFileSync(u,"utf8");try{var d,f;d=o,f=c,!d[f]&&(d[f]=JSON.parse(c)),p=d[f]}catch(h){throw h.message=""+u+": "+h.message,h}if(p.breakConfig)return;l(r,p,function(e,t){return Array.isArray(e)?e.concat(t):void 0})}var m=i.dirname(e);m!==e&&t(m,a)}var r=void 0===arguments[1]?{}:arguments[1],a=".babelrc";return r.breakConfig!==!0&&t(e,a),r}},{fs:172,"lodash/object/merge":410,path:182}],46:[function(e,t){(function(n){"use strict";function r(e,t,n){k(e,function(e){e.shouldRun||e.ran||e.checkNode(t,n)})}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e},s=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e)){for(var n,r=[],l=e[Symbol.iterator]();!(n=l.next()).done&&(r.push(n.value),!t||r.length!==t););return r}throw new TypeError("Invalid attempt to destructure non-iterable instance")},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},o=i(e("convert-source-map")),u=l(e("./option-parsers")),p=i(e("shebang-regex")),c=i(e("../../traversal/path")),d=i(e("lodash/lang/isFunction")),f=i(e("path-is-absolute")),h=i(e("../../tools/resolve-rc")),m=i(e("source-map")),g=i(e("./../index")),y=i(e("../../generation")),b=i(e("lodash/object/defaults")),v=i(e("lodash/collection/includes")),x=(i(e("../../traversal")),i(e("lodash/object/assign"))),E=i(e("./logger")),_=i(e("../../helpers/parse")),S=(i(e("../../traversal/scope")),i(e("slash"))),I=l(e("../../util")),w=i(e("path")),k=i(e("lodash/collection/each")),A=l(e("../../types")),C={enter:function(e,t,n,l){r(l.stack,e,n)}},T=function(){function t(){var e=void 0===arguments[0]?{}:arguments[0];a(this,t),this.dynamicImportedNoDefault=[],this.dynamicImportIds={},this.dynamicImported=[],this.dynamicImports=[],this.usedHelpers={},this.dynamicData={},this.data={},this.uids={},this.lastStatements=[],this.log=new E(this,e.filename||"unknown"),this.opts=this.normalizeOptions(e),this.ast={},this.buildTransformers()}return t.helpers=["inherits","defaults","create-class","create-decorated-class","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","to-consumable-array","sliced-to-array","sliced-to-array-loose","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get","set","class-call-check","object-destructuring-empty","temporal-undefined","temporal-assert-defined","self-global","default-props"],t.options=e("./options"),t.prototype.normalizeOptions=function(e){if(e=x({},e),e.filename){var r=e.filename;f(r)||(r=w.join(n.cwd(),r)),e=h(r,e)}for(var l in e)if("_"!==l[0]){var i=t.options[l];i||this.log.error("Unknown option: "+l,ReferenceError)}for(var l in t.options){var i=t.options[l],s=e[l];if(s||!i.optional){if(s&&i.deprecated)throw new Error("Deprecated option "+l+": "+i.deprecated);null==s&&(s=i["default"]||s);var a=u[i.type];if(a&&(s=a(l,s)),i.alias){var o=e,p=i.alias;o[p]||(o[p]=s)}else e[l]=s}}return e.inputSourceMap&&(e.sourceMaps=!0),e.filename=S(e.filename),e.sourceRoot&&(e.sourceRoot=S(e.sourceRoot)),e.moduleId&&(e.moduleIds=!0),e.basename=w.basename(e.filename,w.extname(e.filename)),e.ignore=I.arrayify(e.ignore,I.regexify),e.only=I.arrayify(e.only,I.regexify),b(e,{moduleRoot:e.sourceRoot}),b(e,{sourceRoot:e.moduleRoot}),b(e,{filenameRelative:e.filename}),b(e,{sourceFileName:e.filenameRelative,sourceMapName:e.filenameRelative}),e.externalHelpers&&this.set("helpersNamespace",A.identifier("babelHelpers")),e},t.prototype.isLoose=function(e){return v(this.opts.loose,e)},t.prototype.buildTransformers=function(){var e=this,t=this.transformers={},n=[],r=[];k(g.transformers,function(l,i){var s=t[i]=l.buildPass(e);s.canTransform()&&(r.push(s),l.metadata.secondPass&&n.push(s),l.manipulateOptions&&l.manipulateOptions(e.opts,e))});for(var l=[],i=[],s=0;s<e.opts.plugins.length;s++)this.addPlugin(e.opts.plugins[s],l,i);r=l.concat(r,i),this.transformerStack=r.concat(n)},t.prototype.getModuleFormatter=function(t){var n=d(t)?t:g.moduleFormatters[t];if(!n){var r=I.resolveRelative(t);r&&(n=e(r))}if(!n)throw new ReferenceError("Unknown module formatter type "+JSON.stringify(t));return new n(this)},t.prototype.addPlugin=function(t,n,r){var l,i="before";if(!t)throw new TypeError("Ilegal kind "+typeof t+" for plugin name "+JSON.stringify(t));if("string"==typeof t){var a=t.split(":"),o=s(a,2);t=o[0];var u=o[1];i=void 0===u?"before":u;var p=I.resolveRelative(t)||I.resolveRelative("babel-plugin-"+t);if(!p)throw new ReferenceError("Unknown plugin "+JSON.stringify(t));l=e(p)}else l=t;if("before"!==i&&"after"!==i)throw new TypeError("Plugin "+JSON.stringify(t)+" has an illegal position of "+JSON.stringify(i));var c=l.key;if(this.transformers[c])throw new ReferenceError("The key for plugin "+JSON.stringify(t)+" of "+c+" collides with an existing plugin");if(!l.buildPass||"Transformer"!==l.constructor.name)throw new TypeError("Plugin "+JSON.stringify(t)+" didn't export default a Transformer instance");var d=this.transformers[c]=l.buildPass(this);if(d.canTransform()){var f=n;"after"===i&&(f=r),f.push(d)}},t.prototype.parseInputSourceMap=function(e){var t=this.opts;if(t.inputSourceMap!==!1){var n=o.fromSource(e);n&&(t.inputSourceMap=n.toObject(),e=o.removeComments(e))}return e},t.prototype.parseShebang=function(e){var t=p.exec(e);return t&&(this.shebang=t[0],e=e.replace(p,"")),e},t.prototype.set=function(e,t){return this.data[e]=t},t.prototype.setDynamic=function(e,t){this.dynamicData[e]=t},t.prototype.get=function(e){var t=this.data[e];if(t)return t;var n=this.dynamicData[e];return n?this.set(e,n()):void 0},t.prototype.resolveModuleSource=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e){var t=this.opts.resolveModuleSource;return t&&(e=t(e,this.opts.filename)),e}),t.prototype.addImport=function(e,t,n){t||(t=e);var r=this.dynamicImportIds[t];if(!r){e=this.resolveModuleSource(e),r=this.dynamicImportIds[t]=this.scope.generateUidIdentifier(t);var l=[A.importDefaultSpecifier(r)],i=A.importDeclaration(l,A.literal(e));i._blockHoist=3,this.dynamicImported.push(i),n&&this.dynamicImportedNoDefault.push(i),this.transformers["es6.modules"].canTransform()?(this.moduleFormatter.importSpecifier(l[0],i,this.dynamicImports),this.moduleFormatter.hasLocalImports=!0):this.dynamicImports.push(i)}return r},t.prototype.isConsequenceExpressionStatement=function(e){return A.isExpressionStatement(e)&&this.lastStatements.indexOf(e)>=0},t.prototype.attachAuxiliaryComment=function(e){var t=this.opts.auxiliaryComment;if(t){var n=e;n.leadingComments||(n.leadingComments=[]),e.leadingComments.push({type:"Line",value:" "+t})}return e},t.prototype.addHelper=function(e){if(!v(t.helpers,e))throw new ReferenceError("Unknown helper "+e);var n=this.ast.program,r=n._declarations&&n._declarations[e];if(r)return r.id;this.usedHelpers[e]=!0;var l=this.get("helperGenerator"),i=this.get("helpersNamespace");if(l)return l(e);if(i){var s=A.identifier(A.toIdentifier(e));return A.memberExpression(i,s)}var a=I.template("helper-"+e);a._compact=!0;var o=this.scope.generateUidIdentifier(e);return this.scope.push({key:e,id:o,init:a}),o},t.prototype.errorWithNode=function(e,t){var n=void 0===arguments[2]?SyntaxError:arguments[2],r=e.loc.start,l=new n("Line "+r.line+": "+t);return l.loc=r,l},t.prototype.addCode=function(e){return e=(e||"")+"",e=this.parseInputSourceMap(e),this.code=e,this.parseShebang(e)},t.prototype.shouldIgnore=function(){var e=this.opts;return I.shouldIgnore(e.filename,e.ignore,e.only)},t.prototype.parse=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e){var t=this;if(this.shouldIgnore())return{metadata:{},code:e,map:null,ast:null};e=this.addCode(e);var n=this.opts,r={highlightCode:n.highlightCode,nonStandard:n.nonStandard,filename:n.filename,plugins:{}},l=r.features={};for(var i in this.transformers){var s=this.transformers[i];l[i]=s.canTransform()}return r.looseModules=this.isLoose("es6.modules"),r.strictMode=l.strict,r.sourceType="module",_(r,e,function(e){return t.transform(e),t.generate()})}),t.prototype.setAst=function(e){this.path=c.get(null,null,e,e,"program",this),this.scope=this.path.scope,this.ast=e,this.path.traverse({enter:function(e,t,n){if(this.isScope())for(var r in n.bindings)n.bindings[r].setTypeAnnotation()}})},t.prototype.transform=function(e){this.log.debug(),this.setAst(e),this.lastStatements=A.getLastStatements(e.program);var t=this.moduleFormatter=this.getModuleFormatter(this.opts.modules);t.init&&this.transformers["es6.modules"].canTransform()&&t.init(),this.checkNode(e),this.call("pre"),k(this.transformerStack,function(e){e.transform()}),this.call("post")},t.prototype.call=function(e){for(var t=this.transformerStack,n=0;n<t.length;n++){var r=t[n].transformer,l=r[e];l&&l(this)}},t.prototype.checkNode=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++)this.checkNode(e[n],t);else{var l=this.transformerStack;t||(t=this.scope),r(l,e,t),t.traverse(e,C,{stack:l})}}),t.prototype.mergeSourceMap=function(e){var t=this.opts,n=t.inputSourceMap;if(n){e.sources[0]=n.file;var r=new m.SourceMapConsumer(n),l=new m.SourceMapConsumer(e),i=m.SourceMapGenerator.fromSourceMap(l);i.applySourceMap(r);var s=i.toJSON();return s.sources=n.sources,s.file=n.file,s}return e},t.prototype.generate=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(){var e=this.opts,t=this.ast,n={metadata:{},code:"",map:null,ast:null};if(this.opts.metadataUsedHelpers&&(n.metadata.usedHelpers=Object.keys(this.usedHelpers)),e.ast&&(n.ast=t),!e.code)return n;var r=y(t,e,this.code);return n.code=r.code,n.map=r.map,this.shebang&&(n.code=""+this.shebang+"\n"+n.code),n.map&&(n.map=this.mergeSourceMap(n.map)),("inline"===e.sourceMaps||"both"===e.sourceMaps)&&(n.code+="\n"+o.fromObject(n.map).toComment()),"inline"===e.sourceMaps&&(n.map=null),n}),t}();t.exports=T}).call(this,e("_process"))},{"../../generation":32,"../../helpers/parse":42,"../../tools/resolve-rc":45,"../../traversal":144,"../../traversal/path":148,"../../traversal/scope":149,"../../types":153,"../../util":157,"./../index":63,"./logger":47,"./option-parsers":48,"./options":49,_process:183,"convert-source-map":208,"lodash/collection/each":316,"lodash/collection/includes":319,"lodash/lang/isFunction":395,"lodash/object/assign":404,"lodash/object/defaults":405,path:182,"path-is-absolute":420,"shebang-regex":439,slash:440,"source-map":441}],47:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("../../util")),i=function(){function e(t,n){r(this,e),this.filename=n,this.file=t}return e.prototype._buildMessage=function(e){var t=this.filename;return e&&(t+=": "+e),t},e.prototype.error=function(e){var t=void 0===arguments[1]?Error:arguments[1];throw new t(this._buildMessage(e))},e.prototype.deprecate=function(e){this.file.opts.suppressDeprecationMessages||console.error(e)},e.prototype.debug=function(e){l.debug(this._buildMessage(e))},e.prototype.deopt=function(e,t){l.debug(this._buildMessage(t))},e}();t.exports=i},{"../../util":157}],48:[function(e,t,n){"use strict";function r(e,t){return t=c.arrayify(t),(t.indexOf("all")>=0||t.indexOf(!0)>=0)&&(t=Object.keys(p.transformers)),p._ensureTransformerNames(e,t)}function l(e,t){return+t}function i(e,t){return!!t}function s(e,t){return c.booleanify(t)}function a(e,t){return c.list(t)}var o=function(e){return e&&e.__esModule?e:{"default":e}},u=function(e){return e&&e.__esModule?e["default"]:e};n.transformerList=r,n.number=l,n.boolean=i,n.booleanString=s,n.list=a,n.__esModule=!0;var p=u(e("./../index")),c=o(e("../../util"))},{"../../util":157,"./../index":63}],49:[function(e,t){t.exports={filename:{type:"string",description:"filename to use when reading from stdin - this will be used in source-maps, errors etc","default":"unknown",shorthand:"f"},filenameRelative:{hidden:!0,type:"string"},inputSourceMap:{hidden:!0},moduleId:{description:"specify a custom name for module ids",type:"string"},nonStandard:{type:"boolean","default":!0,description:"enable support for JSX and Flow"},experimental:{deprecated:"use `--stage 0`/`{ stage: 0 }` instead"},highlightCode:{description:"ANSI syntax highlight code frames",type:"boolean","default":!0},suppressDeprecationMessages:{type:"boolean","default":!1,hidden:!0},resolveModuleSource:{hidden:!0},stage:{description:"ECMAScript proposal stage version to allow [0-4]",shorthand:"e",type:"number","default":2},blacklist:{type:"transformerList",description:"blacklist of transformers to NOT use",shorthand:"b"},whitelist:{type:"transformerList",optional:!0,description:"whitelist of transformers to ONLY use",shorthand:"l"},optional:{type:"transformerList",description:"list of optional transformers to enable"},modules:{type:"string",description:"module formatter type to use [common]","default":"common",shorthand:"m"},moduleIds:{type:"boolean","default":!1,shorthand:"M",description:"insert an explicit id for modules"},loose:{type:"transformerList",description:"list of transformers to enable loose mode ON",shorthand:"L"},jsxPragma:{type:"string",description:"custom pragma to use with JSX (same functionality as @jsx comments)","default":"React.createElement",shorthand:"P"},plugins:{type:"list",description:""},ignore:{type:"list",description:"list of glob paths to **not** compile"},only:{type:"list",description:"list of glob paths to **only** compile"},code:{hidden:!0,"default":!0,type:"boolean"},ast:{hidden:!0,"default":!0,type:"boolean"},comments:{type:"boolean","default":!0,description:"output comments in generated output"},compact:{type:"booleanString","default":"auto",description:"do not include superfluous whitespace characters and line terminators [true|false|auto]"},keepModuleIdExtensions:{type:"boolean",description:"keep extensions when generating module ids","default":!1,shorthand:"k"},auxiliaryComment:{type:"string","default":"",shorthand:"a",description:"attach a comment before all helper declarations and auxiliary code"},externalHelpers:{type:"string","default":!1,shorthand:"r",description:"uses a reference to `babelHelpers` instead of placing helpers at the top of your code."},metadataUsedHelpers:{type:"boolean","default":!1,hidden:!0},sourceMap:{alias:"sourceMaps",hidden:!0},sourceMaps:{type:"booleanString",description:"[true|false|inline]","default":!1,shorthand:"s"},sourceMapName:{type:"string",description:"set `file` on returned source map"},sourceFileName:{type:"string",description:"set `sources[0]` on returned source map"},sourceRoot:{type:"string",description:"the root from which all sources are relative"},moduleRoot:{type:"string",description:"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"},breakConfig:{type:"boolean","default":!1,hidden:!0,description:"stop trying to load .babelrc files"}}},{}],50:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("./explode-assignable-expression")),i=n(e("../../types"));t.exports=function(e,t){var n=function(e){return e.operator===t.operator+"="},r=function(e,t){return i.assignmentExpression("=",e,t)};e.ExpressionStatement=function(e,s,a,o){if(!o.isConsequenceExpressionStatement(e)){var u=e.expression;if(n(u)){var p=[],c=l(u.left,p,o,a,!0);return p.push(i.expressionStatement(r(c.ref,t.build(c.uid,u.right)))),p}}},e.AssignmentExpression=function(e,i,s,a){if(n(e)){var o=[],u=l(e.left,o,a,s);return o.push(r(u.ref,t.build(u.uid,e.right))),o}},e.BinaryExpression=function(e){return e.operator===t.operator?t.build(e.left,e.right):void 0}}},{"../../types":153,"./explode-assignable-expression":55}],51:[function(e,t){"use strict";function n(e,t){var r=e.blocks.shift();if(r){var i=n(e,t);return i||(i=t(),e.filter&&(i=l.ifStatement(e.filter,l.blockStatement([i])))),l.forOfStatement(l.variableDeclaration("let",[l.variableDeclarator(r.left)]),r.right,l.blockStatement([i]))}}var r=function(e){return e&&e.__esModule?e:{"default":e}};t.exports=n;var l=r(e("../../types"))},{"../../types":153}],52:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("lodash/lang/isString")),i=n(e("../../messages")),s=r(e("esutils")),a=n(e("./react")),o=n(e("../../types"));t.exports=function(e,t){e.check=function(e){return o.isJSX(e)?!0:a.isCreateClass(e)?!0:!1},e.JSXIdentifier=function(e,t){return"this"===e.name&&o.isReferenced(e,t)?o.thisExpression():s.keyword.isIdentifierName(e.name)?void(e.type="Identifier"):o.literal(e.name)},e.JSXNamespacedName=function(){throw this.errorWithNode(i.get("JSXNamespacedTags"))},e.JSXMemberExpression={exit:function(e){e.computed=o.isLiteral(e.property),e.type="MemberExpression"}},e.JSXExpressionContainer=function(e){return e.expression},e.JSXAttribute={enter:function(e){var t=e.value;o.isLiteral(t)&&l(t.value)&&(t.value=t.value.replace(/\n\s+/g," "))},exit:function(e){var t=e.value||o.literal(!0);return o.inherits(o.property("init",e.name,t),e)}},e.JSXOpeningElement={exit:function(e,r,l,i){var s,a=e.name,u=[];o.isIdentifier(a)?s=a.name:o.isLiteral(a)&&(s=a.value);var p={tagExpr:a,tagName:s,args:u};t.pre&&t.pre(p,i);var c=e.attributes;return c=c.length?n(c,i):o.literal(null),u.push(c),t.post&&t.post(p,i),p.call||o.callExpression(p.callee,u)}};var n=function(e,t){for(var n=[],r=[],l=function(){n.length&&(r.push(o.objectExpression(n)),n=[])};e.length;){var i=e.shift();o.isJSXSpreadAttribute(i)?(l(),r.push(i.argument)):n.push(i)}return l(),1===r.length?e=r[0]:(o.isObjectExpression(r[0])||r.unshift(o.objectExpression([])),e=o.callExpression(t.addHelper("extends"),r)),e};e.JSXElement={enter:function(e){e.children=a.buildChildren(e)},exit:function(e){var t=e.openingElement;return t.arguments=t.arguments.concat(e.children),t.arguments.length>=3&&(t._prettyCall=!0),o.inherits(t,e)}};var r=function(e,t){for(var n=t.arguments[0].properties,r=!0,l=0;l<n.length;l++){var i=n[l];if(o.isIdentifier(i.key,{name:"displayName"})){r=!1;break}}r&&n.unshift(o.property("init",o.identifier("displayName"),o.literal(e)))};e.ExportDefaultDeclaration=function(e,t,n,l){a.isCreateClass(e.declaration)&&r(l.opts.basename,e.declaration)},e.AssignmentExpression=e.Property=e.VariableDeclarator=function(e){var t,n;o.isAssignmentExpression(e)?(t=e.left,n=e.right):o.isProperty(e)?(t=e.key,n=e.value):o.isVariableDeclarator(e)&&(t=e.id,n=e.init),o.isMemberExpression(t)&&(t=t.property),o.isIdentifier(t)&&a.isCreateClass(n)&&r(t.name,n)}}},{"../../messages":43,"../../types":153,"./react":58,esutils:300,"lodash/lang/isString":401}],53:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../../types"));t.exports=function(e){var t=r.functionExpression(null,[],e.body,e.generator,e.async);t.shadow=!0;var n=r.callExpression(t,[]);return e.generator&&(n=r.yieldExpression(n,!0)),r.returnStatement(n)}},{"../../types":153}],54:[function(e,t,n){"use strict";function r(e,t,n,r,l){var i=d.toKeyAlias({computed:r},t),s={};c(e,i)&&(s=e[i]),e[i]=s,s._key=t,r&&(s._computed=!0),s[n]=l}function l(e){for(var t in e)if(e[t]._computed)return!0;return!1}function i(e){for(var t=d.arrayExpression([]),n=0;n<e.properties.length;n++){var r=e.properties[n],l=r.value;l.properties.unshift(d.property("init",d.identifier("key"),d.toComputedKey(r))),t.elements.push(l)}return t}function s(e){var t=d.objectExpression([]);return p(e,function(e){var n=d.objectExpression([]),r=d.property("init",e._key,n,e._computed);p(e,function(e,t){if("_"!==t[0]){var r=e;(d.isMethodDefinition(e)||d.isClassProperty(e))&&(e=e.value);var l=d.property("init",d.identifier(t),e);d.inheritsComments(l,r),d.removeComments(r),n.properties.push(l)}}),t.properties.push(r)}),t}function a(e){return p(e,function(e){e.value&&(e.writable=d.literal(!0)),e.configurable=d.literal(!0),e.enumerable=d.literal(!0)}),s(e)}var o=function(e){return e&&e.__esModule?e:{"default":e}},u=function(e){return e&&e.__esModule?e["default"]:e};n.push=r,n.hasComputed=l,n.toComputedObjectFromClass=i,n.toClassObject=s,n.toDefineObject=a,n.__esModule=!0;var p=(u(e("lodash/lang/cloneDeep")),u(e("../../traversal")),u(e("lodash/collection/each"))),c=u(e("lodash/object/has")),d=o(e("../../types"))},{"../../traversal":144,"../../types":153,"lodash/collection/each":316,"lodash/lang/cloneDeep":390,"lodash/object/has":407}],55:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../../types")),l=function(e,t,n,l){var i;if(r.isIdentifier(e)){if(l.hasBinding(e.name))return e;i=e}else{if(!r.isMemberExpression(e))throw new Error("We can't explode this node type "+e.type);if(i=e.object,r.isIdentifier(i)&&l.hasGlobal(i.name))return i}var s=l.generateUidBasedOnNode(i);return t.push(r.variableDeclaration("var",[r.variableDeclarator(s,i)])),s},i=function(e,t,n,l){var i=e.property,s=r.toComputedKey(e,i);if(r.isLiteral(s))return s;var a=l.generateUidBasedOnNode(i);return t.push(r.variableDeclaration("var",[r.variableDeclarator(a,i)])),a};t.exports=function(e,t,n,s,a){var o;o=r.isIdentifier(e)&&a?e:l(e,t,n,s);var u,p;if(r.isIdentifier(e))u=e,p=o;else{var c=i(e,t,n,s),d=e.computed||r.isLiteral(c);p=u=r.memberExpression(o,c,d)}return{uid:p,ref:u}}},{"../../types":153}],56:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../../types"));t.exports=function(e){for(var t=0,n=0;n<e.params.length;n++)r.isAssignmentPattern(e.params[n])||(t=n+1);return t}},{"../../types":153}],57:[function(e,t,n){"use strict";function r(e,t,n){var r=f(e,t.name,n);return d(r,e,t,n)}function l(e,t,n){var r=p.toComputedKey(e,e.key);if(!p.isLiteral(r))return e;var l=p.toIdentifier(r.value),i=p.identifier(l),s=e.value,a=f(s,l,n);e.value=d(a,s,i,n)}function i(e,t,n){if(e.id)return e;var r;if(!p.isProperty(t)||"init"!==t.kind||t.computed&&!p.isLiteral(t.key)){if(!p.isVariableDeclarator(t))return e;r=t.id}else r=t.key;var l;if(p.isLiteral(r))l=r.value;else{if(!p.isIdentifier(r))return;l=r.name}l=p.toIdentifier(l),r=p.identifier(l);var i=f(e,l,n);return d(i,e,r,n)}var s=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e};n.custom=r,n.property=l,n.bare=i,n.__esModule=!0;var o=a(e("./get-function-arity")),u=s(e("../../util")),p=s(e("../../types")),c={enter:function(e,t,n,r){if(this.isReferencedIdentifier({name:r.name})){var l=n.getBindingIdentifier(r.name);l===r.outerDeclar&&(r.selfReference=!0,this.stop())}}},d=function(e,t,n,r){if(e.selfReference){var l="property-method-assignment-wrapper";t.generator&&(l+="-generator");for(var i=u.template(l,{FUNCTION:t,FUNCTION_ID:n,FUNCTION_KEY:r.generateUidIdentifier(n.name)}),s=i.callee.body.body[0].params,a=0,p=o(t);p>a;a++)s.push(r.generateUidIdentifier("x"));return i}return t.id=n,t},f=function(e,t,n){var r={selfAssignment:!1,selfReference:!1,outerDeclar:n.getBindingIdentifier(t),references:[],name:t},l=n.getOwnBindingInfo(t);return l?"param"===l.kind&&(r.selfReference=!0):n.traverse(e,c,r),r}},{"../../types":153,"../../util":157,"./get-function-arity":56}],58:[function(e,t,n){"use strict";function r(e){if(!e||!u.isCallExpression(e))return!1;if(!p(e.callee))return!1;var t=e.arguments;if(1!==t.length)return!1;var n=t[0];return u.isObjectExpression(n)?!0:!1}function l(e){return e&&/^[a-z]|\-/.test(e)}function i(e,t){var n,r=e.value.split(/\r\n|\n|\r/),l=0;for(n=0;n<r.length;n++)r[n].match(/[^ \t]/)&&(l=n);var i="";for(n=0;n<r.length;n++){var s=r[n],a=0===n,o=n===r.length-1,p=n===l,c=s.replace(/\t/g," ");a||(c=c.replace(/^[ ]+/,"")),o||(c=c.replace(/[ ]+$/,"")),c&&(p||(c+=" "),i+=c)}i&&t.push(u.literal(i))}function s(e){for(var t=[],n=0;n<e.children.length;n++){var r=e.children[n];u.isLiteral(r)&&"string"==typeof r.value?i(r,t):(u.isJSXExpressionContainer(r)&&(r=r.expression),u.isJSXEmptyExpression(r)||t.push(r))}return t}var a=function(e){return e&&e.__esModule?e:{"default":e}},o=function(e){return e&&e.__esModule?e["default"]:e};n.isCreateClass=r,n.isCompatTag=l,n.buildChildren=s,n.__esModule=!0;var u=(o(e("lodash/lang/isString")),a(e("../../types"))),p=u.buildMatchMemberExpression("React.createClass"),c=u.buildMatchMemberExpression("React.Component");n.isReactComponent=c},{"../../types":153,"lodash/lang/isString":401}],59:[function(e,t,n){"use strict";function r(e,t){return o.isLiteral(e)&&e.regex&&e.regex.flags.indexOf(t)>=0}function l(e,t){var n=e.regex.flags.split("");e.regex.flags.indexOf(t)<0||(a(n,t),e.regex.flags=n.join(""))}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.is=r,n.pullFlag=l,n.__esModule=!0;var a=s(e("lodash/array/pull")),o=i(e("../../types"))},{"../../types":153,"lodash/array/pull":313}],60:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../../types")),l={enter:function(e){r.isFunction(e)&&this.skip(),r.isAwaitExpression(e)&&(e.type="YieldExpression",e.all&&(e.all=!1,e.argument=r.callExpression(r.memberExpression(r.identifier("Promise"),r.identifier("all")),[e.argument])))}},i={enter:function(e,t,n,l){var i=l.id.name;if(r.isReferencedIdentifier(e,t,{name:i})&&n.bindingIdentifierEquals(i,l.id)){var s;return s=l,!s.ref&&(s.ref=n.generateUidIdentifier(i)),s.ref}}};t.exports=function(e,t,n){e.async=!1,e.generator=!0,n.traverse(e,l,u);var s=r.callExpression(t,[e]),a=e.id;if(e.id=null,r.isFunctionDeclaration(e)){var o=r.variableDeclaration("let",[r.variableDeclarator(a,s)]);return o._blockHoist=!0,o}if(a){var u={id:a};if(n.traverse(e,i,u),u.ref)return n.parent.push({id:u.ref}),r.assignmentExpression("=",u.ref,s)}return s}},{"../../types":153}],61:[function(e,t){"use strict";function n(e,t){return o.isSuper(e)?o.isMemberExpression(t,{computed:!1})?!1:o.isCallExpression(t,{callee:e})?!1:!0:!1}function r(e){return o.isMemberExpression(e)&&o.isSuper(e.object)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("../../messages")),o=l(e("../../types")),u={enter:function(e,t,n,r){var l=r.topLevel,i=r.self;if(o.isFunction(e)&&!o.isArrowFunctionExpression(e))return i.traverseLevel(this,!1),this.skip();if(o.isProperty(e,{method:!0})||o.isMethodDefinition(e))return this.skip();var s=l?o.thisExpression:i.getThisReference.bind(i),a=i.specHandle;i.isLoose&&(a=i.looseHandle);var u=a.call(i,this,s);return u&&(this.hasSuper=!0),u!==!0?u:void 0}},p=function(){function e(t){var n=void 0===arguments[1]?!1:arguments[1];s(this,e),this.topLevelThisReference=t.topLevelThisReference,this.methodPath=t.methodPath,this.methodNode=t.methodNode,this.superRef=t.superRef,this.isStatic=t.isStatic,this.hasSuper=!1,this.inClass=n,this.isLoose=t.isLoose,this.scope=t.scope,this.file=t.file,this.opts=t}return e.prototype.getObjectRef=function(){return this.opts.objectRef||this.opts.getObjectRef()},e.prototype.setSuperProperty=function(e,t,n,r){return o.callExpression(this.file.addHelper("set"),[o.callExpression(o.memberExpression(o.identifier("Object"),o.identifier("getPrototypeOf")),[this.isStatic?this.getObjectRef():o.memberExpression(this.getObjectRef(),o.identifier("prototype"))]),n?e:o.literal(e.name),t,r])},e.prototype.getSuperProperty=function(e,t,n){return o.callExpression(this.file.addHelper("get"),[o.callExpression(o.memberExpression(o.identifier("Object"),o.identifier("getPrototypeOf")),[this.isStatic?this.getObjectRef():o.memberExpression(this.getObjectRef(),o.identifier("prototype"))]),t?e:o.literal(e.name),n])},e.prototype.replace=function(){this.traverseLevel(this.methodPath.get("value"),!0)},e.prototype.traverseLevel=function(e,t){var n={self:this,topLevel:t};e.traverse(u,n)},e.prototype.getThisReference=function(){if(this.topLevelThisReference)return this.topLevelThisReference;var e=this.topLevelThisReference=this.scope.generateUidIdentifier("this");return this.methodNode.value.body.body.unshift(o.variableDeclaration("var",[o.variableDeclarator(this.topLevelThisReference,o.thisExpression())])),e},e.prototype.getLooseSuperProperty=function(e,t){var n=this.methodNode,r=n.key,l=this.superRef||o.identifier("Function");return t.property===e?void 0:o.isCallExpression(t,{callee:e})?(t.arguments.unshift(o.thisExpression()),"constructor"===r.name?o.memberExpression(l,o.identifier("call")):(e=l,n["static"]||(e=o.memberExpression(e,o.identifier("prototype"))),e=o.memberExpression(e,r,n.computed),o.memberExpression(e,o.identifier("call")))):o.isMemberExpression(t)&&!n["static"]?o.memberExpression(l,o.identifier("prototype")):l},e.prototype.looseHandle=function(e,t){var n=e.node;if(e.isSuper())return this.getLooseSuperProperty(n,e.parent);if(e.isCallExpression()){var r=n.callee;if(!o.isMemberExpression(r))return;if(!o.isSuper(r.object))return;return o.appendToMemberExpression(r,o.identifier("call")),n.arguments.unshift(t()),!0}},e.prototype.specHandleAssignmentExpression=function(e,t,n,r){return"="===n.operator?this.setSuperProperty(n.left.property,n.right,n.left.computed,r()):(e||(e=t.scope.generateUidIdentifier("ref")),[o.variableDeclaration("var",[o.variableDeclarator(e,n.left)]),o.expressionStatement(o.assignmentExpression("=",n.left,o.binaryExpression(n.operator[0],e,n.right)))])},e.prototype.specHandle=function(e,t){var l,s,u,p,c=this.methodNode,d=e.parent,f=e.node;if(n(f,d))throw e.errorWithNode(a.get("classesIllegalBareSuper"));if(o.isCallExpression(f)){var h=f.callee;if(o.isSuper(h)){if(l=c.key,s=c.computed,u=f.arguments,"constructor"!==c.key.name||!this.inClass){var m=c.key.name||"METHOD_NAME";throw this.file.errorWithNode(f,a.get("classesIllegalSuperCall",m))}}else r(h)&&(l=h.property,s=h.computed,u=f.arguments)}else if(o.isMemberExpression(f)&&o.isSuper(f.object))l=f.property,s=f.computed;else{if(o.isUpdateExpression(f)&&r(f.argument)){var g=o.binaryExpression(f.operator[0],f.argument,o.literal(1));if(f.prefix)return this.specHandleAssignmentExpression(null,e,g,t);var y=e.scope.generateUidIdentifier("ref");return this.specHandleAssignmentExpression(y,e,g,t).concat(o.expressionStatement(y))
}if(o.isAssignmentExpression(f)&&r(f.left))return this.specHandleAssignmentExpression(null,e,f,t)}if(l){p=t();var b=this.getSuperProperty(l,s,p);return u?1===u.length&&o.isSpreadElement(u[0])?o.callExpression(o.memberExpression(b,o.identifier("apply")),[p,u[0].argument]):o.callExpression(o.memberExpression(b,o.identifier("call")),[p].concat(i(u))):b}},e}();t.exports=p},{"../../messages":43,"../../types":153}],62:[function(e,t,n){"use strict";function r(e){var t=e.body[0];return s.isExpressionStatement(t)&&s.isLiteral(t.expression,{value:"use strict"})}function l(e,t){var n;r(e)&&(n=e.body.shift()),t(),n&&e.body.unshift(n)}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.has=r,n.wrap=l,n.__esModule=!0;var s=i(e("../../types"))},{"../../types":153}],63:[function(e,t){"use strict";function n(e,t){var n=new a(t);return n.parse(e)}var r=function(e){return e&&e.__esModule?e["default"]:e};t.exports=n;var l=r(e("../helpers/normalize-ast")),i=r(e("./transformer")),s=r(e("../helpers/object")),a=r(e("./file")),o=r(e("lodash/collection/each"));n.fromAst=function(e,t,n){e=l(e);var r=new a(n);return r.addCode(t),r.transform(e),r.generate()},n._ensureTransformerNames=function(e,t){for(var r=[],l=0;l<t.length;l++){var i=t[l],s=n.deprecatedTransformerMap[i],a=n.aliasTransformerMap[i];if(a)r.push(a);else if(s)console.error("The transformer "+i+" has been renamed to "+s),t.push(s);else if(n.transformers[i])r.push(i);else{if(!n.namespaces[i])throw new ReferenceError("Unknown transformer "+i+" specified in "+e);r=r.concat(n.namespaces[i])}}return r},n.transformerNamespaces=s(),n.transformers=s(),n.namespaces=s(),n.deprecatedTransformerMap=e("./transformers/deprecated"),n.aliasTransformerMap=e("./transformers/aliases"),n.moduleFormatters=e("./modules");var u=r(e("./transformers"));o(u,function(e,t){var r=t.split(".")[0],l=n.namespaces,s=r;l[s]||(l[s]=[]),n.namespaces[r].push(t),n.transformerNamespaces[t]=r,n.transformers[t]=new i(t,e)})},{"../helpers/normalize-ast":40,"../helpers/object":41,"./file":46,"./modules":71,"./transformer":76,"./transformers":110,"./transformers/aliases":77,"./transformers/deprecated":78,"lodash/collection/each":316}],64:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("../../messages")),s=n(e("../../traversal")),a=n(e("lodash/object/extend")),o=n(e("../../helpers/object")),u=r(e("../../util")),p=r(e("../../types")),c={enter:function(e,t,n,r){var l=r.internalRemap[e.name];if(this.isReferencedIdentifier()&&l&&(!n.hasBinding(e.name)||n.bindingIdentifierEquals(e.name,r.localImports[e.name])))return l;if(p.isUpdateExpression(e)){var i=r.getExport(e.argument,n);if(i){this.skip();var s=p.assignmentExpression(e.operator[0]+"=",e.argument,p.literal(1)),a=r.remapExportAssignment(s,i);if(p.isExpressionStatement(t)||e.prefix)return a;var o=[];o.push(a);var u;return u="--"===e.operator?"+":"-",o.push(p.binaryExpression(u,e.argument,p.literal(1))),p.sequenceExpression(o)}}if(p.isAssignmentExpression(e)&&!e._ignoreModulesRemap){var i=r.getExport(e.left,n);if(i)return this.skip(),r.remapExportAssignment(e,i)}}},d={ImportDeclaration:{enter:function(e,t,n,r){r.hasLocalImports=!0,a(r.localImports,this.getBindingIdentifiers())}}},f=s.explode({ExportDeclaration:{enter:function(e,t,n,r){r.hasLocalExports=!0;var l=this.get("declaration");if(l.isStatement()){var i=l.getBindingIdentifiers();for(var s in i){var a=i[s];r._addExport(s,a)}}if(this.isExportNamedDeclaration()&&e.specifiers)for(var o=0;o<e.specifiers.length;o++){var u=e.specifiers[o],c=u.local;c&&r._addExport(c.name,u.exported)}if(!p.isExportDefaultDeclaration(e)){var d=e.specifiers&&1===e.specifiers.length&&p.isSpecifierDefault(e.specifiers[0]);d||(r.hasNonDefaultExports=!0)}}}}),h=function(){function e(t){l(this,e),this.internalRemap=o(),this.defaultIds=o(),this.scope=t.scope,this.file=t,this.ids=o(),this.hasNonDefaultExports=!1,this.hasLocalExports=!1,this.hasLocalImports=!1,this.localExports=o(),this.localImports=o(),this.getLocalExports(),this.getLocalImports()}return e.prototype.transform=function(){this.remapAssignments()},e.prototype.doDefaultExportInterop=function(e){return(p.isExportDefaultDeclaration(e)||p.isSpecifierDefault(e))&&!this.noInteropRequireExport&&!this.hasNonDefaultExports},e.prototype.getLocalExports=function(){this.file.path.traverse(f,this)},e.prototype.getLocalImports=function(){this.file.path.traverse(d,this)},e.prototype.remapAssignments=function(){(this.hasLocalExports||this.hasLocalImports)&&this.file.path.traverse(c,this)},e.prototype.remapExportAssignment=function(e,t){for(var n=e,r=0;r<t.length;r++)n=p.assignmentExpression("=",p.memberExpression(p.identifier("exports"),t[r]),n);return n},e.prototype._addExport=function(e,t){var n,r,l=(n=this.localExports,r=e,!n[r]&&(n[r]={binding:this.scope.getBindingIdentifier(e),exported:[]}),n[r]);l.exported.push(t)},e.prototype.getExport=function(e,t){if(p.isIdentifier(e)){var n=this.localExports[e.name];return n&&n.binding===t.getBindingIdentifier(e.name)?n.exported:void 0}},e.prototype.getModuleName=function(){var e=this.file.opts;if(e.moduleId)return e.moduleId;var t=e.filenameRelative,n="";if(e.moduleRoot&&(n=e.moduleRoot+"/"),!e.filenameRelative)return n+e.filename.replace(/^\//,"");if(e.sourceRoot){var r=new RegExp("^"+e.sourceRoot+"/?");t=t.replace(r,"")}return e.keepModuleIdExtensions||(t=t.replace(/\.(\w*?)$/,"")),n+=t,n=n.replace(/\\/g,"/")},e.prototype._pushStatement=function(e,t){return(p.isClass(e)||p.isFunction(e))&&e.id&&(t.push(p.toStatement(e)),e=e.id),e},e.prototype._hoistExport=function(e,t,n){return p.isFunctionDeclaration(e)&&(t._blockHoist=n||2),t},e.prototype.getExternalReference=function(e,t){var n=this.ids,r=e.source.value;return n[r]?n[r]:this.ids[r]=this._getExternalReference(e,t)},e.prototype.checkExportIdentifier=function(e){if(p.isIdentifier(e,{name:"__esModule"}))throw this.file.errorWithNode(e,i.get("modulesIllegalExportName",e.name))},e.prototype.exportAllDeclaration=function(e,t){var n=this.getExternalReference(e,t);t.push(this.buildExportsWildcard(n,e))},e.prototype.isLoose=function(){return this.file.isLoose("es6.modules")},e.prototype.exportSpecifier=function(e,t,n){if(t.source){var r=this.getExternalReference(t,n);if("default"!==e.local.name||this.noInteropRequireExport){if(r=p.memberExpression(r,e.local),!this.isLoose())return void n.push(this.buildExportsFromAssignment(e.exported,r,t))}else r=p.callExpression(this.file.addHelper("interop-require"),[r]);n.push(this.buildExportsAssignment(e.exported,r,t))}else n.push(this.buildExportsAssignment(e.exported,e.local,t))},e.prototype.buildExportsWildcard=function(e){return p.expressionStatement(p.callExpression(this.file.addHelper("defaults"),[p.identifier("exports"),p.callExpression(this.file.addHelper("interop-require-wildcard"),[e])]))},e.prototype.buildExportsFromAssignment=function(e,t){return this.checkExportIdentifier(e),u.template("exports-from-assign",{INIT:t,ID:p.literal(e.name)},!0)},e.prototype.buildExportsAssignment=function(e,t){return this.checkExportIdentifier(e),u.template("exports-assign",{VALUE:t,KEY:e},!0)},e.prototype.exportDeclaration=function(e,t){var n=e.declaration,r=n.id;p.isExportDefaultDeclaration(e)&&(r=p.identifier("default"));var l;if(p.isVariableDeclaration(n))for(var i=0;i<n.declarations.length;i++){var s=n.declarations[i];s.init=this.buildExportsAssignment(s.id,s.init,e).expression;var a=p.variableDeclaration(n.kind,[s]);0===i&&p.inherits(a,n),t.push(a)}else{var o=n;(p.isFunctionDeclaration(n)||p.isClassDeclaration(n))&&(o=n.id,t.push(n)),l=this.buildExportsAssignment(r,o,e),t.push(l),this._hoistExport(n,l)}},e}();t.exports=h},{"../../helpers/object":41,"../../messages":43,"../../traversal":144,"../../types":153,"../../util":157,"lodash/object/extend":406}],65:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=n(e("../../util"));t.exports=function(e){var t=function(){this.noInteropRequireImport=!0,this.noInteropRequireExport=!0,e.apply(this,arguments)};return r.inherits(t,e),t}},{"../../util":157}],66:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=n(e("./amd")),l=n(e("./_strict"));t.exports=l(r)},{"./_strict":65,"./amd":67}],67:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=r(e("./_default")),a=r(e("./common")),o=r(e("lodash/collection/includes")),u=r(e("lodash/object/values")),p=n(e("../../util")),c=n(e("../../types")),d=function(e){function t(){i(this,t),null!=e&&e.apply(this,arguments)}return l(t,e),t.prototype.init=function(){a.prototype._init.call(this,this.hasNonDefaultExports)},t.prototype.buildDependencyLiterals=function(){var e=[];for(var t in this.ids)e.push(c.literal(t));return e},t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments);var t=e.body,n=[c.literal("exports")];this.passModuleArg&&n.push(c.literal("module")),n=n.concat(this.buildDependencyLiterals()),n=c.arrayExpression(n);var r=u(this.ids);this.passModuleArg&&r.unshift(c.identifier("module")),r.unshift(c.identifier("exports"));var l=c.functionExpression(null,r,c.blockStatement(t)),i=[n,l],a=this.getModuleName();a&&i.unshift(c.literal(a));var o=c.callExpression(c.identifier("define"),i);e.body=[c.expressionStatement(o)]},t.prototype.getModuleName=function(){return this.file.opts.moduleIds?s.prototype.getModuleName.apply(this,arguments):null},t.prototype._getExternalReference=function(e){return this.scope.generateUidIdentifier(e.source.value)},t.prototype.importDeclaration=function(e){this.getExternalReference(e)},t.prototype.importSpecifier=function(e,t,n){var r=t.source.value,l=this.getExternalReference(t);if((c.isImportNamespaceSpecifier(e)||c.isImportDefaultSpecifier(e))&&(this.defaultIds[r]=e.local),o(this.file.dynamicImportedNoDefault,t))this.ids[t.source.value]=l;else if(c.isImportNamespaceSpecifier(e));else if(o(this.file.dynamicImported,t)||!c.isSpecifierDefault(e)||this.noInteropRequireImport){var i=e.imported;c.isSpecifierDefault(e)&&(i=c.identifier("default")),l=c.memberExpression(l,i)}else{var s=this.scope.generateUidIdentifier(e.local.name);n.push(c.variableDeclaration("var",[c.variableDeclarator(s,c.callExpression(this.file.addHelper("interop-require"),[l]))])),l=s}this.internalRemap[e.local.name]=l},t.prototype.exportSpecifier=function(e,t,n){this.doDefaultExportInterop(e)?n.push(p.template("exports-default-assign",{VALUE:e.local},!0)):a.prototype.exportSpecifier.apply(this,arguments)},t.prototype.exportDeclaration=function(e,t){if(this.doDefaultExportInterop(e)){this.passModuleArg=!0;var n=e.declaration,r=p.template("exports-default-assign",{VALUE:this._pushStatement(n,t)},!0);return c.isFunctionDeclaration(n)&&(r._blockHoist=3),void t.push(r)}s.prototype.exportDeclaration.apply(this,arguments)},t}(s);t.exports=d},{"../../types":153,"../../util":157,"./_default":64,"./common":69,"lodash/collection/includes":319,"lodash/object/values":411}],68:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=n(e("./common")),l=n(e("./_strict"));t.exports=l(r)},{"./_strict":65,"./common":69}],69:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=r(e("./_default")),a=r(e("lodash/collection/includes")),o=n(e("../../util")),u=n(e("../../types")),p=function(e){function t(){i(this,t),null!=e&&e.apply(this,arguments)}return l(t,e),t.prototype.init=function(){this._init(this.hasLocalExports)},t.prototype._init=function(e){var t=this.file,n=t.scope;if(n.rename("module"),n.rename("exports"),!this.noInteropRequireImport&&e){var r="exports-module-declaration";this.file.isLoose("es6.modules")&&(r+="-loose");var l=o.template(r,!0);l._blockHoist=3,t.ast.program.body.unshift(l)}},t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments),this.hasDefaultOnlyExport&&e.body.push(u.expressionStatement(u.assignmentExpression("=",u.memberExpression(u.identifier("module"),u.identifier("exports")),u.memberExpression(u.identifier("exports"),u.identifier("default")))))},t.prototype.importSpecifier=function(e,t,n){var r=e.local,l=this.getExternalReference(t,n);if(u.isSpecifierDefault(e)){if(a(this.file.dynamicImportedNoDefault,t))this.internalRemap[r.name]=l;else if(this.noInteropRequireImport)this.internalRemap[r.name]=u.memberExpression(l,u.identifier("default"));else if(!a(this.file.dynamicImported,t)){var i=this.scope.generateUidBasedOnNode(t,"import");n.push(u.variableDeclaration("var",[u.variableDeclarator(i,u.callExpression(this.file.addHelper("interop-require-wildcard"),[l]))])),this.internalRemap[r.name]=u.memberExpression(i,u.identifier("default"))}}else u.isImportNamespaceSpecifier(e)?(this.noInteropRequireImport||(l=u.callExpression(this.file.addHelper("interop-require-wildcard"),[l])),n.push(u.variableDeclaration("var",[u.variableDeclarator(r,l)]))):this.internalRemap[r.name]=u.memberExpression(l,e.imported)},t.prototype.importDeclaration=function(e,t){t.push(o.template("require",{MODULE_NAME:e.source},!0))},t.prototype.exportSpecifier=function(e){this.doDefaultExportInterop(e)&&(this.hasDefaultOnlyExport=!0),s.prototype.exportSpecifier.apply(this,arguments)},t.prototype.exportDeclaration=function(e){this.doDefaultExportInterop(e)&&(this.hasDefaultOnlyExport=!0),s.prototype.exportDeclaration.apply(this,arguments)},t.prototype._getExternalReference=function(e,t){var n,r=(e.source.value,u.callExpression(u.identifier("require"),[e.source]));a(this.file.dynamicImported,e)&&!a(this.file.dynamicImportedNoDefault,e)?(r=u.memberExpression(r,u.identifier("default")),n=e.specifiers[0].local):n=this.scope.generateUidBasedOnNode(e,"import");var l=u.variableDeclaration("var",[u.variableDeclarator(n,r)]);return t.push(l),n},t}(s);t.exports=p},{"../../types":153,"../../util":157,"./_default":64,"lodash/collection/includes":319}],70:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("../../types")),i=function(){function e(){r(this,e)}return e.prototype.exportDeclaration=function(e,t){var n=l.toStatement(e.declaration,!0);n&&t.push(l.inherits(n,e))},e.prototype.exportAllDeclaration=function(){},e.prototype.importDeclaration=function(){},e.prototype.importSpecifier=function(){},e.prototype.exportSpecifier=function(){},e}();t.exports=i},{"../../types":153}],71:[function(e,t){"use strict";t.exports={commonStrict:e("./common-strict"),amdStrict:e("./amd-strict"),umdStrict:e("./umd-strict"),common:e("./common"),system:e("./system"),ignore:e("./ignore"),amd:e("./amd"),umd:e("./umd")}},{"./amd":67,"./amd-strict":66,"./common":69,"./common-strict":68,"./ignore":70,"./system":72,"./umd":74,"./umd-strict":73}],72:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=r(e("./_default")),a=r(e("./amd")),o=n(e("../../util")),u=r(e("lodash/array/last")),p=r(e("lodash/collection/each")),c=r(e("lodash/collection/map")),d=n(e("../../types")),f=function(e,t){return e._blockHoist&&!t.transformers.runtime.canTransform()},h={enter:function(e,t,n,r){if(d.isFunction(e))return this.skip();if(d.isVariableDeclaration(e)){if("var"!==e.kind&&!d.isProgram(t))return;if(f(e,n.file))return;for(var l=[],i=0;i<e.declarations.length;i++){var s=e.declarations[i];if(r.push(d.variableDeclarator(s.id)),s.init){var a=d.expressionStatement(d.assignmentExpression("=",s.id,s.init));l.push(a)}}if(d.isFor(t)){if(t.left===e)return e.declarations[0].id;if(t.init===e)return l}return l}}},m={enter:function(e,t,n,r){d.isFunction(e)&&this.skip(),(d.isFunctionDeclaration(e)||f(e,n.file))&&(r.push(e),this.remove())}},g={enter:function(e,t,n,r){e._importSource===r.source&&(d.isVariableDeclaration(e)?p(e.declarations,function(e){r.hoistDeclarators.push(d.variableDeclarator(e.id)),r.nodes.push(d.expressionStatement(d.assignmentExpression("=",e.id,e.init)))}):r.nodes.push(e),this.remove())}},y=function(e){function t(e){i(this,t),this.exportIdentifier=e.scope.generateUidIdentifier("export"),this.noInteropRequireExport=!0,this.noInteropRequireImport=!0,s.apply(this,arguments)}return l(t,e),t.prototype._addImportSource=function(e,t){return e&&(e._importSource=t.source&&t.source.value),e},t.prototype.buildExportsWildcard=function(e,t){var n=this.scope.generateUidIdentifier("key"),r=d.memberExpression(e,n,!0),l=d.variableDeclaration("var",[d.variableDeclarator(n)]),i=e,s=d.blockStatement([d.expressionStatement(this.buildExportCall(n,r))]);return this._addImportSource(d.forInStatement(l,i,s),t)},t.prototype.buildExportsAssignment=function(e,t,n){var r=this.buildExportCall(d.literal(e.name),t,!0);return this._addImportSource(r,n)},t.prototype.buildExportsFromAssignment=function(){return this.buildExportsAssignment.apply(this,arguments)},t.prototype.remapExportAssignment=function(e,t){for(var n=e,r=0;r<t.length;r++)n=this.buildExportCall(d.literal(t[r].name),n);return n},t.prototype.buildExportCall=function(e,t,n){var r=d.callExpression(this.exportIdentifier,[e,t]);return n?d.expressionStatement(r):r},t.prototype.importSpecifier=function(e,t,n){a.prototype.importSpecifier.apply(this,arguments);for(var r in this.internalRemap)n.push(d.variableDeclaration("var",[d.variableDeclarator(d.identifier(r),this.internalRemap[r])]));this.internalRemap={},this._addImportSource(u(n),t)},t.prototype.buildRunnerSetters=function(e,t){var n=this.file.scope;return d.arrayExpression(c(this.ids,function(r,l){var i={hoistDeclarators:t,source:l,nodes:[]};return n.traverse(e,g,i),d.functionExpression(null,[r],d.blockStatement(i.nodes))}))},t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments);var t=[],n=this.getModuleName(),r=d.literal(n),l=d.blockStatement(e.body),i=o.template("system",{MODULE_DEPENDENCIES:d.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,MODULE_NAME:r,SETTERS:this.buildRunnerSetters(l,t),EXECUTE:d.functionExpression(null,[],l)},!0),a=i.expression.arguments[2].body.body;n||i.expression.arguments.shift();var u=a.pop();if(this.file.scope.traverse(l,h,t),t.length){var p=d.variableDeclaration("var",t);p._blockHoist=!0,a.unshift(p)}this.file.scope.traverse(l,m,a),a.push(u),e.body=[i]},t}(a);t.exports=y},{"../../types":153,"../../util":157,"./_default":64,"./amd":67,"lodash/array/last":312,"lodash/collection/each":316,"lodash/collection/map":320}],73:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=n(e("./umd")),l=n(e("./_strict"));t.exports=l(r)},{"./_strict":65,"./umd":74}],74:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=r(e("./_default")),a=r(e("./amd")),o=r(e("lodash/object/values")),u=n(e("../../util")),p=n(e("../../types")),c=function(e){function t(){i(this,t),null!=e&&e.apply(this,arguments)}return l(t,e),t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments);var t=e.body,n=[];for(var r in this.ids)n.push(p.literal(r));var l=o(this.ids),i=[p.identifier("exports")];this.passModuleArg&&i.push(p.identifier("module")),i=i.concat(l);var a=p.functionExpression(null,i,p.blockStatement(t)),c=[p.literal("exports")];this.passModuleArg&&c.push(p.literal("module")),c=c.concat(n),c=[p.arrayExpression(c)];var d=u.template("test-exports"),f=u.template("test-module"),h=this.passModuleArg?p.logicalExpression("&&",d,f):d,m=[p.identifier("exports")];this.passModuleArg&&m.push(p.identifier("module")),m=m.concat(n.map(function(e){return p.callExpression(p.identifier("require"),[e])}));var g=[];this.passModuleArg&&g.push(p.identifier("mod"));for(var y in this.ids){var b=this.defaultIds[y]||p.identifier(p.toIdentifier(y));g.push(p.memberExpression(p.identifier("global"),b))}var v=this.getModuleName();v&&c.unshift(p.literal(v));var x=this.file.opts.basename;v&&(x=v),x=p.identifier(p.toIdentifier(x));var E=u.template("umd-runner-body",{AMD_ARGUMENTS:c,COMMON_TEST:h,COMMON_ARGUMENTS:m,BROWSER_ARGUMENTS:g,GLOBAL_ARG:x});e.body=[p.expressionStatement(p.callExpression(E,[p.thisExpression(),a]))]},t}(a);t.exports=c},{"../../types":153,"../../util":157,"./_default":64,"./amd":67,"lodash/object/values":411}],75:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("lodash/collection/includes")),i=n(e("../traversal")),s=function(){function e(t,n){r(this,e),this.transformer=n,this.shouldRun=!n.check,this.handlers=n.handlers,this.file=t,this.ran=!1}return e.prototype.canTransform=function(){var e=this.transformer,t=this.file.opts,n=e.key;if("_"===n[0])return!0;var r=t.blacklist;if(r.length&&l(r,n))return!1;var i=t.whitelist;if(i)return l(i,n);var s=e.metadata.stage;return null!=s&&s>=t.stage?!0:e.metadata.optional&&!l(t.optional,n)?!1:!0},e.prototype.checkNode=function(e){var t=this.transformer.check;return t?this.shouldRun=t(e):!0},e.prototype.transform=function(){if(this.shouldRun){var e=this.file;e.log.debug("Running transformer "+this.transformer.key),i(e.ast,this.handlers,e.scope,e),this.ran=!0}},e}();t.exports=s},{"../traversal":144,"lodash/collection/includes":319}],76:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("./transformer-pass")),s=r(e("lodash/lang/isFunction")),a=r(e("../traversal")),o=r(e("lodash/lang/isObject")),u=r(e("lodash/object/assign")),p=(n(e("../../acorn")),r(e("./file"))),c=r(e("lodash/collection/each")),d=function(){function e(t,n){l(this,e),n=u({},n);var r=function(e){var t=n[e];return delete n[e],t};this.manipulateOptions=r("manipulateOptions"),this.metadata=r("metadata")||{},this.parser=r("parser"),this.check=r("check"),this.post=r("post"),this.pre=r("pre"),null!=this.metadata.stage&&(this.metadata.optional=!0),this.handlers=this.normalize(n);var i=this;i.opts||(i.opts={}),this.key=t}return e.prototype.normalize=function(e){var t=this;return s(e)&&(e={ast:e}),a.explode(e),c(e,function(n,r){return"_"===r[0]?void(t[r]=n):void("enter"!==r&&"exit"!==r&&(s(n)&&(n={enter:n}),o(n)&&(n.enter||(n.enter=function(){}),n.exit||(n.exit=function(){}),e[r]=n)))}),e},e.prototype.buildPass=function(e){if(!(e instanceof p))throw new TypeError("Transformer "+this.key+" is resolving to a different Babel version to what is doing the actual transformation...");return new i(e,this)},e}();t.exports=d},{"../../acorn":5,"../traversal":144,"./file":46,"./transformer-pass":75,"lodash/collection/each":316,"lodash/lang/isFunction":395,"lodash/lang/isObject":398,"lodash/object/assign":404}],77:[function(e,t){t.exports={useStrict:"strict","es5.runtime":"runtime","es6.runtime":"runtime"}},{}],78:[function(e,t){t.exports={selfContained:"runtime","unicode-regex":"regex.unicode","spec.typeofSymbol":"es6.spec.symbols","es6.symbols":"es6.spec.symbols","es6.blockScopingTDZ":"es6.spec.blockScoping","minification.deadCodeElimination":"utility.deadCodeElimination","minification.removeConsoleCalls":"utility.removeConsole","minification.removeDebugger":"utility.removeDebugger"}},{}],79:[function(e,t,n){"use strict";function r(e){var t=e.property;e.computed&&i.isLiteral(t)&&i.isValidIdentifier(t.value)?(e.property=i.identifier(t.value),e.computed=!1):e.computed||!i.isIdentifier(t)||i.isValidIdentifier(t.name)||(e.property=i.literal(t.name),e.computed=!0)}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.MemberExpression=r,n.__esModule=!0;var i=l(e("../../../types"))},{"../../../types":153}],80:[function(e,t,n){"use strict";function r(e){var t=e.key;i.isLiteral(t)&&i.isValidIdentifier(t.value)?(e.key=i.identifier(t.value),e.computed=!1):e.computed||!i.isIdentifier(t)||i.isValidIdentifier(t.name)||(e.key=i.literal(t.name))}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.Property=r,n.__esModule=!0;var i=l(e("../../../types"))},{"../../../types":153}],81:[function(e,t,n){"use strict";function r(e){return a.isProperty(e)&&("get"===e.kind||"set"===e.kind)}function l(e){var t={},n=!1;return e.properties=e.properties.filter(function(e){return"get"===e.kind||"set"===e.kind?(n=!0,s.push(t,e.key,e.kind,e.computed,e.value),!1):!0}),n?a.callExpression(a.memberExpression(a.identifier("Object"),a.identifier("defineProperties")),[e,s.toDefineObject(t)]):void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.ObjectExpression=l,n.__esModule=!0;var s=i(e("../../helpers/define-map")),a=i(e("../../../types"))},{"../../../types":153,"../../helpers/define-map":54}],82:[function(e,t,n){"use strict";function r(e){return i.ensureBlock(e),e.expression=!1,e.type="FunctionExpression",e.shadow=!0,e}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.ArrowFunctionExpression=r,n.__esModule=!0;var i=l(e("../../../types")),s=i.isArrowFunctionExpression;n.check=s},{"../../../types":153}],83:[function(e,t,n){"use strict";function r(e,t){if(!v.isVariableDeclaration(e))return!1;if(e._let)return!0;if("let"!==e.kind)return!1;if(l(e,t))for(var n=0;n<e.declarations.length;n++){var r=e.declarations[n],i=r;i.init||(i.init=v.identifier("undefined"))}return e._let=!0,e.kind="var",!0}function l(e,t){return!v.isFor(t)||!v.isFor(t,{left:e})}function i(e,t){return v.isVariableDeclaration(e,{kind:"var"})&&!r(e,t)}function s(e){for(var t=0;t<e.length;t++)delete e[t]._let}function a(e){return v.isVariableDeclaration(e)&&("let"===e.kind||"const"===e.kind)}function o(e,t,n,i){if(r(e,t)&&l(e)&&i.transformers["es6.spec.blockScoping"].canTransform()){for(var s=[e],a=0;a<e.declarations.length;a++){var o=e.declarations[a];if(o.init){var u=v.assignmentExpression("=",o.id,o.init);u._ignoreBlockScopingTDZ=!0,s.push(v.expressionStatement(u))}o.init=i.addHelper("temporal-undefined")}return e._blockHoist=2,s}}function u(e,t,n,l){var i=e.left||e.init;r(i,e)&&(v.ensureBlock(e),e.body._letDeclarators=[i]);var s=new j(this,this.get("body"),t,n,l);return s.run()}function p(e,t,n,r){if(!v.isLoop(t)){var l=new j(null,this,t,n,r);l.run()}}function c(e,t,n,r){if(v.isReferencedIdentifier(e,t)){var l=r[e.name];if(l){var i=n.getBindingIdentifier(e.name);i===l.binding?e.name=l.uid:this&&this.skip()}}}function d(e,t,n,r){c(e,t,n,r),n.traverse(e,_,r)}var f=function(e){return e&&e.__esModule?e:{"default":e}},h=function(e){return e&&e.__esModule?e["default"]:e},m=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.check=a,n.VariableDeclaration=o,n.Loop=u,n.BlockStatement=p,n.__esModule=!0;var g=h(e("../../../traversal")),y=h(e("../../../helpers/object")),b=f(e("../../../util")),v=f(e("../../../types")),x=h(e("lodash/object/values")),E=h(e("lodash/object/extend"));n.Program=p;var _={enter:c},S={enter:function(e,t,n,r){return this.isFunction()?(this.traverse(I,r),this.skip()):void 0}},I={enter:function(e,t,n,r){if(this.isReferencedIdentifier()){var l=r.letReferences[e.name];l&&n.getBindingIdentifier(e.name)===l&&(r.closurify=!0)}}},w={enter:function(e,t,n,r){if(this.isForStatement())i(e.init,e)&&(e.init=v.sequenceExpression(r.pushDeclar(e.init)));else if(this.isFor())i(e.left,e)&&(e.left=e.left.declarations[0].id);else{if(i(e,t))return r.pushDeclar(e).map(v.expressionStatement);if(this.isFunction())return this.skip()}}},k={enter:function(e,t,n,r){this.isLabeledStatement()&&r.innerLabels.push(e.label.name)}},A={enter:function(e,t,n,r){if(this.isAssignmentExpression()||this.isUpdateExpression()){var l=this.getBindingIdentifiers();for(var i in l)r.outsideReferences[i]===n.getBindingIdentifier(i)&&(r.reassignments[i]=!0)}}},C=function(e){return v.isBreakStatement(e)?"break":v.isContinueStatement(e)?"continue":void 0},T={enter:function(e,t,n,r){var l;if(this.isLoop()&&(r.ignoreLabeless=!0,this.traverse(T,r),r.ignoreLabeless=!1),this.isFunction()||this.isLoop())return this.skip();var i=C(e);if(i){if(e.label){if(r.innerLabels.indexOf(e.label.name)>=0)return;i=""+i+"|"+e.label.name}else{if(r.ignoreLabeless)return;if(v.isBreakStatement(e)&&v.isSwitchCase(t))return}r.hasBreakContinue=!0,r.map[i]=e,l=v.literal(i)}return this.isReturnStatement()&&(r.hasReturn=!0,l=v.objectExpression([v.property("init",v.identifier("v"),e.argument||v.identifier("undefined"))])),l?(l=v.returnStatement(l),v.inherits(l,e)):void 0}},j=function(){function e(t,n,r,l,i){m(this,e),this.parent=r,this.scope=l,this.file=i,this.blockPath=n,this.block=n.node,this.outsideLetReferences=y(),this.hasLetReferences=!1,this.letReferences=this.block._letReferences=y(),this.body=[],t&&(this.loopParent=t.parent,this.loopLabel=v.isLabeledStatement(this.loopParent)&&this.loopParent.label,this.loopPath=t,this.loop=t.node)}return e.prototype.run=function(){var e=this.block;if(!e._letDone){e._letDone=!0;var t=this.getLetReferences();if(!v.isFunction(this.parent)&&!v.isProgram(this.block)&&this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.loopLabel&&!v.isLabeledStatement(this.loopParent)?v.labeledStatement(this.loopLabel,this.loop):void 0}},e.prototype.remap=function(){var e=!1,t=this.letReferences,n=this.scope,r=y();for(var l in t){var i=t[l];if(n.parentHasBinding(l)||n.hasGlobal(l)){var s=n.generateUidIdentifier(i.name).name;i.name=s,e=!0,r[l]=r[s]={binding:i,uid:s}}}if(e){var a=this.loop;a&&(d(a.right,a,n,r),d(a.test,a,n,r),d(a.update,a,n,r)),this.blockPath.traverse(_,r)}},e.prototype.wrapClosure=function(){var e=this.block,t=this.outsideLetReferences;if(this.loop)for(var n in t){var r=t[n];(this.scope.hasGlobal(r.name)||this.scope.parentHasBinding(r.name))&&(delete t[r.name],delete this.letReferences[r.name],this.scope.rename(r.name),this.letReferences[r.name]=r,t[r.name]=r)}this.has=this.checkLoop(),this.hoistVarDeclarations();var l=x(t),i=x(t),s=v.functionExpression(null,l,v.blockStatement(e.body));s.shadow=!0,this.addContinuations(s),e.body=this.body;var a=s;this.loop&&(a=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(v.variableDeclaration("var",[v.variableDeclarator(a,s)])));var o=v.callExpression(a,i),u=this.scope.generateUidIdentifier("ret"),p=g.hasType(s.body,this.scope,"YieldExpression",v.FUNCTION_TYPES);p&&(s.generator=!0,o=v.yieldExpression(o,!0));
var c=g.hasType(s.body,this.scope,"AwaitExpression",v.FUNCTION_TYPES);c&&(s.async=!0,o=v.awaitExpression(o)),this.buildClosure(u,o)},e.prototype.buildClosure=function(e,t){var n=this.has;n.hasReturn||n.hasBreakContinue?this.buildHas(e,t):this.body.push(v.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,A,t);for(var n=0;n<e.params.length;n++){var r=e.params[n];if(t.reassignments[r.name]){var l=this.scope.generateUidIdentifier(r.name);e.params[n]=l,this.scope.rename(r.name,l.name,e),e.body.body.push(v.expressionStatement(v.assignmentExpression("=",r,l)))}}},e.prototype.getLetReferences=function(){for(var e,t=this.block,n=t._letDeclarators||[],l=0;l<n.length;l++)e=n[l],E(this.outsideLetReferences,v.getBindingIdentifiers(e));if(t.body)for(l=0;l<t.body.length;l++)e=t.body[l],r(e,t)&&(n=n.concat(e.declarations));for(l=0;l<n.length;l++){e=n[l];var i=v.getBindingIdentifiers(e);E(this.letReferences,i),this.hasLetReferences=!0}if(this.hasLetReferences){s(n);var a={letReferences:this.letReferences,closurify:!1};return this.blockPath.traverse(S,a),a.closurify}},e.prototype.checkLoop=function(){var e={hasBreakContinue:!1,ignoreLabeless:!1,innerLabels:[],hasReturn:!1,isLoop:!!this.loop,map:{}};return this.blockPath.traverse(k,e),this.blockPath.traverse(T,e),e},e.prototype.hoistVarDeclarations=function(){this.blockPath.traverse(w,this)},e.prototype.pushDeclar=function(e){this.body.push(v.variableDeclaration(e.kind,e.declarations.map(function(e){return v.variableDeclarator(e.id)})));for(var t=[],n=0;n<e.declarations.length;n++){var r=e.declarations[n];if(r.init){var l=v.assignmentExpression("=",r.id,r.init);t.push(v.inherits(l,r))}}return t},e.prototype.buildHas=function(e,t){var n=this.body;n.push(v.variableDeclaration("var",[v.variableDeclarator(e,t)]));var r,l=(this.loop,this.has),i=[];if(l.hasReturn&&(r=b.template("let-scoping-return",{RETURN:e})),l.hasBreakContinue){for(var s in l.map)i.push(v.switchCase(v.literal(s),[l.map[s]]));if(l.hasReturn&&i.push(v.switchCase(null,[r])),1===i.length){var a=i[0];n.push(this.file.attachAuxiliaryComment(v.ifStatement(v.binaryExpression("===",e,a.test),a.consequent[0])))}else{for(var o=0;o<i.length;o++){var u=i[o].consequent[0];if(v.isBreakStatement(u)&&!u.label){var p;u.label=(p=this,!p.loopLabel&&(p.loopLabel=this.file.scope.generateUidIdentifier("loop")),p.loopLabel)}}n.push(this.file.attachAuxiliaryComment(v.switchStatement(e,i)))}}else l.hasReturn&&n.push(this.file.attachAuxiliaryComment(r))},e}()},{"../../../helpers/object":41,"../../../traversal":144,"../../../types":153,"../../../util":157,"lodash/object/extend":406,"lodash/object/values":411}],84:[function(e,t,n){"use strict";function r(e){return m.variableDeclaration("let",[m.variableDeclarator(e.id,m.toExpression(e))])}function l(e,t,n,r){return new x(this,r).run()}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.ClassDeclaration=r,n.ClassExpression=l,n.__esModule=!0;var o=s(e("../../helpers/replace-supers")),u=i(e("../../helpers/name-method")),p=i(e("../../helpers/define-map")),c=i(e("../../../messages")),d=i(e("../../../util")),f=s(e("../../../traversal")),h=(s(e("lodash/collection/each")),s(e("lodash/object/has"))),m=i(e("../../../types")),g="__initializeProperties",y=m.isClass;n.check=y;var b={Identifier:{enter:function(e,t,n,r){this.parentPath.isClassProperty({key:e})||this.isReferenced()&&n.getBinding(e.name)===r.scope.getBinding(e.name)&&(r.references[e.name]=!0)}}},v=f.explode({MethodDefinition:{enter:function(){this.skip()}},Property:{enter:function(e){e.method&&this.skip()}},CallExpression:{enter:function(e,t,n,r){if(this.get("callee").isSuper()&&(r.hasBareSuper=!0,r.bareSuper=this,!r.hasSuper))throw this.errorWithNode("super call is only allowed in derived constructor")}},FunctionDeclaration:{enter:function(){this.skip()}},FunctionExpression:{enter:function(){this.skip()}},ThisExpression:{enter:function(e,t,n,r){if(r.hasSuper&&!r.hasBareSuper)throw this.errorWithNode("'this' is not allowed before super()")}}}),x=function(){function e(t,n){a(this,e),this.parent=t.parent,this.scope=t.scope,this.node=t.node,this.path=t,this.file=n,this.hasInstanceDescriptors=!1,this.hasStaticDescriptors=!1,this.instanceMutatorMap={},this.staticMutatorMap={},this.instancePropBody=[],this.instancePropRefs={},this.staticPropBody=[],this.body=[],this.hasConstructor=!1,this.hasDecorators=!1,this.className=this.node.id,this.classRef=this.node.id||this.scope.generateUidIdentifier("class"),this.superName=this.node.superClass||m.identifier("Function"),this.hasSuper=!!this.node.superClass,this.isLoose=n.isLoose("es6.classes")}return e.prototype.run=function(){var e,t=this.superName,n=(this.className,this.node.body.body,this.classRef),r=this.file,l=this.body,i=this.constructorBody=m.blockStatement([]);this.className?(e=m.functionDeclaration(this.className,[],i),l.push(e)):e=m.functionExpression(null,[],i),this.constructor=e;var s=[],a=[];this.hasSuper&&(a.push(t),t=this.scope.generateUidBasedOnNode(t),s.push(t),this.superName=t,l.push(m.expressionStatement(m.callExpression(r.addHelper("inherits"),[n,t])))),this.buildBody();var o=this.node.decorators,p=n;if(o&&(p=this.scope.generateUidIdentifier(n)),i.body.unshift(m.expressionStatement(m.callExpression(r.addHelper("class-call-check"),[m.thisExpression(),p]))),o){this.className&&l.push(m.variableDeclaration("var",[m.variableDeclarator(p,n)]));for(var c=0;c<o.length;c++){var f=o[c],h=d.template("class-decorator",{DECORATOR:f.expression,CLASS_REF:n},!0);h.expression._ignoreModulesRemap=!0,l.push(h)}}if(this.className){if(1===l.length)return m.toExpression(l[0])}else e=u.bare(e,this.parent,this.scope),l.unshift(m.variableDeclaration("var",[m.variableDeclarator(n,e)])),m.inheritsComments(l[0],this.node);return l=l.concat(this.staticPropBody),l.push(m.returnStatement(n)),m.callExpression(m.functionExpression(null,s,m.blockStatement(l)),a)},e.prototype.pushToMap=function(e,t){var n,r=void 0===arguments[2]?"value":arguments[2];e["static"]?(this.hasStaticDescriptors=!0,n=this.staticMutatorMap):(this.hasInstanceDescriptors=!0,n=this.instanceMutatorMap);var l=m.toKeyAlias(e),i={};h(n,l)&&(i=n[l]),n[l]=i;var s=i;if(s._inherits||(s._inherits=[]),i._inherits.push(e),i._key=e.key,t&&(i.enumerable=m.literal(!0)),e.computed&&(i._computed=!0),e.decorators){var a;this.hasDecorators=!0;var o=(a=i,!a.decorators&&(a.decorators=m.arrayExpression([])),a.decorators);o.elements=o.elements.concat(e.decorators.map(function(e){return e.expression}))}if(i.value||i.initializer)throw this.file.errorWithNode(e,"Key conflict with sibling node");"get"===e.kind&&(r="get"),"set"===e.kind&&(r="set"),m.inheritsComments(e.value,e),i[r]=e.value},e.prototype.buildBody=function(){for(var e=this.constructorBody,t=(this.constructor,this.className),n=(this.superName,this.node.body.body),r=this.body,l=this.path.get("body").get("body"),i=0;i<n.length;i++){var s=n[i],a=l[i];if(m.isMethodDefinition(s)){var u="constructor"===s.kind;u&&this.verifyConstructor(a);var c=new o({methodPath:a,methodNode:s,objectRef:this.classRef,superRef:this.superName,isStatic:s["static"],isLoose:this.isLoose,scope:this.scope,file:this.file},!0);c.replace(),u?this.pushConstructor(s,a):this.pushMethod(s)}else m.isClassProperty(s)&&this.pushProperty(s)}if(!this.hasConstructor&&this.hasSuper){var f="class-super-constructor-call";this.isLoose&&(f+="-loose"),e.body.push(d.template(f,{CLASS_NAME:t,SUPER_NAME:this.superName},!0))}this.placePropertyInitializers(),this.userConstructor&&(e.body=e.body.concat(this.userConstructor.body.body),m.inherits(this.constructor,this.userConstructor),m.inherits(this.constructorBody,this.userConstructor.body));var h,g,y="create-class";if(this.hasDecorators&&(y="create-decorated-class"),this.hasInstanceDescriptors&&(h=p.toClassObject(this.instanceMutatorMap)),this.hasStaticDescriptors&&(g=p.toClassObject(this.staticMutatorMap)),h||g){h&&(h=p.toComputedObjectFromClass(h)),g&&(g=p.toComputedObjectFromClass(g));var b=m.literal(null),v=[this.classRef,b,b,b,b];h&&(v[1]=h),g&&(v[2]=g),this.instanceInitializersId&&(v[3]=this.instanceInitializersId,r.unshift(this.buildObjectAssignment(this.instanceInitializersId))),this.staticInitializersId&&(v[4]=this.staticInitializersId,r.unshift(this.buildObjectAssignment(this.staticInitializersId)));for(var x=0,i=0;i<v.length;i++)v[i]!==b&&(x=i);v=v.slice(0,x+1),r.push(m.expressionStatement(m.callExpression(this.file.addHelper(y),v)))}},e.prototype.buildObjectAssignment=function(e){return m.variableDeclaration("var",[m.variableDeclarator(e,m.objectExpression([]))])},e.prototype.placePropertyInitializers=function(){var e=this.instancePropBody;if(e.length)if(this.hasPropertyCollision()){var t=m.expressionStatement(m.callExpression(m.memberExpression(m.thisExpression(),m.identifier(g)),[]));this.pushMethod(m.methodDefinition(m.identifier(g),m.functionExpression(null,[],m.blockStatement(e))),!0),this.hasSuper?this.bareSuper.insertAfter(t):this.constructorBody.body.unshift(t)}else this.hasSuper?this.hasConstructor?this.bareSuper.insertAfter(e):this.constructorBody.body=this.constructorBody.body.concat(e):this.constructorBody.body=e.concat(this.constructorBody.body)},e.prototype.hasPropertyCollision=function(){if(this.userConstructorPath)for(var e in this.instancePropRefs)if(this.userConstructorPath.scope.hasOwnBinding(e))return!0;return!1},e.prototype.verifyConstructor=function(e){var t={hasBareSuper:!1,bareSuper:null,hasSuper:this.hasSuper,file:this.file};if(e.get("value").traverse(v,t),this.bareSuper=t.bareSuper,!t.hasBareSuper&&this.hasSuper)throw e.errorWithNode("Derived constructor must call super()")},e.prototype.pushMethod=function(e,t){if(!t&&m.isLiteral(m.toComputedKey(e),{value:g}))throw this.file.errorWithNode(e,c.get("illegalMethodName",g));if("method"===e.kind&&(u.property(e,this.file,this.scope),this.isLoose)){var n=this.classRef;e["static"]||(n=m.memberExpression(n,m.identifier("prototype")));var r=m.memberExpression(n,e.key,e.computed),l=m.expressionStatement(m.assignmentExpression("=",r,e.value));return m.inheritsComments(l,e),void this.body.push(l)}this.pushToMap(e)},e.prototype.pushProperty=function(e){if(e.value||e.decorators){if(this.scope.traverse(e,b,{references:this.instancePropRefs,scope:this.scope}),e.decorators){var t=[];if(e.value&&t.push(m.returnStatement(e.value)),e.value=m.functionExpression(null,[],m.blockStatement(t)),this.pushToMap(e,!0,"initializer"),e["static"]){var n;this.staticPropBody.push(d.template("call-static-decorator",{INITIALIZERS:(n=this,!n.staticInitializersId&&(n.staticInitializersId=this.scope.generateUidIdentifier("staticInitializers")),n.staticInitializersId),CONSTRUCTOR:this.classRef,KEY:e.key},!0))}else{var r;this.instancePropBody.push(d.template("call-instance-decorator",{INITIALIZERS:(r=this,!r.instanceInitializersId&&(r.instanceInitializersId=this.scope.generateUidIdentifier("instanceInitializers")),r.instanceInitializersId),KEY:e.key},!0))}}else e["static"]?this.pushToMap(e,!0):this.instancePropBody.push(m.expressionStatement(m.assignmentExpression("=",m.memberExpression(m.thisExpression(),e.key),e.value)))}},e.prototype.pushConstructor=function(e,t){var n=t.get("value");n.scope.hasOwnBinding(this.classRef.name)&&n.scope.rename(this.classRef.name);var r=this.constructor,l=e.value;this.userConstructorPath=n,this.userConstructor=l,this.hasConstructor=!0,m.inheritsComments(r,e),r._ignoreUserWhitespace=!0,r.params=l.params,m.inherits(r.body,l.body)},e}()},{"../../../messages":43,"../../../traversal":144,"../../../types":153,"../../../util":157,"../../helpers/define-map":54,"../../helpers/name-method":57,"../../helpers/replace-supers":61,"lodash/collection/each":316,"lodash/object/has":407}],85:[function(e,t,n){"use strict";function r(e){return o.isVariableDeclaration(e,{kind:"const"})||o.isImportDeclaration(e)}function l(e,t,n,r){this.traverse(u,{constants:n.getAllBindingsOfKind("const","module"),file:r})}function i(e){"const"===e.kind&&(e.kind="let")}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.Scopable=l,n.VariableDeclaration=i,n.__esModule=!0;var a=s(e("../../../messages")),o=s(e("../../../types")),u={enter:function(e,t,n,r){if(this.isAssignmentExpression()||this.isUpdateExpression()){var l=this.getBindingIdentifiers();for(var i in l){var s=l[i],o=r.constants[i];if(o){var u=o.identifier;if(s!==u&&n.bindingIdentifierEquals(i,u))throw r.file.errorWithNode(s,a.get("readOnly",i))}}}else this.isScope()&&this.skip()}}},{"../../../messages":43,"../../../types":153}],86:[function(e,t,n){"use strict";function r(e,t,n,r){var l=e.left;if(f.isPattern(l)){var i=n.generateUidIdentifier("ref");return e.left=f.variableDeclaration("var",[f.variableDeclarator(i)]),f.ensureBlock(e),void e.body.body.unshift(f.variableDeclaration("var",[f.variableDeclarator(l,i)]))}if(f.isVariableDeclaration(l)){var s=l.declarations[0].id;if(f.isPattern(s)){var a=n.generateUidIdentifier("ref");e.left=f.variableDeclaration(l.kind,[f.variableDeclarator(a,null)]);var o=[],u=new g({kind:l.kind,file:r,scope:n,nodes:o});u.init(s,a),f.ensureBlock(e);var p=e.body;p.body=o.concat(p.body)}}}function l(e,t,n,r){var l=e.param;if(f.isPattern(l)){var i=n.generateUidIdentifier("ref");e.param=i;var s=[],a=new g({kind:"let",file:r,scope:n,nodes:s});return a.init(l,i),e.body.body=s.concat(e.body.body),e}}function i(e,t,n,r){var l=e.expression;if("AssignmentExpression"===l.type&&f.isPattern(l.left)&&!r.isConsequenceExpressionStatement(e)){var i=new g({operator:l.operator,scope:n,file:r});return i.init(l.left,l.right)}}function s(e,t,n,r){if(f.isPattern(e.left)){var l=n.generateUidIdentifier("temp");n.push({id:l});var i=[];i.push(f.expressionStatement(f.assignmentExpression("=",l,e.right)));var s=new g({operator:e.operator,file:r,scope:n,nodes:i});return s.init(e.left,l),i.push(f.expressionStatement(l)),i}}function a(e){for(var t=0;t<e.declarations.length;t++)if(f.isPattern(e.declarations[t].id))return!0;return!1}function o(e,t,n,r){if(!f.isForInStatement(t)&&!f.isForOfStatement(t)&&a(e)){for(var l,i=[],s=0;s<e.declarations.length;s++){l=e.declarations[s];var o=l.init,u=l.id,p=new g({nodes:i,scope:n,kind:e.kind,file:r});f.isPattern(u)&&o?(p.init(u,o),+s!==e.declarations.length-1&&f.inherits(i[i.length-1],l)):i.push(f.inherits(p.buildVariableAssignment(l.id,l.init),l))}if(!f.isProgram(t)&&!f.isBlockStatement(t)){for(l=null,s=0;s<i.length;s++){if(e=i[s],l||(l=f.variableDeclaration(e.kind,[])),!f.isVariableDeclaration(e)&&l.kind!==e.kind)throw r.errorWithNode(e,d.get("invalidParentForThisNode"));l.declarations=l.declarations.concat(e.declarations)}return l}return i}}function u(e){for(var t=0;t<e.elements.length;t++)if(f.isRestElement(e.elements[t]))return!0;return!1}var p=function(e){return e&&e.__esModule?e:{"default":e}},c=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};n.ForOfStatement=r,n.CatchClause=l,n.ExpressionStatement=i,n.AssignmentExpression=s,n.VariableDeclaration=o,n.__esModule=!0;var d=p(e("../../../messages")),f=p(e("../../../types")),h=f.isPattern;n.check=h,n.ForInStatement=r,n.Function=function(e,t,n,r){var l=[],i=!1;if(e.params=e.params.map(function(t,s){if(!f.isPattern(t))return t;i=!0;var a=n.generateUidIdentifier("ref"),o=new g({blockHoist:e.params.length-s,nodes:l,scope:n,file:r,kind:"let"});return o.init(t,a),a}),i){r.checkNode(l),f.ensureBlock(e);var s=e.body;s.body=l.concat(s.body)}};var m={enter:function(e,t,n,r){this.isReferencedIdentifier()&&r.bindings[e.name]&&(r.deopt=!0,this.stop())}},g=function(){function e(t){c(this,e),this.blockHoist=t.blockHoist,this.operator=t.operator,this.arrays={},this.nodes=t.nodes||[],this.scope=t.scope,this.file=t.file,this.kind=t.kind}return e.prototype.buildVariableAssignment=function(e,t){var n=this.operator;f.isMemberExpression(e)&&(n="=");var r;return r=n?f.expressionStatement(f.assignmentExpression(n,e,t)):f.variableDeclaration(this.kind,[f.variableDeclarator(e,t)]),r._blockHoist=this.blockHoist,r},e.prototype.buildVariableDeclaration=function(e,t){var n=f.variableDeclaration("var",[f.variableDeclarator(e,t)]);return n._blockHoist=this.blockHoist,n},e.prototype.push=function(e,t){f.isObjectPattern(e)?this.pushObjectPattern(e,t):f.isArrayPattern(e)?this.pushArrayPattern(e,t):f.isAssignmentPattern(e)?this.pushAssignmentPattern(e,t):this.nodes.push(this.buildVariableAssignment(e,t))},e.prototype.toArray=function(e,t){return this.file.isLoose("es6.destructuring")||f.isIdentifier(e)&&this.arrays[e.name]?e:this.scope.toArray(e,t)},e.prototype.pushAssignmentPattern=function(e,t){var n=this.scope.generateUidBasedOnNode(t),r=f.variableDeclaration("var",[f.variableDeclarator(n,t)]);r._blockHoist=this.blockHoist,this.nodes.push(r);var l=f.conditionalExpression(f.binaryExpression("===",n,f.identifier("undefined")),e.right,n),i=e.left;f.isPattern(i)?(this.nodes.push(f.expressionStatement(f.assignmentExpression("=",n,l))),this.push(i,n)):this.nodes.push(this.buildVariableAssignment(i,l))},e.prototype.pushObjectSpread=function(e,t,n,r){for(var l=[],i=0;i<e.properties.length;i++){var s=e.properties[i];if(i>=r)break;if(!f.isSpreadProperty(s)){var a=s.key;f.isIdentifier(a)&&!s.computed&&(a=f.literal(s.key.name)),l.push(a)}}l=f.arrayExpression(l);var o=f.callExpression(this.file.addHelper("object-without-properties"),[t,l]);this.nodes.push(this.buildVariableAssignment(n.argument,o))},e.prototype.pushObjectProperty=function(e,t){f.isLiteral(e.key)&&(e.computed=!0);var n=e.value,r=f.memberExpression(t,e.key,e.computed);f.isPattern(n)?this.push(n,r):this.nodes.push(this.buildVariableAssignment(n,r))},e.prototype.pushObjectPattern=function(e,t){if(e.properties.length||this.nodes.push(f.expressionStatement(f.callExpression(this.file.addHelper("object-destructuring-empty"),[t]))),e.properties.length>1&&f.isMemberExpression(t)){var n=this.scope.generateUidBasedOnNode(t,this.file);this.nodes.push(this.buildVariableDeclaration(n,t)),t=n}for(var r=0;r<e.properties.length;r++){var l=e.properties[r];f.isSpreadProperty(l)?this.pushObjectSpread(e,t,l,r):this.pushObjectProperty(l,t)}},e.prototype.canUnpackArrayPattern=function(e,t){if(!f.isArrayExpression(t))return!1;if(!(e.elements.length>t.elements.length)){if(e.elements.length<t.elements.length&&!u(e))return!1;for(var n=0;n<e.elements.length;n++)if(!e.elements[n])return!1;var r=f.getBindingIdentifiers(e),l={deopt:!1,bindings:r};return this.scope.traverse(t,m,l),!l.deopt}},e.prototype.pushUnpackedArrayPattern=function(e,t){for(var n=0;n<e.elements.length;n++){var r=e.elements[n];f.isRestElement(r)?this.push(r.argument,f.arrayExpression(t.elements.slice(n))):this.push(r,t.elements[n])}},e.prototype.pushArrayPattern=function(e,t){if(e.elements){if(this.canUnpackArrayPattern(e,t))return this.pushUnpackedArrayPattern(e,t);var n=!u(e)&&e.elements.length,r=this.toArray(t,n);f.isIdentifier(r)?t=r:(t=this.scope.generateUidBasedOnNode(t),this.arrays[t.name]=!0,this.nodes.push(this.buildVariableDeclaration(t,r)));for(var l=0;l<e.elements.length;l++){var i=e.elements[l];if(i){var s;f.isRestElement(i)?(s=this.toArray(t),l>0&&(s=f.callExpression(f.memberExpression(s,f.identifier("slice")),[f.literal(l)])),i=i.argument):s=f.memberExpression(t,f.literal(l),!0),this.push(i,s)}}}},e.prototype.init=function(e,t){if(!f.isArrayExpression(t)&&!f.isMemberExpression(t)){var n=this.scope.generateMemoisedReference(t,!0);n&&(this.nodes.push(this.buildVariableDeclaration(n,t)),t=n)}return this.push(e,t),this.nodes},e}()},{"../../../messages":43,"../../../types":153}],87:[function(e,t,n){"use strict";function r(e,t,n,r){if(this.get("right").isArrayExpression())return l.call(this,e,n,r);var i=c;r.isLoose("es6.forOf")&&(i=p);var s=i(e,t,n,r),a=s.declar,u=s.loop,d=u.body;o.inheritsComments(u,e),o.ensureBlock(e),a&&d.body.push(a),d.body=d.body.concat(e.body.body),o.inherits(u,e),s.replaceParent?(this.parentPath.replaceWithMultiple(s.node),this.remove()):this.replaceWithMultiple(s.node)}function l(e,t){var n=[],r=e.right;if(!o.isIdentifier(r)||!t.hasBinding(r.name)){var l=t.generateUidIdentifier("arr");n.push(o.variableDeclaration("var",[o.variableDeclarator(l,r)])),r=l}var i=t.generateUidIdentifier("i"),s=a.template("for-of-array",{BODY:e.body,KEY:i,ARR:r});o.inherits(s,e),o.ensureBlock(s);var u=o.memberExpression(r,i,!0),p=e.left;return o.isVariableDeclaration(p)?(p.declarations[0].init=u,s.body.body.unshift(p)):s.body.body.unshift(o.expressionStatement(o.assignmentExpression("=",p,u))),n.push(s),n}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.ForOfStatement=r,n._ForOfStatementArray=l,n.__esModule=!0;var s=i(e("../../../messages")),a=i(e("../../../util")),o=i(e("../../../types")),u=o.isForOfStatement;n.check=u;var p=function(e,t,n,r){var l,i,u=e.left;if(o.isIdentifier(u)||o.isPattern(u)||o.isMemberExpression(u))i=u;else{if(!o.isVariableDeclaration(u))throw r.errorWithNode(u,s.get("unknownForHead",u.type));i=n.generateUidIdentifier("ref"),l=o.variableDeclaration(u.kind,[o.variableDeclarator(u.declarations[0].id,i)])}var p=n.generateUidIdentifier("iterator"),c=n.generateUidIdentifier("isArray"),d=a.template("for-of-loose",{LOOP_OBJECT:p,IS_ARRAY:c,OBJECT:e.right,INDEX:n.generateUidIdentifier("i"),ID:i});return l||d.body.body.shift(),{declar:l,node:d,loop:d}},c=function(e,t,n,r){var l,i=e.left,u=n.generateUidIdentifier("step"),p=o.memberExpression(u,o.identifier("value"));if(o.isIdentifier(i)||o.isPattern(i)||o.isMemberExpression(i))l=o.expressionStatement(o.assignmentExpression("=",i,p));else{if(!o.isVariableDeclaration(i))throw r.errorWithNode(i,s.get("unknownForHead",i.type));l=o.variableDeclaration(i.kind,[o.variableDeclarator(i.declarations[0].id,p)])}var c=n.generateUidIdentifier("iterator"),d=a.template("for-of",{ITERATOR_HAD_ERROR_KEY:n.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:n.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:n.generateUidIdentifier("iteratorError"),ITERATOR_KEY:c,STEP_KEY:u,OBJECT:e.right,BODY:null}),f=o.isLabeledStatement(t),h=d[3].block.body,m=h[0];return f&&(h[0]=o.labeledStatement(t.label,m)),{replaceParent:f,declar:l,loop:m,node:d}}},{"../../../messages":43,"../../../types":153,"../../../util":157}],88:[function(e,t,n){"use strict";function r(e,t){if(e._blockHoist)for(var n=0;n<t.length;n++)t[n]._blockHoist=e._blockHoist}function l(e,t,n,r){if(!e.isType){var l=[];if(e.specifiers.length)for(var i=0;i<e.specifiers.length;i++)r.moduleFormatter.importSpecifier(e.specifiers[i],e,l,t);else r.moduleFormatter.importDeclaration(e,l,t);return 1===l.length&&(l[0]._blockHoist=e._blockHoist),l}}function i(e,t,n,l){var i=[];return l.moduleFormatter.exportAllDeclaration(e,i,t),r(e,i),i}function s(e,t,n,l){var i=[];return l.moduleFormatter.exportDeclaration(e,i,t),r(e,i),i}function a(e,t,n,l){if(!this.get("declaration").isTypeAlias()){var i=[];if(e.declaration){if(u.isVariableDeclaration(e.declaration)){var s=e.declaration.declarations[0];s.init=s.init||u.identifier("undefined")}l.moduleFormatter.exportDeclaration(e,i,t)}else if(e.specifiers)for(var a=0;a<e.specifiers.length;a++)l.moduleFormatter.exportSpecifier(e.specifiers[a],e,i,t);return r(e,i),i}}var o=function(e){return e&&e.__esModule?e:{"default":e}};n.ImportDeclaration=l,n.ExportAllDeclaration=i,n.ExportDefaultDeclaration=s,n.ExportNamedDeclaration=a,n.__esModule=!0;var u=o(e("../../../types"));n.check=e("../internal/modules").check},{"../../../types":153,"../internal/modules":115}],89:[function(e,t,n){"use strict";function r(e,t,n,r,l){if(t.method){var i=t.value,s=n.generateUidIdentifier("this"),u=new a({topLevelThisReference:s,getObjectRef:r,methodNode:t,methodPath:e,isStatic:!0,scope:n,file:l});u.replace(),u.hasSuper&&i.body.body.unshift(o.variableDeclaration("var",[o.variableDeclarator(s,o.thisExpression())]))}}function l(e,t,n,l){for(var i,s=function(){return!i&&(i=n.generateUidIdentifier("obj")),i},a=this.get("properties"),u=0;u<e.properties.length;u++)r(a[u],e.properties[u],n,s,l);return i?(n.push({id:i}),o.assignmentExpression("=",i,e)):void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.ObjectExpression=l,n.__esModule=!0;var a=s(e("../../helpers/replace-supers")),o=i(e("../../../types")),u=o.isSuper;n.check=u},{"../../../types":153,"../../helpers/replace-supers":61}],90:[function(e,t,n){"use strict";function r(e){return o.isFunction(e)&&u(e)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e};n.check=r,n.__esModule=!0;var s=i(e("../../helpers/call-delegate")),a=l(e("../../../util")),o=l(e("../../../types")),u=function(e){for(var t=0;t<e.params.length;t++)if(!o.isIdentifier(e.params[t]))return!0;return!1},p={enter:function(e,t,n,r){this.isReferencedIdentifier()&&r.scope.hasOwnBinding(e.name)&&(r.scope.bindingIdentifierEquals(e.name,e)||(r.iife=!0,this.stop()))}};n.Function=function(e,t,n,r){if(u(e)){o.ensureBlock(e);var l=[],i=o.identifier("arguments");i._shadowedFunctionLiteral=!0;for(var c=0,d={iife:!1,scope:n},f=function(t,n,s){var u=a.template("default-parameter",{VARIABLE_NAME:t,DEFAULT_VALUE:n,ARGUMENT_KEY:o.literal(s),ARGUMENTS:i},!0);r.checkNode(u),u._blockHoist=e.params.length-s,l.push(u)},h=this.get("params"),m=0;m<h.length;m++){var g=h[m];if(g.isAssignmentPattern()){var y=g.get("left"),b=g.get("right"),v=n.generateUidIdentifier("x");v._isDefaultPlaceholder=!0,e.params[m]=v,d.iife||(b.isIdentifier()&&n.hasOwnBinding(b.node.name)?d.iife=!0:b.traverse(p,d)),f(y.node,b.node,m)}else g.isRestElement()||(c=m+1),g.isIdentifier()||g.traverse(p,d),r.transformers["es6.spec.blockScoping"].canTransform()&&g.isIdentifier()&&f(g.node,o.identifier("undefined"),m)}e.params=e.params.slice(0,c),d.iife?(l.push(s(e)),e.body=o.blockStatement(l)):e.body.body=l.concat(e.body.body)}}},{"../../../types":153,"../../../util":157,"../../helpers/call-delegate":53}],91:[function(e,t,n){"use strict";function r(e,t){var n,r=e.property;o.isLiteral(r)?(r.value+=t,r.raw=String(r.value)):(n=o.binaryExpression("+",r,o.literal(t)),e.property=n)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e};n.__esModule=!0;var s=i(e("lodash/lang/isNumber")),a=l(e("../../../util")),o=l(e("../../../types")),u=o.isRestElement;n.check=u;var p={enter:function(e,t,n,r){if(this.isScope()&&!n.bindingIdentifierEquals(r.name,r.outerBinding))return this.skip();if(this.isFunctionDeclaration()||this.isFunctionExpression())return r.noOptimise=!0,this.traverse(p,r),r.noOptimise=!1,this.skip();if(this.isReferencedIdentifier({name:r.name})){if(!r.noOptimise&&o.isMemberExpression(t)&&t.computed){var l=t.property;if(s(l.value)||o.isUnaryExpression(l)||o.isBinaryExpression(l))return void r.candidates.push(this)}r.canOptimise=!1,this.stop()}}},c=function(e){return o.isRestElement(e.params[e.params.length-1])};n.Function=function(e,t,n,l){if(c(e)){var i=e.params.pop().argument,s=o.identifier("arguments");if(s._shadowedFunctionLiteral=!0,o.isPattern(i)){var u=i;i=n.generateUidIdentifier("ref");var d=o.variableDeclaration("let",u.elements.map(function(e,t){var n=o.memberExpression(i,o.literal(t),!0);return o.variableDeclarator(e,n)}));l.checkNode(d),e.body.body.unshift(d)}var f={outerBinding:n.getBindingIdentifier(i.name),canOptimise:!0,candidates:[],method:e,name:i.name};if(this.traverse(p,f),f.canOptimise&&f.candidates.length)for(var h=0;h<f.candidates.length;h++){var m=f.candidates[h];m.replaceWith(s),r(m.parent,e.params.length)}else{var g=o.literal(e.params.length),y=n.generateUidIdentifier("key"),b=n.generateUidIdentifier("len"),v=y,x=b;e.params.length&&(v=o.binaryExpression("-",y,g),x=o.conditionalExpression(o.binaryExpression(">",b,g),o.binaryExpression("-",b,g),o.literal(0)));var E=a.template("rest",{ARGUMENTS:s,ARRAY_KEY:v,ARRAY_LEN:x,START:g,ARRAY:i,KEY:y,LEN:b});E._blockHoist=e.params.length+1,e.body.body.unshift(E)}}}},{"../../../types":153,"../../../util":157,"lodash/lang/isNumber":397}],92:[function(e,t,n){"use strict";function r(e,t,n){for(var r=0;r<e.properties.length;r++){var l=e.properties[r];t.push(o.expressionStatement(o.assignmentExpression("=",o.memberExpression(n,l.key,l.computed||o.isLiteral(l.key)),l.value)))}}function l(e,t,n,r,l){for(var i,s,a=e.properties,u=0;u<a.length;u++)i=a[u],"init"===i.kind&&(s=i.key,!i.computed&&o.isIdentifier(s)&&(i.key=o.literal(s.name)));var p=!1;for(u=0;u<a.length;u++)i=a[u],i.computed&&(p=!0),("init"!==i.kind||!p||o.isLiteral(o.toComputedKey(i,i.key),{value:"__proto__"}))&&(r.push(i),a[u]=null);for(u=0;u<a.length;u++)if(i=a[u]){s=i.key;var c;c=i.computed&&o.isMemberExpression(s)&&o.isIdentifier(s.object,{name:"Symbol"})?o.assignmentExpression("=",o.memberExpression(n,s,!0),i.value):o.callExpression(l.addHelper("define-property"),[n,s,i.value]),t.push(o.expressionStatement(c))}if(1===t.length){var d=t[0].expression;if(o.isCallExpression(d))return d.arguments[0]=o.objectExpression(r),d}}function i(e){return o.isProperty(e)&&e.computed}function s(e,t,n,i){for(var s=!1,a=0;a<e.properties.length&&!(s=o.isProperty(e.properties[a],{computed:!0,kind:"init"}));a++);if(s){var u=[],p=n.generateUidBasedOnNode(t),c=[],d=l;i.isLoose("es6.properties.computed")&&(d=r);var f=d(e,c,p,u,i);return f?f:(c.unshift(o.variableDeclaration("var",[o.variableDeclarator(p,o.objectExpression(u))])),c.push(o.expressionStatement(p)),c)}}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.check=i,n.ObjectExpression=s,n.__esModule=!0;var o=a(e("../../../types"))},{"../../../types":153}],93:[function(e,t,n){"use strict";function r(e){return s.isProperty(e)&&(e.method||e.shorthand)}function l(e){e.method&&(e.method=!1),e.shorthand&&(e.shorthand=!1,e.key=s.removeComments(s.clone(e.key)))}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.Property=l,n.__esModule=!0;var s=i(e("../../../types"))},{"../../../types":153}],94:[function(e,t,n){"use strict";function r(e){return s.is(e,"y")}function l(e){return s.is(e,"y")?a.newExpression(a.identifier("RegExp"),[a.literal(e.regex.pattern),a.literal(e.regex.flags)]):void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.Literal=l,n.__esModule=!0;var s=i(e("../../helpers/regex")),a=i(e("../../../types"))},{"../../../types":153,"../../helpers/regex":59}],95:[function(e,t,n){"use strict";function r(e){return o.is(e,"u")}function l(e){o.is(e,"u")&&(e.regex.pattern=a(e.regex.pattern,e.regex.flags),o.pullFlag(e,"u"))}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.check=r,n.Literal=l,n.__esModule=!0;var a=s(e("regexpu/rewrite-pattern")),o=i(e("../../helpers/regex"))},{"../../helpers/regex":59,"regexpu/rewrite-pattern":436}],96:[function(e,t,n){"use strict";function r(e,t,n,r){var l=e._letReferences;l&&this.traverse(s,{letRefs:l,file:r})}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.BlockStatement=r,n.__esModule=!0;var i=l(e("../../../types")),s={enter:function(e,t,n,r){if(this.isReferencedIdentifier()&&(!i.isFor(t)||t.left!==e)){var l=r.letRefs[e.name];if(l&&n.getBindingIdentifier(e.name)===l){var s=i.callExpression(r.file.addHelper("temporal-assert-defined"),[e,i.literal(e.name),r.file.addHelper("temporal-undefined")]);return this.skip(),i.isAssignmentExpression(t)||i.isUpdateExpression(t)?void(t._ignoreBlockScopingTDZ||this.parentPath.replaceWith(i.sequenceExpression([s,t]))):i.logicalExpression("&&",s,e)}}}},a={optional:!0};n.metadata=a,n.Program=r,n.Loop=r},{"../../../types":153}],97:[function(e,t,n){"use strict";function r(e,t,n,r){if(this.skip(),"typeof"===e.operator){var l=i.callExpression(r.addHelper("typeof"),[e.argument]);if(this.get("argument").isIdentifier()){var s=i.literal("undefined");return i.conditionalExpression(i.binaryExpression("===",i.unaryExpression("typeof",e.argument),s),s,l)
}return l}}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.UnaryExpression=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0};n.metadata=s},{"../../../types":153}],98:[function(e,t,n){"use strict";function r(e,t){if(!i.isTaggedTemplateExpression(t))for(var n=0;n<e.expressions.length;n++)e.expressions[n]=i.callExpression(i.identifier("String"),[e.expressions[n]])}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.TemplateLiteral=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0};n.metadata=s},{"../../../types":153}],99:[function(e,t,n){"use strict";function r(e,t){return t.file.isLoose("es6.spread")?e.argument:t.toArray(e.argument,!0)}function l(e){for(var t=0;t<e.length;t++)if(c.isSpreadElement(e[t]))return!0;return!1}function i(e,t){for(var n=[],l=[],i=function(){l.length&&(n.push(c.arrayExpression(l)),l=[])},s=0;s<e.length;s++){var a=e[s];c.isSpreadElement(a)?(i(),n.push(r(a,t))):l.push(a)}return i(),n}function s(e,t,n){var r=e.elements;if(l(r)){var s=i(r,n),a=s.shift();return c.isArrayExpression(a)||(s.unshift(a),a=c.arrayExpression([])),c.callExpression(c.memberExpression(a,c.identifier("concat")),s)}}function a(e,t,n){var r=e.arguments;if(l(r)){var s=c.identifier("undefined");e.arguments=[];var a;a=1===r.length&&"arguments"===r[0].argument.name?[r[0].argument]:i(r,n);var o=a.shift();e.arguments.push(a.length?c.callExpression(c.memberExpression(o,c.identifier("concat")),a):o);var u=e.callee;if(this.get("callee").isMemberExpression()){var p=n.generateMemoisedReference(u.object);p?(u.object=c.assignmentExpression("=",p,u.object),s=p):s=u.object,c.appendToMemberExpression(u,c.identifier("apply"))}else e.callee=c.memberExpression(e.callee,c.identifier("apply"));e.arguments.unshift(s)}}function o(e,t,n,r){var s=e.arguments;if(l(s)){var a=i(s,n),o=c.arrayExpression([c.literal(null)]);return s=c.callExpression(c.memberExpression(o,c.identifier("concat")),a),c.newExpression(c.callExpression(c.memberExpression(r.addHelper("bind"),c.identifier("apply")),[e.callee,s]),[])}}var u=function(e){return e&&e.__esModule?e:{"default":e}},p=function(e){return e&&e.__esModule?e["default"]:e};n.ArrayExpression=s,n.CallExpression=a,n.NewExpression=o,n.__esModule=!0;var c=(p(e("lodash/collection/includes")),u(e("../../../types"))),d=c.isSpreadElement;n.check=d},{"../../../types":153,"lodash/collection/includes":319}],100:[function(e,t,n){"use strict";function r(e){return d.blockStatement([d.returnStatement(e)])}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=i(e("lodash/collection/reduceRight")),o=l(e("../../../messages")),u=i(e("lodash/array/flatten")),p=l(e("../../../util")),c=i(e("lodash/collection/map")),d=l(e("../../../types"));n.Function=function(e,t,n,r){var l=new g(this,n,r);l.run()};var f={enter:function(e,t,n,r){if(this.isIfStatement())this.get("alternate").isReturnStatement()&&d.ensureBlock(e,"alternate"),this.get("consequent").isReturnStatement()&&d.ensureBlock(e,"consequent");else{if(this.isReturnStatement())return this.skip(),r.subTransform(e.argument);d.isTryStatement(t)?e===t.block?this.skip():t.finalizer&&e!==t.finalizer&&this.skip():this.isFunction()?this.skip():this.isVariableDeclaration()&&(this.skip(),r.vars.push(e))}}},h={enter:function(e,t,n,r){return this.isThisExpression()?(r.needsThis=!0,r.getThisId()):this.isReferencedIdentifier({name:"arguments"})?(r.needsArguments=!0,r.getArgumentsId()):this.isFunction()&&(this.skip(),this.isFunctionDeclaration())?(e=d.variableDeclaration("var",[d.variableDeclarator(e.id,d.toExpression(e))]),e._blockHoist=2,e):void 0}},m={enter:function(e,t,n,r){if(this.isExpressionStatement()){var l=e.expression;if(d.isAssignmentExpression(l))if(r.needsThis||l.left!==r.getThisId()){if(!r.needsArguments&&l.left===r.getArgumentsId()&&d.isArrayExpression(l.right))return c(l.right.elements,function(e){return d.expressionStatement(e)})}else this.remove()}}},g=function(){function e(t,n,r){s(this,e),this.hasTailRecursion=!1,this.needsArguments=!1,this.setsArguments=!1,this.needsThis=!1,this.ownerId=t.node.id,this.vars=[],this.scope=n,this.path=t,this.file=r,this.node=t.node}return e.prototype.getArgumentsId=function(){var e;return e=this,!e.argumentsId&&(e.argumentsId=this.scope.generateUidIdentifier("arguments")),e.argumentsId},e.prototype.getThisId=function(){var e;return e=this,!e.thisId&&(e.thisId=this.scope.generateUidIdentifier("this")),e.thisId},e.prototype.getLeftId=function(){var e;return e=this,!e.leftId&&(e.leftId=this.scope.generateUidIdentifier("left")),e.leftId},e.prototype.getFunctionId=function(){var e;return e=this,!e.functionId&&(e.functionId=this.scope.generateUidIdentifier("function")),e.functionId},e.prototype.getAgainId=function(){var e;return e=this,!e.againId&&(e.againId=this.scope.generateUidIdentifier("again")),e.againId},e.prototype.getParams=function(){var e=this.params;if(!e){e=this.node.params,this.paramDecls=[];for(var t=0;t<e.length;t++){var n=e[t];n._isDefaultPlaceholder||this.paramDecls.push(d.variableDeclarator(n,e[t]=this.scope.generateUidIdentifier("x")))}}return this.params=e},e.prototype.hasDeopt=function(){var e=this.scope.getBinding(this.ownerId.name);return e&&!e.constant},e.prototype.run=function(){var e=(this.scope,this.node),t=this.ownerId;if(t&&(this.path.traverse(f,this),this.hasTailRecursion)){if(this.hasDeopt())return void this.file.log.deopt(e,o.get("tailCallReassignmentDeopt"));this.path.traverse(h,this),this.needsThis&&this.needsArguments||this.path.traverse(m,this);var n=d.ensureBlock(e).body;if(this.vars.length>0){var r=u(c(this.vars,function(e){return e.declarations},this)),l=a(r,function(e,t){return d.assignmentExpression("=",t.id,e)},d.identifier("undefined")),i=d.expressionStatement(l);i._blockHoist=1/0,n.unshift(i)}var s=this.paramDecls;s.length>0&&n.unshift(d.variableDeclaration("var",s)),n.unshift(d.expressionStatement(d.assignmentExpression("=",this.getAgainId(),d.literal(!1)))),e.body=p.template("tail-call-body",{AGAIN_ID:this.getAgainId(),THIS_ID:this.thisId,ARGUMENTS_ID:this.argumentsId,FUNCTION_ID:this.getFunctionId(),BLOCK:e.body});var g=[];if(this.needsThis&&g.push(d.variableDeclarator(this.getThisId(),d.thisExpression())),this.needsArguments||this.setsArguments){var y=d.variableDeclarator(this.getArgumentsId());this.needsArguments&&(y.init=d.identifier("arguments")),g.push(y)}var b=this.leftId;b&&g.push(d.variableDeclarator(b)),g.length>0&&e.body.body.unshift(d.variableDeclaration("var",g))}},e.prototype.subTransform=function(e){if(e){var t=this["subTransform"+e.type];return t?t.call(this,e):void 0}},e.prototype.subTransformConditionalExpression=function(e){var t=this.subTransform(e.consequent),n=this.subTransform(e.alternate);return t||n?(e.type="IfStatement",e.consequent=t?d.toBlock(t):r(e.consequent),e.alternate=n?d.isIfStatement(n)?n:d.toBlock(n):r(e.alternate),[e]):void 0},e.prototype.subTransformLogicalExpression=function(e){var t=this.subTransform(e.right);if(t){var n=this.getLeftId(),l=d.assignmentExpression("=",n,e.left);return"&&"===e.operator&&(l=d.unaryExpression("!",l)),[d.ifStatement(l,r(n))].concat(t)}},e.prototype.subTransformSequenceExpression=function(e){var t=e.expressions,n=this.subTransform(t[t.length-1]);return n?(1===--t.length&&(e=t[0]),[d.expressionStatement(e)].concat(n)):void 0},e.prototype.subTransformCallExpression=function(e){var t,n,r=e.callee;if(d.isMemberExpression(r,{computed:!1})&&d.isIdentifier(r.property)){switch(r.property.name){case"call":n=d.arrayExpression(e.arguments.slice(1));break;case"apply":n=e.arguments[1]||d.identifier("undefined");break;default:return}t=e.arguments[0],r=r.object}if(d.isIdentifier(r)&&this.scope.bindingIdentifierEquals(r.name,this.ownerId)&&(this.hasTailRecursion=!0,!this.hasDeopt())){var l=[];d.isThisExpression(t)||l.push(d.expressionStatement(d.assignmentExpression("=",this.getThisId(),t||d.identifier("undefined")))),n||(n=d.arrayExpression(e.arguments));var i=this.getArgumentsId(),s=this.getParams();l.push(d.expressionStatement(d.assignmentExpression("=",i,n)));var a,o;if(d.isArrayExpression(n)){var u=n.elements;for(a=0;a<u.length&&a<s.length;a++){o=s[a];var p=u[a]||(u[a]=d.identifier("undefined"));o._isDefaultPlaceholder||(u[a]=d.assignmentExpression("=",o,p))}}else for(this.setsArguments=!0,a=0;a<s.length;a++)o=s[a],o._isDefaultPlaceholder||l.push(d.expressionStatement(d.assignmentExpression("=",o,d.memberExpression(i,d.literal(a),!0))));return l.push(d.expressionStatement(d.assignmentExpression("=",this.getAgainId(),d.literal(!0)))),l.push(d.continueStatement(this.getFunctionId())),l}},e}()},{"../../../messages":43,"../../../types":153,"../../../util":157,"lodash/array/flatten":311,"lodash/collection/map":320,"lodash/collection/reduceRight":321}],101:[function(e,t,n){"use strict";function r(e){return a.isTemplateLiteral(e)||a.isTaggedTemplateExpression(e)}function l(e,t,n,r){for(var l=e.quasi,i=[],s=[],o=[],u=0;u<l.quasis.length;u++){var p=l.quasis[u];s.push(a.literal(p.value.cooked)),o.push(a.literal(p.value.raw))}s=a.arrayExpression(s),o=a.arrayExpression(o);var c="tagged-template-literal";return r.isLoose("es6.templateLiterals")&&(c+="-loose"),i.push(a.callExpression(r.addHelper(c),[s,o])),i=i.concat(l.expressions),a.callExpression(e.tag,i)}function i(e){var t,n=[];for(t=0;t<e.quasis.length;t++){var r=e.quasis[t];n.push(a.literal(r.value.cooked));var l=e.expressions.shift();l&&n.push(l)}if(n.length>1){var i=n[n.length-1];a.isLiteral(i,{value:""})&&n.pop();var s=o(n.shift(),n.shift());for(t=0;t<n.length;t++)s=o(s,n[t]);return s}return n[0]}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.TaggedTemplateExpression=l,n.TemplateLiteral=i,n.__esModule=!0;var a=s(e("../../../types")),o=function(e,t){return a.binaryExpression("+",e,t)}},{"../../../types":153}],102:[function(e,t,n){"use strict";function r(){return!1}n.check=r,n.__esModule=!0;var l={stage:1};n.metadata=l},{}],103:[function(e,t,n){"use strict";function r(){return!1}n.check=r,n.__esModule=!0;var l={stage:0};n.metadata=l},{}],104:[function(e,t,n){"use strict";function r(e,t,n,r){var s=i;return e.generator&&(s=l),s(e,t,n,r)}function l(e){var t=[],n=c.functionExpression(null,[],c.blockStatement(t),!0);return n.shadow=!0,t.push(o(e,function(){return c.expressionStatement(c.yieldExpression(e.body))})),c.callExpression(n,[])}function i(e,t,n){var r=n.generateUidBasedOnNode(t),l=p.template("array-comprehension-container",{KEY:r});l.callee.shadow=!0;var i=l.callee.body,s=i.body;u.hasType(e,n,"YieldExpression",c.FUNCTION_TYPES)&&(l.callee.generator=!0,l=c.yieldExpression(l,!0));var a=s.pop();return s.push(o(e,function(){return p.template("array-push",{STATEMENT:e.body,KEY:r},!0)})),s.push(a),l}var s=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e};n.ComprehensionExpression=r,n.__esModule=!0;var o=a(e("../../helpers/build-comprehension")),u=a(e("../../../traversal")),p=s(e("../../../util")),c=s(e("../../../types")),d={stage:0};n.metadata=d},{"../../../traversal":144,"../../../types":153,"../../../util":157,"../../helpers/build-comprehension":51}],105:[function(e,t,n){"use strict";n.__esModule=!0;var r={optional:!0,stage:1};n.metadata=r},{}],106:[function(e,t,n){"use strict";function r(e){var t=e.body.body;return t.length?t:i.identifier("undefined")}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.DoExpression=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0,stage:0};n.metadata=s;var a=i.isDoExpression;n.check=a},{"../../../types":153}],107:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e){return e&&e.__esModule?e["default"]:e};n.__esModule=!0;var i=l(e("../../helpers/build-binary-assignment-operator-transformer")),s=r(e("../../../types")),a={stage:2};n.metadata=a;var o=s.memberExpression(s.identifier("Math"),s.identifier("pow"));i(n,{operator:"**",build:function(e,t){return s.callExpression(o,[e,t])}})},{"../../../types":153,"../../helpers/build-binary-assignment-operator-transformer":50}],108:[function(e,t,n){"use strict";function r(e){return a.isExportDefaultSpecifier(e)||a.isExportNamespaceSpecifier(e)}function l(e,t,n){var r=e.specifiers[0];if(a.isExportNamespaceSpecifier(r)||a.isExportDefaultSpecifier(r)){var i,s=e.specifiers.shift(),o=n.generateUidIdentifier(s.exported.name);i=a.isExportNamespaceSpecifier(s)?a.importNamespaceSpecifier(o):a.importDefaultSpecifier(o),t.push(a.importDeclaration([i],e.source)),t.push(a.exportNamedDeclaration(null,[a.exportSpecifier(o,s.exported)])),l(e,t,n)}}function i(e,t,n){var r=[];return l(e,r,n),r.length?(e.specifiers.length>=1&&r.push(e),r):void 0}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.ExportNamedDeclaration=i,n.__esModule=!0;var a=s(e("../../../types")),o={stage:1};n.metadata=o},{"../../../types":153}],109:[function(e,t,n){"use strict";function r(e){e.whitelist&&e.whitelist.push("es6.destructuring")}function l(e,t,n,r){if(o(e)){for(var l=[],i=[],a=function(){i.length&&(l.push(s.objectExpression(i)),i=[])},u=0;u<e.properties.length;u++){var p=e.properties[u];s.isSpreadProperty(p)?(a(),l.push(p.argument)):i.push(p)}return a(),s.isObjectExpression(l[0])||l.unshift(s.objectExpression([])),s.callExpression(r.addHelper("extends"),l)}}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.manipulateOptions=r,n.ObjectExpression=l,n.__esModule=!0;var s=i(e("../../../types")),a={stage:1};n.metadata=a;var o=function(e){for(var t=0;t<e.properties.length;t++)if(s.isSpreadProperty(e.properties[t]))return!0;return!1}},{"../../../types":153}],110:[function(e,t){"use strict";t.exports={"es7.classProperties":e("./es7/class-properties"),"es7.asyncFunctions":e("./es7/async-functions"),"es7.decorators":e("./es7/decorators"),strict:e("./other/strict"),_validation:e("./internal/validation"),"validation.undeclaredVariableCheck":e("./validation/undeclared-variable-check"),"validation.react":e("./validation/react"),"spec.functionName":e("./spec/function-name"),"es6.arrowFunctions":e("./es6/arrow-functions"),"spec.blockScopedFunctions":e("./spec/block-scoped-functions"),"optimisation.react.constantElements":e("./optimisation/react.constant-elements"),"optimisation.react.inlineElements":e("./optimisation/react.inline-elements"),reactCompat:e("./other/react-compat"),react:e("./other/react"),_modules:e("./internal/modules"),"es7.comprehensions":e("./es7/comprehensions"),"es6.classes":e("./es6/classes"),asyncToGenerator:e("./other/async-to-generator"),bluebirdCoroutines:e("./other/bluebird-coroutines"),"es6.objectSuper":e("./es6/object-super"),"es7.objectRestSpread":e("./es7/object-rest-spread"),"es7.exponentiationOperator":e("./es7/exponentiation-operator"),"es6.spec.templateLiterals":e("./es6/spec.template-literals"),"es6.templateLiterals":e("./es6/template-literals"),"es5.properties.mutators":e("./es5/properties.mutators"),"es6.properties.shorthand":e("./es6/properties.shorthand"),"es6.properties.computed":e("./es6/properties.computed"),"optimisation.flow.forOf":e("./optimisation/flow.for-of"),"es6.forOf":e("./es6/for-of"),"es6.regex.sticky":e("./es6/regex.sticky"),"es6.regex.unicode":e("./es6/regex.unicode"),"es6.constants":e("./es6/constants"),"es6.parameters.rest":e("./es6/parameters.rest"),"es6.spread":e("./es6/spread"),"es6.parameters.default":e("./es6/parameters.default"),"es6.destructuring":e("./es6/destructuring"),"es6.blockScoping":e("./es6/block-scoping"),"es6.spec.blockScoping":e("./es6/spec.block-scoping"),"es6.tailCall":e("./es6/tail-call"),regenerator:e("./other/regenerator"),runtime:e("./other/runtime"),"es7.exportExtensions":e("./es7/export-extensions"),"es6.modules":e("./es6/modules"),_blockHoist:e("./internal/block-hoist"),"spec.protoToAssign":e("./spec/proto-to-assign"),_declarations:e("./internal/declarations"),_shadowFunctions:e("./internal/shadow-functions"),"es7.doExpressions":e("./es7/do-expressions"),"es6.spec.symbols":e("./es6/spec.symbols"),ludicrous:e("./other/ludicrous"),"spec.undefinedToVoid":e("./spec/undefined-to-void"),_strict:e("./internal/strict"),_moduleFormatter:e("./internal/module-formatter"),"es3.propertyLiterals":e("./es3/property-literals"),"es3.memberExpressionLiterals":e("./es3/member-expression-literals"),"utility.removeDebugger":e("./utility/remove-debugger"),"utility.removeConsole":e("./utility/remove-console"),"utility.inlineEnvironmentVariables":e("./utility/inline-environment-variables"),"utility.inlineExpressions":e("./utility/inline-expressions"),"utility.deadCodeElimination":e("./utility/dead-code-elimination"),flow:e("./other/flow"),_cleanUp:e("./internal/cleanup")}},{"./es3/member-expression-literals":79,"./es3/property-literals":80,"./es5/properties.mutators":81,"./es6/arrow-functions":82,"./es6/block-scoping":83,"./es6/classes":84,"./es6/constants":85,"./es6/destructuring":86,"./es6/for-of":87,"./es6/modules":88,"./es6/object-super":89,"./es6/parameters.default":90,"./es6/parameters.rest":91,"./es6/properties.computed":92,"./es6/properties.shorthand":93,"./es6/regex.sticky":94,"./es6/regex.unicode":95,"./es6/spec.block-scoping":96,"./es6/spec.symbols":97,"./es6/spec.template-literals":98,"./es6/spread":99,"./es6/tail-call":100,"./es6/template-literals":101,"./es7/async-functions":102,"./es7/class-properties":103,"./es7/comprehensions":104,"./es7/decorators":105,"./es7/do-expressions":106,"./es7/exponentiation-operator":107,"./es7/export-extensions":108,"./es7/object-rest-spread":109,"./internal/block-hoist":111,"./internal/cleanup":112,"./internal/declarations":113,"./internal/module-formatter":114,"./internal/modules":115,"./internal/shadow-functions":116,"./internal/strict":117,"./internal/validation":118,"./optimisation/flow.for-of":119,"./optimisation/react.constant-elements":120,"./optimisation/react.inline-elements":121,"./other/async-to-generator":122,"./other/bluebird-coroutines":123,"./other/flow":124,"./other/ludicrous":125,"./other/react":127,"./other/react-compat":126,"./other/regenerator":128,"./other/runtime":129,"./other/strict":130,"./spec/block-scoped-functions":131,"./spec/function-name":132,"./spec/proto-to-assign":133,"./spec/undefined-to-void":134,"./utility/dead-code-elimination":135,"./utility/inline-environment-variables":136,"./utility/inline-expressions":137,"./utility/remove-console":138,"./utility/remove-debugger":139,"./validation/react":140,"./validation/undeclared-variable-check":141}],111:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e};n.__esModule=!0;var l=r(e("lodash/collection/groupBy")),i=r(e("lodash/array/flatten")),s=r(e("lodash/object/values")),a={exit:function(e){for(var t=!1,n=0;n<e.body.length;n++){var r=e.body[n];r&&null!=r._blockHoist&&(t=!0)}if(t){var a=l(e.body,function(e){var t=e&&e._blockHoist;return null==t&&(t=1),t===!0&&(t=2),t});e.body=i(s(a).reverse())}}};n.BlockStatement=a,n.Program=a},{"lodash/array/flatten":311,"lodash/collection/groupBy":318,"lodash/object/values":411}],112:[function(e,t,n){"use strict";n.__esModule=!0;var r={exit:function(e){return 1===e.expressions.length?e.expressions[0]:void(e.expressions.length||this.remove())}};n.SequenceExpression=r;var l={exit:function(e){e.expression||this.remove()}};n.ExpressionStatement=l;var i={exit:function(e){var t=e.right,n=e.left;if(n||t){if(!n)return t;if(!t)return n}else this.remove()}};n.Binary=i},{}],113:[function(e,t,n){"use strict";function r(e,t,n,r){e._declarations&&i.wrap(e,function(){var t,n={};for(var l in e._declarations){var i=e._declarations[l];t=i.kind||"var";var a=s.variableDeclarator(i.id,i.init);if(i.init)e.body.unshift(r.attachAuxiliaryComment(s.variableDeclaration(t,[a])));else{var o=n,u=t;o[u]||(o[u]=[]),n[t].push(a)}}for(t in n)e.body.unshift(r.attachAuxiliaryComment(s.variableDeclaration(t,n[t])));e._declarations=null})}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.BlockStatement=r,n.__esModule=!0;var i=l(e("../../helpers/strict")),s=l(e("../../../types")),a={secondPass:!0};n.metadata=a,n.Program=r},{"../../../types":153,"../../helpers/strict":62}],114:[function(e,t,n){"use strict";function r(e,t,n,r){i.wrap(e,function(){e.body=r.dynamicImports.concat(e.body)}),r.transformers["es6.modules"].canTransform()&&r.moduleFormatter.transform&&r.moduleFormatter.transform(e)}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=r,n.__esModule=!0;var i=l(e("../../helpers/strict"))},{"../../helpers/strict":62}],115:[function(e,t,n){"use strict";function r(e){return u.isImportDeclaration(e)||u.isExportDeclaration(e)}function l(e,t,n,r){e.source&&(e.source.value=r.resolveModuleSource(e.source.value))}function i(e,t,n){l.apply(this,arguments);var r=e.declaration,i=function(){return r._ignoreUserWhitespace=!0,r};if(u.isClassDeclaration(r))return e.declaration=r.id,[i(),e];if(u.isClassExpression(r)){var s=n.generateUidIdentifier("default");return r=u.variableDeclaration("var",[u.variableDeclarator(s,r)]),e.declaration=s,[i(),e]}return u.isFunctionDeclaration(r)?(e._blockHoist=2,e.declaration=r.id,[i(),e]):void 0}function s(e){l.apply(this,arguments);var t=e.declaration,n=function(){return t._ignoreUserWhitespace=!0,t};if(u.isClassDeclaration(t))return e.specifiers=[u.exportSpecifier(t.id,t.id)],e.declaration=null,[n(),e];if(u.isFunctionDeclaration(t))return e.specifiers=[u.exportSpecifier(t.id,t.id)],e.declaration=null,e._blockHoist=2,[n(),e];if(u.isVariableDeclaration(t)){var r=[],i=this.get("declaration").getBindingIdentifiers();for(var s in i){var a=i[s];r.push(u.exportSpecifier(a,a))}return[t,u.exportNamedDeclaration(null,r)]}}function a(e){for(var t=[],n=[],r=0;r<e.body.length;r++){var l=e.body[r];u.isImportDeclaration(l)?t.push(l):n.push(l)}e.body=t.concat(n)}var o=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.ImportDeclaration=l,n.ExportDefaultDeclaration=i,n.ExportNamedDeclaration=s,n.Program=a,n.__esModule=!0;var u=o(e("../../../types"))},{"../../../types":153}],116:[function(e,t,n){"use strict";function r(e,t,n){var r,l,i={getArgumentsId:function(){return!r&&(r=n.generateUidIdentifier("arguments")),r},getThisId:function(){return!l&&(l=n.generateUidIdentifier("this")),l}};t.traverse(u,i);var s,o=function(t,n){s||(s=e()),s.unshift(a.variableDeclaration("var",[a.variableDeclarator(t,n)]))};r&&o(r,a.identifier("arguments")),l&&o(l,a.thisExpression())}function l(e,t,n){r(function(){return e.body},this,n)}function i(e,t,n){r(function(){return a.ensureBlock(e),e.body.body},this,n)}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=l,n.FunctionDeclaration=i,n.__esModule=!0;var a=s(e("../../../types")),o={enter:function(e,t,n,r){if(this.isClass(e))return this.skip();if(this.isFunction()&&!e.shadow)return this.skip();if(e._shadowedFunctionLiteral)return this.skip();var l;if(this.isIdentifier()&&"arguments"===e.name)l=r.getArgumentsId;else{if(!this.isThisExpression())return;l=r.getThisId}return this.isReferenced()?l():void 0}},u={enter:function(e,t,n,r){return e.shadow?(this.traverse(o,r),e.shadow=!1,this.skip()):this.isFunction()?this.skip():void 0}};n.FunctionExpression=i},{"../../../types":153}],117:[function(e,t,n){"use strict";function r(e,t,n,r){if(r.transformers.strict.canTransform()){var l=r.get("existingStrictDirective");if(!l){l=i.expressionStatement(i.literal("use strict"));var s=e.body[0];s&&(l.leadingComments=s.leadingComments,s.leadingComments=[])}e.body.unshift(l)}}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=r,n.__esModule=!0;var i=l(e("../../../types"))},{"../../../types":153}],118:[function(e,t,n){"use strict";function r(e,t,n,r){var l=e.left;if(u.isVariableDeclaration(l)){var i=l.declarations[0];if(i.init)throw r.errorWithNode(i,o.get("noAssignmentsInForHead"))}}function l(e){if("constructor"!==e.kind){var t=!e.computed&&u.isIdentifier(e.key,{name:"constructor"});if(t||(t=u.isLiteral(e.key,{value:"constructor"})),t)throw this.errorWithNode(o.get("classesIllegalConstructorKind"))}i.apply(this,arguments)}function i(e,t,n,r){if("set"===e.kind){if(1!==e.value.params.length)throw r.errorWithNode(e.value,o.get("settersInvalidParamLength"));var l=e.value.params[0];if(u.isRestElement(l))throw r.errorWithNode(l,o.get("settersNoRest"))}}function s(e){for(var t=0;t<e.body.length;t++){var n=e.body[t];if(!u.isExpressionStatement(n)||!u.isLiteral(n.expression))return;n._blockHoist=1/0}}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.ForOfStatement=r,n.MethodDefinition=l,n.Property=i,n.BlockStatement=s,n.__esModule=!0;var o=a(e("../../../messages")),u=a(e("../../../types")),p={readOnly:!0};n.metadata=p,n.ForInStatement=r,n.Program=s},{"../../../messages":43,"../../../types":153}],119:[function(e,t,n){"use strict";function r(e,t,n,r){return this.get("right").isTypeGeneric("Array")?i.call(this,e,n,r):void 0}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.ForOfStatement=r,n.__esModule=!0;var i=e("../es6/for-of")._ForOfStatementArray,s=l(e("../../../types")),a=s.isForOfStatement;n.check=a;var o=!0;n.optional=o},{"../../../types":153,"../es6/for-of":87}],120:[function(e,t,n){"use strict";function r(e){if(!e._ignoreConstant){var t={isImmutable:!0};this.traverse(s,t),this.skip(),t.isImmutable&&(this.hoist(),e._ignoreConstant=!0)}}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.JSXElement=r,n.__esModule=!0;var i=(l(e("../../helpers/react")),{optional:!0});n.metadata=i;var s={enter:function(e,t,n,r){var l=this,i=function(){r.isImmutable=!1,l.stop()};return this.isJSXClosingElement()?void this.skip():this.isJSXIdentifier({name:"ref"})&&this.parentPath.isJSXAttribute({name:e})?i():void(this.isJSXIdentifier()||this.isIdentifier()||this.isJSXMemberExpression()||this.isImmutable()||i())}}},{"../../helpers/react":58}],121:[function(e,t,n){"use strict";function r(e){for(var t=0;t<e.length;t++){var n=e[t];if(o.isJSXSpreadAttribute(n))return!0;if(l(n,"ref"))return!0}return!1}function l(e,t){return o.isJSXAttribute(e)&&o.isJSXIdentifier(e.name,{name:t})}function i(e,t,n,i){function s(e,t){u(f.properties,o.identifier(e),t)}function u(e,t,n){e.push(o.property("init",t,n))}var p=e.openingElement;if(!r(p.attributes)){var c=!0,d=o.objectExpression([]),f=o.objectExpression([]),h=o.literal(null),m=p.name;o.isJSXIdentifier(m)&&a.isCompatTag(m.name)&&(m=o.literal(m.name),c=!1),s("type",m),s("ref",o.literal(null)),e.children.length&&u(d.properties,o.identifier("children"),o.arrayExpression(a.buildChildren(e)));for(var g=0;g<p.attributes.length;g++){var y=p.attributes[g];l(y,"key")?h=y.value:u(d.properties,y.name,y.value)}return c&&(d=o.callExpression(i.addHelper("default-props"),[o.memberExpression(m,o.identifier("defaultProps")),d])),s("props",d),s("key",h),f}}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.JSXElement=i,n.__esModule=!0;var a=s(e("../../helpers/react")),o=s(e("../../../types")),u={optional:!0};n.metadata=u},{"../../../types":153,"../../helpers/react":58}],122:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e};n.__esModule=!0;var l=r(e("../../helpers/remap-async-to-generator"));n.manipulateOptions=e("./bluebird-coroutines").manipulateOptions;var i={optional:!0};n.metadata=i,n.Function=function(e,t,n,r){return e.async&&!e.generator?l(e,r.addHelper("async-to-generator"),n):void 0}},{"../../helpers/remap-async-to-generator":60,"./bluebird-coroutines":123}],123:[function(e,t,n){"use strict";function r(e){e.optional.push("es7.asyncFunctions"),e.blacklist.push("regenerator")}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e};n.manipulateOptions=r,n.__esModule=!0;var s=i(e("../../helpers/remap-async-to-generator")),a=l(e("../../../types")),o={optional:!0};n.metadata=o,n.Function=function(e,t,n,r){return e.async&&!e.generator?s(e,a.memberExpression(r.addImport("bluebird",null,!0),a.identifier("coroutine")),n):void 0}},{"../../../types":153,"../../helpers/remap-async-to-generator":60}],124:[function(e,t,n){"use strict";function r(){this.remove()}function l(e){e.typeAnnotation=null,e.value||this.remove()}function i(e){e["implements"]=null}function s(e){return e.expression}function a(e){e.isType&&this.remove()}function o(){this.get("declaration").isTypeAlias()&&this.remove()}var u=function(e){return e&&e.__esModule?e:{"default":e}};n.Flow=r,n.ClassProperty=l,n.Class=i,n.TypeCastExpression=s,n.ImportDeclaration=a,n.ExportDeclaration=o,n.__esModule=!0;u(e("../../../types"));n.Function=function(e){for(var t=0;t<e.params.length;t++){var n=e.params[t];n.optional=!1}}},{"../../../types":153}],125:[function(e,t,n){"use strict";function r(e){return"in"===e.operator?o.template("ludicrous-in",{LEFT:e.left,RIGHT:e.right}):void 0}function l(e){var t=e.key;a.isLiteral(t)&&"number"==typeof t.value&&(t.value=""+t.value)}function i(e){e.regex&&(e.regex.pattern="foobar",e.regex.flags="")}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.BinaryExpression=r,n.Property=l,n.Literal=i,n.__esModule=!0;var a=s(e("../../../types")),o=s(e("../../../util")),u={optional:!0};n.metadata=u},{"../../../types":153,"../../../util":157}],126:[function(e,t,n){"use strict";function r(e){e.blacklist.push("react")}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.manipulateOptions=r,n.__esModule=!0;var i=l(e("../../helpers/react")),s=l(e("../../../types")),a={optional:!0};n.metadata=a,e("../../helpers/build-react-transformer")(n,{pre:function(e){e.callee=e.tagExpr},post:function(e){i.isCompatTag(e.tagName)&&(e.call=s.callExpression(s.memberExpression(s.memberExpression(s.identifier("React"),s.identifier("DOM")),e.tagExpr,s.isLiteral(e.tagExpr)),e.args))}})},{"../../../types":153,"../../helpers/build-react-transformer":52,"../../helpers/react":58}],127:[function(e,t,n){"use strict";function r(e,t,n,r){for(var l=r.opts.jsxPragma,i=0;i<r.ast.comments.length;i++){var o=r.ast.comments[i],u=a.exec(o.value);if(u){if(l=u[1],"React.DOM"===l)throw r.errorWithNode(o,"The @jsx React.DOM pragma has been deprecated as of React 0.12");break}}r.set("jsxIdentifier",l.split(".").map(s.identifier).reduce(function(e,t){return s.memberExpression(e,t)}))}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=r,n.__esModule=!0;var i=l(e("../../helpers/react")),s=l(e("../../../types")),a=/^\*\s*@jsx\s+([^\s]+)/;e("../../helpers/build-react-transformer")(n,{pre:function(e){var t=e.tagName,n=e.args;n.push(i.isCompatTag(t)?s.literal(t):e.tagExpr)},post:function(e,t){e.callee=t.get("jsxIdentifier")}})},{"../../../types":153,"../../helpers/build-react-transformer":52,"../../helpers/react":58}],128:[function(e,t,n){"use strict";function r(e){return a.isFunction(e)&&(e.async||e.generator)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e};n.check=r,n.__esModule=!0;var s=i(e("regenerator-babel")),a=l(e("../../../types")),o={enter:function(e){s.transform(e),this.stop()}};n.Program=o},{"../../../types":153,"regenerator-babel":428}],129:[function(e,t,n){"use strict";function r(e){return"_"!==e.name&&u(s,e.name)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e},s=i(e("core-js/library")),a=i(e("lodash/collection/includes")),o=l(e("../../../util")),u=i(e("lodash/object/has")),p=l(e("../../../types")),c=p.buildMatchMemberExpression("Symbol.iterator"),d=["Symbol","Promise","Map","WeakMap","Set","WeakSet"],f={enter:function(e,t,n,l){var i;if(this.isMemberExpression()&&this.isReferenced()){var f=e.object;if(i=e.property,!p.isReferenced(f,e))return;if(!e.computed&&r(f)&&u(s[f.name],i.name)&&!n.getBindingIdentifier(f.name))return this.skip(),p.prependToMemberExpression(e,l.get("coreIdentifier"))}else{if(this.isReferencedIdentifier()&&!p.isMemberExpression(t)&&a(d,e.name)&&!n.getBindingIdentifier(e.name))return p.memberExpression(l.get("coreIdentifier"),e);if(this.isCallExpression()){var h=e.callee;
return e.arguments.length?!1:p.isMemberExpression(h)&&h.computed?(i=h.property,c(i)?o.template("corejs-iterator",{CORE_ID:l.get("coreIdentifier"),VALUE:h.object}):!1):!1}if(this.isBinaryExpression()){if("in"!==e.operator)return;var m=e.left;if(!c(m))return;return o.template("corejs-is-iterator",{CORE_ID:l.get("coreIdentifier"),VALUE:e.right})}}}};n.metadata={optional:!0},n.Program=function(e,t,n,r){this.traverse(f,r)},n.pre=function(e){e.set("helperGenerator",function(t){return e.addImport("babel-runtime/helpers/"+t,t)}),e.setDynamic("coreIdentifier",function(){return e.addImport("babel-runtime/core-js","core")}),e.setDynamic("regeneratorIdentifier",function(){return e.addImport("babel-runtime/regenerator","regeneratorRuntime")})},n.Identifier=function(e,t,n,r){return this.isReferencedIdentifier({name:"regeneratorRuntime"})?r.get("regeneratorIdentifier"):void 0}},{"../../../types":153,"../../../util":157,"core-js/library":209,"lodash/collection/includes":319,"lodash/object/has":407}],130:[function(e,t,n){"use strict";function r(e,t,n,r){var l=e.body[0];u.isExpressionStatement(l)&&u.isLiteral(l.expression,{value:"use strict"})&&r.set("existingStrictDirective",e.body.shift())}function l(){this.skip()}function i(){return u.identifier("undefined")}function s(e,t,n,r){if(u.isIdentifier(e.callee,{name:"eval"}))throw r.errorWithNode(e,o.get("evalInStrictMode"))}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=r,n.FunctionExpression=l,n.ThisExpression=i,n.CallExpression=s,n.__esModule=!0;var o=a(e("../../../messages")),u=a(e("../../../types"));n.FunctionDeclaration=l,n.Class=l},{"../../../messages":43,"../../../types":153}],131:[function(e,t,n){"use strict";function r(e,t,n){for(var r=0;r<t[e].length;r++){var l=t[e][r];if(a.isFunctionDeclaration(l)){var i=a.variableDeclaration("let",[a.variableDeclarator(l.id,a.toExpression(l))]);i._blockHoist=2,l.id=null,t[e][r]=i,n.checkNode(i)}}}function l(e,t,n,l){a.isFunction(t)&&t.body===e||a.isExportDeclaration(t)||r("body",e,l)}function i(e,t,n,l){r("consequent",e,l)}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.BlockStatement=l,n.SwitchCase=i,n.__esModule=!0;var a=s(e("../../../types"))},{"../../../types":153}],132:[function(e,t,n){"use strict";n.__esModule=!0;var r=e("../../helpers/name-method");n.FunctionExpression=r.bare,n.ArrowFunctionExpression=r.bare},{"../../helpers/name-method":57}],133:[function(e,t,n){"use strict";function r(e){return c.isLiteral(c.toComputedKey(e,e.key),{value:"__proto__"})}function l(e){var t=e.left;return c.isMemberExpression(t)&&c.isLiteral(c.toComputedKey(t,t.property),{value:"__proto__"})}function i(e,t,n){return c.expressionStatement(c.callExpression(n.addHelper("defaults"),[t,e.right]))}function s(e,t,n,r){if(l(e)){var s=[],a=e.left.object,o=n.generateMemoisedReference(a);return s.push(c.expressionStatement(c.assignmentExpression("=",o,a))),s.push(i(e,o,r)),o&&s.push(o),s}}function a(e,t,n,r){var s=e.expression;if(c.isAssignmentExpression(s,{operator:"="}))return l(s)?i(s,s.left.object,r):void 0}function o(e,t,n,l){for(var i,s=0;s<e.properties.length;s++){var a=e.properties[s];r(a)&&(i=a.value,d(e.properties,a))}if(i){var o=[c.objectExpression([]),i];return e.properties.length&&o.push(e),c.callExpression(l.addHelper("extends"),o)}}var u=function(e){return e&&e.__esModule?e["default"]:e},p=function(e){return e&&e.__esModule?e:{"default":e}};n.AssignmentExpression=s,n.ExpressionStatement=a,n.ObjectExpression=o,n.__esModule=!0;var c=p(e("../../../types")),d=u(e("lodash/array/pull")),f={secondPass:!0,optional:!0};n.metadata=f},{"../../../types":153,"lodash/array/pull":313}],134:[function(e,t,n){"use strict";function r(e){return"undefined"===e.name&&this.isReferenced()?i.unaryExpression("void",i.literal(0),!0):void 0}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.Identifier=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0,react:!0};n.metadata=s},{"../../../types":153}],135:[function(e,t,n){"use strict";function r(e){if(s.isBlockStatement(e)){for(var t=!1,n=0;n<e.body.length;n++){var r=e.body[n];s.isBlockScoped(r)&&(t=!0)}if(!t)return e.body}return e}function l(e){var t=this.get("test").evaluateTruthy();return t===!0?e.consequent:t===!1?e.alternate:void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.ConditionalExpression=l,n.__esModule=!0;var s=i(e("../../../types")),a={optional:!0};n.metadata=a;var o={exit:function(e){var t=e.consequent,n=e.alternate,l=this.get("test").evaluateTruthy();return l===!0?r(t):l===!1?n?r(n):this.remove():(s.isBlockStatement(n)&&!n.body.length&&(n=e.alternate=null),void(s.isBlockStatement(t)&&!t.body.length&&s.isBlockStatement(n)&&n.body.length&&(e.consequent=e.alternate,e.alternate=null,e.test=s.unaryExpression("!",test,!0))))}};n.IfStatement=o},{"../../../types":153}],136:[function(e,t,n){(function(t){"use strict";function r(e){if(a(e.object)){var n=this.toComputedKey();if(i.isLiteral(n))return i.valueToNode(t.env[n.value])}}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.MemberExpression=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0};n.metadata=s;var a=i.buildMatchMemberExpression("process.env")}).call(this,e("_process"))},{"../../../types":153,_process:183}],137:[function(e,t,n){"use strict";function r(){var e=this.evaluate();return e.confident?s.valueToNode(e.value):void 0}function l(){}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.Expression=r,n.Identifier=l,n.__esModule=!0;var s=i(e("../../../types")),a={optional:!0};n.metadata=a},{"../../../types":153}],138:[function(e,t,n){"use strict";function r(e,t){this.get("callee").matchesPattern("console",!0)&&(i.isExpressionStatement(t)?this.parentPath.remove():this.remove())}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.CallExpression=r,n.__esModule=!0;var i=l(e("../../../types")),s={optional:!0};n.metadata=s},{"../../../types":153}],139:[function(e,t,n){"use strict";function r(){this.get("expression").isIdentifier({name:"debugger"})&&this.remove()}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.ExpressionStatement=r,n.__esModule=!0;var i=(l(e("../../../types")),{optional:!0});n.metadata=i},{"../../../types":153}],140:[function(e,t,n){"use strict";function r(e,t){if(o.isLiteral(e)){var n=e.value,r=n.toLowerCase();if("react"===r&&n!==r)throw t.errorWithNode(e,a.get("didYouMean","react"))}}function l(e,t,n,l){this.get("callee").isIdentifier({name:"require"})&&1===e.arguments.length&&r(e.arguments[0],l)}function i(e,t,n,l){r(e.source,l)}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.CallExpression=l,n.ModuleDeclaration=i,n.__esModule=!0;var a=s(e("../../../messages")),o=s(e("../../../types"))},{"../../../messages":43,"../../../types":153}],141:[function(e,t,n){"use strict";function r(e,t,n,r){if(this.isReferenced()&&!n.hasBinding(e.name)){var l,i=n.getAllBindings(),o=-1;for(var u in i){var p=s(e.name,u);0>=p||p>3||o>=p||(l=u,o=p)}var c;throw c=l?a.get("undeclaredVariableSuggestion",e.name,l):a.get("undeclaredVariable",e.name),r.errorWithNode(e,c,ReferenceError)}}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e};n.Identifier=r,n.__esModule=!0;var s=i(e("leven")),a=l(e("../../../messages")),o={optional:!0};n.metadata=o},{"../../../messages":43,leven:307}],142:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("../types")),i=function(){function e(t){var n=t.identifier,l=t.scope,i=t.path,s=t.kind;r(this,e),this.identifier=n,this.constant=!0,this.scope=l,this.path=i,this.kind=s}return e.prototype.setTypeAnnotation=function(){var e=this.path.getTypeAnnotation();this.typeAnnotationInferred=e.inferred,this.typeAnnotation=e.annotation},e.prototype.isTypeGeneric=function(){var e;return(e=this.path).isTypeGeneric.apply(e,arguments)},e.prototype.assignTypeGeneric=function(e,t){var n=null;t&&(t=l.typeParameterInstantiation(t)),this.assignType(l.genericTypeAnnotation(l.identifier(e),n))},e.prototype.assignType=function(e){this.typeAnnotation=e},e.prototype.reassign=function(){this.constant=!1,this.typeAnnotationInferred&&(this.typeAnnotation=null)},e.prototype.isCompatibleWithType=function(){return!1},e}();t.exports=i},{"../types":153}],143:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("./path")),s=(r(e("lodash/array/compact")),n(e("../types")),function(){function e(t,n,r,i){l(this,e),this.parentPath=i,this.scope=t,this.state=r,this.opts=n}return e.prototype.create=function(e,t,n){return i.get(this.parentPath,this,e,t,n)},e.prototype.visitMultiple=function(e,t){if(0===e.length)return!1;for(var n=[],r=this.queue=[],l=!1,i=0;i<e.length;i++)e[i]&&r.push(this.create(t,e,i));for(var i=0;i<r.length;i++){var s=r[i];if(!(n.indexOf(s.node)>=0)&&(n.push(s.node),s.visit())){l=!0;break}}for(var i=0;i<r.length;i++);return l},e.prototype.visitSingle=function(e,t){return this.create(e,e,t).visit()},e.prototype.visit=function(e,t){var n=e[t];if(n)return Array.isArray(n)?this.visitMultiple(n,e,t):this.visitSingle(e,t)},e}());t.exports=s},{"../types":153,"./path":148,"lodash/array/compact":310}],144:[function(e,t){"use strict";function n(e,t,r,l,i){if(e){if(!t.noScope&&!r&&"Program"!==e.type&&"File"!==e.type)throw new Error("Must pass a scope and parentPath unless traversing a Program/File got a "+e.type+" node");if(t||(t={}),t.enter||(t.enter=function(){}),t.exit||(t.exit=function(){}),Array.isArray(e))for(var s=0;s<e.length;s++)n.node(e[s],t,r,l,i);else n.node(e,t,r,l,i)}}function r(e){for(var t=0;t<p.length;t++){var n=p[t];null!=e[n]&&(e[n]=null)}for(var n in e){var r=e[n];Array.isArray(r)&&delete r._paths}}function l(e,t,n,r){e.type===r.type&&(r.has=!0,this.skip())}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};t.exports=n;var a=s(e("./context")),o=s(e("lodash/collection/includes")),u=i(e("../types"));n.node=function(e,t,n,r,l){var i=u.VISITOR_KEYS[e.type];if(i)for(var s=new a(n,t,r,l),o=0;o<i.length;o++)if(s.visit(e,i[o]))return};var p=["trailingComments","leadingComments","extendedRange","_declarations","_scopeInfo","_paths","tokens","range","start","end","loc","raw"],c={noScope:!0,exit:r};n.removeProperties=function(e){return n(e,c),r(e),e},n.explode=function(e){for(var t in e){var n=e[t],r=u.FLIPPED_ALIAS_KEYS[t];if(r)for(var l=0;l<r.length;l++){var i=e,s=r[l];i[s]||(i[s]=n)}}return e},n.hasType=function(e,t,r,i){if(o(i,e.type))return!1;if(e.type===r)return!0;var s={has:!1,type:r};return n(e,{blacklist:i,enter:l},t,s),s.has}},{"../types":153,"./context":143,"lodash/collection/includes":319}],145:[function(e,t,n){"use strict";function r(){var e,t=this.node;if(this.isMemberExpression())e=t.property;else{if(!this.isProperty())throw new ReferenceError("todo");e=t.key}return t.computed||i.isIdentifier(e)&&(e=i.literal(e.name)),e}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.toComputedKey=r,n.__esModule=!0;var i=l(e("../../types"))},{"../../types":153}],146:[function(e,t,n){"use strict";function r(){var e=this.evaluate();return e.confident?!!e.value:void 0}function l(){function e(n){if(t){var r=n.node;if(n.isSequenceExpression()){var l=n.get("expressions");return e(l[l.length-1])}if(n.isLiteral()&&(!r.regex||null!==r.value))return r.value;if(n.isConditionalExpression())return e(e(n.get("test"))?n.get("consequent"):n.get("alternate"));if(n.isIdentifier({name:"undefined"}))return void 0;if(n.isIdentifier()||n.isMemberExpression())return n=n.resolve(),n?e(n):t=!1;if(n.isUnaryExpression({prefix:!0})){var i=e(n.get("argument"));switch(r.operator){case"void":return void 0;case"!":return!i;case"+":return+i;case"-":return-i}}if(n.isArrayExpression()||n.isObjectExpression(),n.isLogicalExpression()){var s=e(n.get("left")),a=e(n.get("right"));switch(r.operator){case"||":return s||a;case"&&":return s&&a}}if(n.isBinaryExpression()){var s=e(n.get("left")),a=e(n.get("right"));switch(r.operator){case"-":return s-a;case"+":return s+a;case"/":return s/a;case"*":return s*a;case"%":return s%a;case"<":return a>s;case">":return s>a;case"<=":return a>=s;case">=":return s>=a;case"==":return s==a;case"!=":return s!=a;case"===":return s===a;case"!==":return s!==a}}t=!1}}var t=!0,n=e(this);return t||(n=void 0),{confident:t,value:n}}n.evaluateTruthy=r,n.evaluate=l,n.__esModule=!0},{}],147:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("../../transformation/helpers/react")),i=n(e("../../types")),s={enter:function(e,t,n,r){if((!this.isJSXIdentifier()||!l.isCompatTag(e.name))&&(this.isJSXIdentifier()||this.isIdentifier())&&this.isReferenced()){var i=n.getBinding(e.name);if(i!==r.scope.getBinding(e.name))return;i&&i.constant?r.bindings[e.name]=i:(n.dump(),r.foundIncompatible=!0,this.stop())}}},a=function(){function e(t,n){r(this,e),this.foundIncompatible=!1,this.bindings={},this.scope=n,this.scopes=[],this.path=t}return e.prototype.isCompatibleScope=function(e){for(var t in this.bindings){var n=this.bindings[t];if(!e.bindingIdentifierEquals(t,n.identifier))return!1}return!0},e.prototype.getCompatibleScopes=function(){var e=this.path.scope;do{if(!this.isCompatibleScope(e))break;this.scopes.push(e)}while(e=e.parent)},e.prototype.getAttachmentPath=function(){var e=this.scopes,t=e.pop();return t.path.isFunction()?this.hasNonParamBindings()?this.getNextScopeStatementParent():t.path.get("body").get("body")[0]:t.path.isProgram()?this.getNextScopeStatementParent():void 0},e.prototype.getNextScopeStatementParent=function(){var e=this.scopes.pop();return e?e.path.getStatementParent():void 0},e.prototype.hasNonParamBindings=function(){for(var e in this.bindings){var t=this.bindings[e];if("param"!==t.kind)return!0}return!1},e.prototype.run=function(){if(this.path.traverse(s,this),!this.foundIncompatible){this.getCompatibleScopes();var e=this.getAttachmentPath();if(e){var t=e.scope.generateUidIdentifier("ref");e.insertBefore([i.variableDeclaration("var",[i.variableDeclarator(t,this.path.node)])]),this.path.replaceWith(t)}}},e}();t.exports=a},{"../../transformation/helpers/react":58,"../../types":153}],148:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(){function e(e,t){for(var n in t){var r=t[n];r.configurable=!0,r.value&&(r.writable=!0)}Object.defineProperties(e,t)}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=r(e("./hoister")),a=r(e("lodash/lang/isBoolean")),o=r(e("lodash/lang/isNumber")),u=(r(e("lodash/lang/isRegExp")),r(e("lodash/lang/isString"))),p=r(e("../index")),c=r(e("lodash/collection/includes")),d=r(e("lodash/object/assign")),f=(r(e("lodash/object/extend")),r(e("../scope"))),h=n(e("../../types")),m={enter:function(e,t,n){if(this.isFunction())return this.skip();if(this.isVariableDeclaration()&&"var"===e.kind){var r=this.getBindingIdentifiers();for(var l in r)n.push({id:r[l]});for(var i=[],s=0;s<e.declarations.length;s++){var a=e.declarations[s];a.init&&i.push(h.expressionStatement(h.assignmentExpression("=",a.id,a.init)))}return i}}},g=function(){function e(t,n){i(this,e),this.container=n,this.parent=t,this.data={}}return e.get=function(t,n,r,l,i,s){for(var a,o,u=l[i],p=(a=l,!a._paths&&(a._paths=[]),a._paths),c=0;c<p.length;c++){var d=p[c];if(d.node===u){o=d;break}}return o||(o=new e(r,l),p.push(o)),o.setContext(t,n,i,s),o},e.getScope=function(e,t,n){var r=t;return e.isScope()&&(r=new f(e,t,n)),r},e.prototype.queueNode=function(e){this.context&&this.context.queue.push(e)},e.prototype.insertBefore=function(e){if(e=this._verifyNodeList(e),this.checkNodes(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertBefore(e);if(this.isPreviousType("Statement"))if(this._maybePopFromStatements(e),Array.isArray(this.container))this._containerInsertBefore(e);else{if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.push(this.node),this.container[this.key]=h.blockStatement(e)}else{if(!this.isPreviousType("Expression"))throw new Error("No clue what to do with this node type.");this.node&&e.push(this.node),this.replaceExpressionWithStatements(e)}},e.prototype._containerInsert=function(e,t){this.updateSiblingKeys(e,t.length);for(var n=0;n<t.length;n++){var r=e+n;this.container.splice(r,0,t[n]),this.context&&this.queueNode(this.context.create(this.parent,this.container,r))}},e.prototype._containerInsertBefore=function(e){this._containerInsert(this.key,e)},e.prototype._containerInsertAfter=function(e){this._containerInsert(this.key+1,e)},e.prototype._maybePopFromStatements=function(e){var t=e[e.length-1];h.isExpressionStatement(t)&&h.isIdentifier(t.expression)&&e.pop()},e.prototype.isStatementOrBlock=function(){return h.isLabeledStatement(this.parent)||h.isBlockStatement(this.container)?!1:c(h.STATEMENT_OR_BLOCK_KEYS,this.key)},e.prototype.insertAfter=function(e){if(e=this._verifyNodeList(e),this.checkNodes(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertAfter(e);if(this.isPreviousType("Statement"))if(this._maybePopFromStatements(e),Array.isArray(this.container))this._containerInsertAfter(e);else{if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.unshift(this.node),this.container[this.key]=h.blockStatement(e)}else{if(!this.isPreviousType("Expression"))throw new Error("No clue what to do with this node type.");if(this.node){var t=this.scope.generateTemp();e.unshift(h.expressionStatement(h.assignmentExpression("=",t,this.node))),e.push(h.expressionStatement(t))}this.replaceExpressionWithStatements(e)}},e.prototype.updateSiblingKeys=function(e,t){for(var n=this.container._paths,r=0;r<n.length;r++){var l=n[r];l.key>=e&&(l.key+=t)}},e.prototype.setData=function(e,t){return this.data[e]=t},e.prototype.getData=function(e,t){var n=this.data[e];return!n&&t&&(n=this.data[e]=t),n},e.prototype.setScope=function(t){this.scope=e.getScope(this,this.context&&this.context.scope,t)},e.prototype.clearContext=function(){this.context=null},e.prototype.setContext=function(e,t,n,r){this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.parentPath=e||this.parentPath,this.key=n,t&&(this.context=t,this.state=t.state,this.opts=t.opts),this.type=this.node&&this.node.type,this.setScope(r)},e.prototype._remove=function(){Array.isArray(this.container)?(this.container.splice(this.key,1),this.updateSiblingKeys(this.key,-1)):this.container[this.key]=null},e.prototype.remove=function(){var e=!1;return this.parentPath&&(e||(e=this.parentPath.isExpressionStatement()),e||(e=this.parentPath.isSequenceExpression()&&1===this.parent.expressions.length),e)?this.parentPath.remove():(this._remove(),void(this.removed=!0))},e.prototype.skip=function(){this.shouldSkip=!0},e.prototype.stop=function(){this.shouldStop=!0,this.shouldSkip=!0},e.prototype.errorWithNode=function(e){var t=void 0===arguments[1]?SyntaxError:arguments[1],n=this.node.loc.start,r=new t("Line "+n.line+": "+e);return r.loc=n,r},e.prototype.replaceInline=function(e){return Array.isArray(e)?Array.isArray(this.container)?(e=this._verifyNodeList(e),this._containerInsertAfter(e),this.remove()):this.replaceWithMultiple(e):this.replaceWith(e)},e.prototype._verifyNodeList=function(e){e.constructor!==Array&&(e=[e]);for(var t=0;t<e.length;t++){var n=e[t];if(!n)throw new Error("Node list has falsy node with the index of "+t);if("object"!=typeof n)throw new Error("Node list contains a non-object node with the index of "+t);if(!n.type)throw new Error("Node list contains a node without a type with the index of "+t)}return e},e.prototype.replaceWithMultiple=function(e){e=this._verifyNodeList(e),h.inheritsComments(e[0],this.node),this.container[this.key]=null,this.insertAfter(e),this.node||this.remove()},e.prototype.replaceWith=function(e,t){if(this.removed)throw new Error("You can't replace this node, we've already removed it");if(!e)throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");if(Array.isArray(e)){if(t)return this.replaceWithMultiple(e);throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`")}if(this.isPreviousType("Expression")&&h.isStatement(e))return this.replaceExpressionWithStatements([e]);var n=this.node;n&&h.inheritsComments(e,n),this.container[this.key]=e,this.type=e.type,this.setScope(),this.checkNodes([e])},e.prototype.checkNodes=function(e){var t=this.scope,n=t&&t.file;if(n)for(var r=0;r<e.length;r++)n.checkNode(e[r],t)},e.prototype.getStatementParent=function(){var e=this;do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement())break;e=e.parentPath}while(e);if(e&&(e.isProgram()||e.isFile()))throw new Error("File/Program node, we can't possibly find a statement parent to this");return e},e.prototype.getLastStatements=function(){var e=[],t=function(t){t&&(e=e.concat(t.getLastStatements()))};return this.isIfStatement()?(t(this.get("consequent")),t(this.get("alternate"))):this.isDoExpression()?t(this.get("body")):this.isProgram()||this.isBlockStatement()?t(this.get("body").pop()):e.push(this),e},e.prototype.replaceExpressionWithStatements=function(e){var t=h.toSequenceExpression(e,this.scope);if(t)return this.replaceWith(t);var n=h.functionExpression(null,[],h.blockStatement(e));n.shadow=!0;for(var r=this.getLastStatements(),l=0;l<r.length;l++){var i=r[l];i.isExpressionStatement()&&i.replaceWith(h.returnStatement(i.node.expression))}return this.replaceWith(h.callExpression(n,[])),this.traverse(m),this.node},e.prototype.call=function(e){var t=this.node;if(t){var n=this.opts,r=n[e]||n;n[t.type]&&(r=n[t.type][e]||r);var l=r.call(this,t,this.parent,this.scope,this.state);l&&this.replaceWith(l,!0)}},e.prototype.isBlacklisted=function(){var e=this.opts.blacklist;return e&&e.indexOf(this.node.type)>-1},e.prototype.visit=function(){if(this.isBlacklisted())return!1;if(this.call("enter"),this.shouldSkip)return this.shouldStop;var e=this.node,t=this.opts;if(e)if(Array.isArray(e))for(var n=0;n<e.length;n++)p.node(e[n],t,this.scope,this.state,this);else p.node(e,t,this.scope,this.state,this),this.call("exit");return this.shouldStop},e.prototype.getSibling=function(t){return e.get(this.parentPath,null,this.parent,this.container,t,this.file)},e.prototype.get=function(t){var n=this,r=t.split(".");if(1===r.length){var l=this.node,i=l[t];return Array.isArray(i)?i.map(function(t,r){return e.get(n,null,l,i,r)}):e.get(this,null,l,l,t)}for(var s=this,a=0;a>r.length;a++){var o=r[a];s="."===o?s.parentPath:s.get(r[a])}return s},e.prototype.has=function(e){return!!this.node[e]},e.prototype.is=function(e){return this.has(e)},e.prototype.isnt=function(e){return!this.has(e)},e.prototype.getTypeAnnotation=function(){if(this.typeInfo)return this.typeInfo;var e=this.typeInfo={inferred:!1,annotation:null},t=this.node.typeAnnotation;return t||(e.inferred=!0,t=this.inferType(this)),t&&(h.isTypeAnnotation(t)&&(t=t.typeAnnotation),e.annotation=t),e},e.prototype.resolve=function(){if(this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve()}else{if(this.isIdentifier()){var e=this.scope.getBinding(this.node.name);return void(!e||!e.constant)}if(!this.isMemberExpression())return this;var t=this.toComputedKey();if(!h.isLiteral(t))return;var n=t.value,r=this.get("object").resolve();if(!r||!r.isObjectExpression())return;for(var l=r.get("properties"),i=0;i<l.length;i++){var s=l[i];if(s.isProperty()){var a=s.get("key"),o=s.isnt("computed")&&a.isIdentifier({name:n});if(o||(o=a.isLiteral({value:n})),o)return s.get("value")}}}},e.prototype.inferType=function(e){if(e=e.resolve()){if(e.isRestElement()||e.parentPath.isRestElement()||e.isArrayExpression())return h.genericTypeAnnotation(h.identifier("Array"));if(e.parentPath.isTypeCastExpression())return e.parentPath.node.typeAnnotation;if(e.isTypeCastExpression())return e.node.typeAnnotation;if(e.isObjectExpression())return h.genericTypeAnnotation(h.identifier("Object"));if(e.isFunction())return h.identifier("Function");if(e.isLiteral()){var t=e.node.value;if(u(t))return h.stringTypeAnnotation();if(o(t))return h.numberTypeAnnotation();if(a(t))return h.booleanTypeAnnotation()}if(e.isCallExpression()){var n=e.get("callee").resolve();if(n&&n.isFunction())return n.node.returnType}}},e.prototype.isScope=function(){return h.isScope(this.node,this.parent)},e.prototype.isReferencedIdentifier=function(e){return h.isReferencedIdentifier(this.node,this.parent,e)},e.prototype.isReferenced=function(){return h.isReferenced(this.node,this.parent)},e.prototype.isBlockScoped=function(){return h.isBlockScoped(this.node)},e.prototype.isVar=function(){return h.isVar(this.node)},e.prototype.isPreviousType=function(e){return h.isType(this.type,e)},e.prototype.isTypeGeneric=function(e){var t=void 0===arguments[1]?{}:arguments[1],n=this.getTypeAnnotation(),r=n.annotation;return r?r.inferred&&t.inference===!1?!1:h.isGenericTypeAnnotation(r)&&h.isIdentifier(r.id,{name:e})?t.requireTypeParameters&&!r.typeParameters?!1:!0:!1:!1},e.prototype.getBindingIdentifiers=function(){return h.getBindingIdentifiers(this.node)},e.prototype.traverse=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e,t){p(this.node,e,this.scope,t,this)}),e.prototype.hoist=function(){var e=void 0===arguments[0]?this.scope:arguments[0],t=new s(this,e);return t.run()},e.prototype.matchesPattern=function(e,t){var n=e.split(".");if(!this.isMemberExpression())return!1;for(var r=[this.node],l=0;r.length;){var i=r.shift();if(t&&l===n.length)return!0;if(h.isIdentifier(i)){if(n[l]!==i.name)return!1}else{if(!h.isLiteral(i)){if(h.isMemberExpression(i)){if(i.computed&&!h.isLiteral(i.property))return!1;r.push(i.object),r.push(i.property);continue}return!1}if(n[l]!==i.value)return!1}if(++l>n.length)return!1}return!0},l(e,{node:{get:function(){return this.removed?null:this.container[this.key]},set:function(){throw new Error("Don't use `path.node = newNode;`, use `path.replaceWith(newNode)` or `path.replaceWithMultiple([newNode])`")}}}),e}();t.exports=g,d(g.prototype,e("./evaluation")),d(g.prototype,e("./conversion"));for(var y=0;y<h.TYPES.length;y++)!function(){var e=h.TYPES[y],t="is"+e;g.prototype[t]=function(e){return h[t](this.node,e)}}()},{"../../types":153,"../index":144,"../scope":149,"./conversion":145,"./evaluation":146,"./hoister":147,"lodash/collection/includes":319,"lodash/lang/isBoolean":393,"lodash/lang/isNumber":397,"lodash/lang/isRegExp":400,"lodash/lang/isString":401,"lodash/object/assign":404,"lodash/object/extend":406}],149:[function(e,t){"use strict";var n=function(e){return e&&e.__esModule?e:{"default":e}},r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=r(e("lodash/collection/includes")),s=r(e("./index")),a=r(e("lodash/object/defaults")),o=n(e("../messages")),u=r(e("./binding")),p=r(e("globals")),c=r(e("lodash/array/flatten")),d=r(e("lodash/object/extend")),f=r(e("../helpers/object")),h=r(e("lodash/collection/each")),m=n(e("../types")),g={enter:function(e,t,n,r){var l=this;return m.isFor(e)&&h(m.FOR_INIT_KEYS,function(e){var t=l.get(e);t.isVar()&&r.scope.registerBinding("var",t)}),this.isFunction()?this.skip():void(r.blockId&&e===r.blockId||this.isBlockScoped()||this.isExportDeclaration()&&m.isDeclaration(e.declaration)||this.isDeclaration()&&r.scope.registerDeclaration(this))}},y={enter:function(e,t,n,r){m.isReferencedIdentifier(e,t)&&!n.hasBinding(e.name)?r.addGlobal(e):m.isLabeledStatement(e)?r.addGlobal(e):m.isAssignmentExpression(e)?n.registerConstantViolation(this.get("left"),this.get("right")):m.isUpdateExpression(e)?n.registerConstantViolation(this.get("argument"),null):m.isUnaryExpression(e)&&"delete"===e.operator&&n.registerConstantViolation(this.get("left"),null)}},b={enter:function(e,t,n,r){(this.isFunctionDeclaration()||this.isBlockScoped())&&r.registerDeclaration(this),this.isScope()&&this.skip()}},v=function(){function e(t,n,r){if(l(this,e),n&&n.block===t.node)return n;var i=t.getData("scope");return i&&i.parent===n?i:(t.setData("scope",this),this.parent=n,this.file=n?n.file:r,this.parentBlock=t.parent,this.block=t.node,this.path=t,void this.crawl())}return e.globals=c([p.builtin,p.browser,p.node].map(Object.keys)),e.contextVariables=["this","arguments","super"],e.prototype.traverse=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e,t,n){s(e,t,this,n,this.path)}),e.prototype.generateTemp=function(){var e=void 0===arguments[0]?"temp":arguments[0],t=this.generateUidIdentifier(e);return this.push({id:t}),t},e.prototype.generateUidIdentifier=function(e){return m.identifier(this.generateUid(e))},e.prototype.generateUid=function(e){e=m.toIdentifier(e).replace(/^_+/,"");var t,n=0;do t=this._generateUid(e,n),n++;while(this.hasBinding(t)||this.hasGlobal(t)||this.hasUid(t));return this.file.uids[t]=!0,t},e.prototype._generateUid=function(e,t){var n=e;return t>1&&(n+=t),"_"+n},e.prototype.hasUid=function(e){var t=this;do{if(t.file.uids[e])return!0;t=t.parent}while(t);return!1},e.prototype.generateUidBasedOnNode=function(e,t){var n=e;m.isAssignmentExpression(e)?n=e.left:m.isVariableDeclarator(e)?n=e.id:m.isProperty(n)&&(n=n.key);var r=[],l=function(e){var t=function(){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e){if(m.isModuleDeclaration(e))if(e.specifiers&&e.specifiers.length)for(var t=0;t<e.specifiers.length;t++)l(e.specifiers[t]);else l(e.source);else if(m.isModuleSpecifier(e))l(e.local);else if(m.isMemberExpression(e))l(e.object),l(e.property);else if(m.isIdentifier(e))r.push(e.name);else if(m.isLiteral(e))r.push(e.value);else if(m.isCallExpression(e))l(e.callee);else if(m.isObjectExpression(e)||m.isObjectPattern(e))for(var t=0;t<e.properties.length;t++){var n=e.properties[t];l(n.key||n.argument)}});l(n);var i=r.join("$");return i=i.replace(/^_/,"")||t||"ref",this.generateUidIdentifier(i)},e.prototype.generateMemoisedReference=function(e,t){if(m.isThisExpression(e)||m.isSuper(e))return null;if(m.isIdentifier(e)&&this.hasBinding(e.name))return null;var n=this.generateUidBasedOnNode(e);return t||this.push({id:n}),n},e.prototype.checkBlockScopedCollisions=function(e,t,n){var r=this.getOwnBindingInfo(t);if(r&&"param"!==e&&("hoisted"!==e||"let"!==r.kind)){var l=!1;if(l||(l="let"===e||"const"===e||"let"===r.kind||"const"===r.kind||"module"===r.kind),l||(l="param"===r.kind&&("let"===e||"const"===e)),l)throw this.file.errorWithNode(n,o.get("scopeDuplicateDeclaration",t),TypeError)}},e.prototype.rename=function(e,t,n){t||(t=this.generateUidIdentifier(e).name);var r=this.getBinding(e);if(r){var l=r.identifier,i=r.scope;i.traverse(n||i.block,{enter:function(n,r,i){if(m.isReferencedIdentifier(n,r)&&n.name===e)n.name=t;else if(m.isDeclaration(n)){var s=this.getBindingIdentifiers();for(var a in s)a===e&&(s[a].name=t)}else this.isScope()&&(i.bindingIdentifierEquals(e,l)||this.skip())}}),n||(i.removeOwnBinding(e),i.bindings[t]=r,l.name=t)}},e.prototype.dump=function(){var e=this;do console.log(e.block.type,"Bindings:",Object.keys(e.bindings));while(e=e.parent);console.log("-------------")},e.prototype.toArray=function(e,t){var n=this.file;
if(m.isIdentifier(e)){var r=this.getBinding(e.name);if(r&&r.isTypeGeneric("Array",{inference:!1}))return e}if(m.isArrayExpression(e))return e;if(m.isIdentifier(e,{name:"arguments"}))return m.callExpression(m.memberExpression(n.addHelper("slice"),m.identifier("call")),[e]);var l="to-array",i=[e];return t===!0?l="to-consumable-array":t&&(i.push(m.literal(t)),l="sliced-to-array",this.file.isLoose("es6.forOf")&&(l+="-loose")),m.callExpression(n.addHelper(l),i)},e.prototype.registerDeclaration=function(e){var t=e.node;if(m.isFunctionDeclaration(t))this.registerBinding("hoisted",e);else if(m.isVariableDeclaration(t))for(var n=e.get("declarations"),r=0;r<n.length;r++)this.registerBinding(t.kind,n[r]);else m.isClassDeclaration(t)?this.registerBinding("let",e):m.isImportDeclaration(t)||m.isExportDeclaration(t)?this.registerBinding("module",e):this.registerBinding("unknown",e)},e.prototype.registerConstantViolation=function(e,t){var n=e.getBindingIdentifiers();for(var r in n){var l=this.getBinding(r);if(l){if(t){var i=t.typeAnnotation;if(i&&l.isCompatibleWithType(i))continue}l.reassign()}}},e.prototype.registerBinding=function(e,t){if(!e)throw new ReferenceError("no `kind`");var n=t.getBindingIdentifiers();for(var r in n){var l=n[r];this.checkBlockScopedCollisions(e,r,l),this.bindings[r]=new u({identifier:l,scope:this,path:t,kind:e})}},e.prototype.addGlobal=function(e){this.globals[e.name]=e},e.prototype.hasGlobal=function(e){var t=this;do if(t.globals[e])return!0;while(t=t.parent);return!1},e.prototype.recrawl=function(){this.path.setData("scopeInfo",null),this.crawl()},e.prototype.crawl=function(){var e=this.path,t=this.block._scopeInfo;if(t)return d(this,t);if(t=this.block._scopeInfo={bindings:f(),globals:f()},d(this,t),e.isLoop())for(var n=0;n<m.FOR_INIT_KEYS.length;n++){var r=e.get(m.FOR_INIT_KEYS[n]);r.isBlockScoped()&&this.registerBinding("let",r)}if(e.isFunctionExpression()&&e.has("id")&&(m.isProperty(e.parent,{method:!0})||this.registerBinding("var",e.get("id"))),e.isClass()&&e.has("id")&&this.registerBinding("var",e.get("id")),e.isFunction()){for(var l=e.get("params"),n=0;n<l.length;n++)this.registerBinding("param",l[n]);this.traverse(e.get("body").node,b,this)}(e.isProgram()||e.isFunction())&&this.traverse(e.node,g,{blockId:e.get("id").node,scope:this}),(e.isBlockStatement()||e.isProgram())&&this.traverse(e.node,b,this),e.isCatchClause()&&this.registerBinding("let",e.get("param")),e.isComprehensionExpression()&&this.registerBinding("let",e),e.isProgram()&&this.traverse(e.node,y,this)},e.prototype.push=function(e){var t=this.block;(m.isLoop(t)||m.isCatchClause(t)||m.isFunction(t))&&(m.ensureBlock(t),t=t.body),m.isBlockStatement(t)||m.isProgram(t)||(t=this.getBlockParent().block);var n=t;n._declarations||(n._declarations={}),t._declarations[e.key||e.id.name]={kind:e.kind||"var",id:e.id,init:e.init}},e.prototype.getFunctionParent=function(){for(var e=this;e.parent&&!m.isFunction(e.block);)e=e.parent;return e},e.prototype.getBlockParent=function(){for(var e=this;e.parent&&!m.isFunction(e.block)&&!m.isLoop(e.block)&&!m.isFunction(e.block);)e=e.parent;return e},e.prototype.getAllBindings=function(){var e=f(),t=this;do a(e,t.bindings),t=t.parent;while(t);return e},e.prototype.getAllBindingsOfKind=function(){for(var e=f(),t=0;t<arguments.length;t++){var n=arguments[t],r=this;do{for(var l in r.bindings){var i=r.bindings[l];i.kind===n&&(e[l]=i)}r=r.parent}while(r)}return e},e.prototype.bindingIdentifierEquals=function(e,t){return this.getBindingIdentifier(e)===t},e.prototype.getBinding=function(e){var t=this;do{var n=t.getOwnBindingInfo(e);if(n)return n}while(t=t.parent)},e.prototype.getOwnBindingInfo=function(e){return this.bindings[e]},e.prototype.getBindingIdentifier=function(e){var t=this.getBinding(e);return t&&t.identifier},e.prototype.getOwnBindingIdentifier=function(e){var t=this.bindings[e];return t&&t.identifier},e.prototype.hasOwnBinding=function(e){return!!this.getOwnBindingInfo(e)},e.prototype.hasBinding=function(t){return t?this.hasOwnBinding(t)?!0:this.parentHasBinding(t)?!0:this.file.uids[t]?!0:i(e.globals,t)?!0:i(e.contextVariables,t)?!0:!1:!1},e.prototype.parentHasBinding=function(e){return this.parent&&this.parent.hasBinding(e)},e.prototype.removeOwnBinding=function(e){this.bindings[e]=null},e.prototype.removeBinding=function(e){var t=this.getBinding(e);t&&t.scope.removeOwnBinding(e)},e}();t.exports=v},{"../helpers/object":41,"../messages":43,"../types":153,"./binding":142,"./index":144,globals:302,"lodash/array/flatten":311,"lodash/collection/each":316,"lodash/collection/includes":319,"lodash/object/defaults":405,"lodash/object/extend":406}],150:[function(e,t){t.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While","Scopable"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While","Scopable"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ImportSpecifier:["ModuleSpecifier"],ExportSpecifier:["ModuleSpecifier"],ImportDefaultSpecifier:["ModuleSpecifier"],ExportDefaultSpecifier:["ModuleSpecifier"],ExportNamespaceSpecifier:["ModuleSpecifier"],ExportDefaultFromSpecifier:["ModuleSpecifier"],ExportAllDeclaration:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],ExportDefaultDeclaration:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],ExportNamedDeclaration:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],ImportDeclaration:["Statement","Declaration","ModuleDeclaration"],ArrowFunctionExpression:["Scopable","Function","Expression"],FunctionDeclaration:["Scopable","Function","Statement","Declaration"],FunctionExpression:["Scopable","Function","Expression"],BlockStatement:["Scopable","Statement"],Program:["Scopable"],CatchClause:["Scopable"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Scopable","Class","Statement","Declaration"],ClassExpression:["Scopable","Class","Expression"],ForOfStatement:["Scopable","Statement","For","Loop"],ForInStatement:["Scopable","Statement","For","Loop"],ForStatement:["Scopable","Statement","For","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scopable"],ConditionalExpression:["Expression"],DoExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],MetaProperty:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],Super:["Expression"],UpdateExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"],AnyTypeAnnotation:["Flow"],ArrayTypeAnnotation:["Flow"],BooleanTypeAnnotation:["Flow"],ClassImplements:["Flow"],DeclareClass:["Flow"],DeclareFunction:["Flow"],DeclareModule:["Flow"],DeclareVariable:["Flow"],FunctionTypeAnnotation:["Flow"],FunctionTypeParam:["Flow"],GenericTypeAnnotation:["Flow"],InterfaceExtends:["Flow"],InterfaceDeclaration:["Flow"],IntersectionTypeAnnotation:["Flow"],NullableTypeAnnotation:["Flow"],NumberTypeAnnotation:["Flow"],StringLiteralTypeAnnotation:["Flow"],StringTypeAnnotation:["Flow"],TupleTypeAnnotation:["Flow"],TypeofTypeAnnotation:["Flow"],TypeAlias:["Flow"],TypeAnnotation:["Flow"],TypeCastExpression:["Flow"],TypeParameterDeclaration:["Flow"],TypeParameterInstantiation:["Flow"],ObjectTypeAnnotation:["Flow"],ObjectTypeCallProperty:["Flow","UserWhitespacable"],ObjectTypeIndexer:["Flow","UserWhitespacable"],ObjectTypeProperty:["Flow","UserWhitespacable"],QualifiedTypeIdentifier:["Flow"],UnionTypeAnnotation:["Flow"],VoidTypeAnnotation:["Flow"],JSXAttribute:["JSX","Immutable"],JSXClosingElement:["JSX","Immutable"],JSXElement:["JSX","Immutable","Expression"],JSXEmptyExpression:["JSX","Immutable"],JSXExpressionContainer:["JSX","Immutable"],JSXIdentifier:["JSX"],JSXMemberExpression:["JSX"],JSXNamespacedName:["JSX"],JSXOpeningElement:["JSX","Immutable"],JSXSpreadAttribute:["JSX"]}},{}],151:[function(e,t){t.exports={ArrayExpression:{elements:null},ArrowFunctionExpression:{params:null,body:null},AssignmentExpression:{operator:null,left:null,right:null},BinaryExpression:{operator:null,left:null,right:null},BlockStatement:{body:null},CallExpression:{callee:null,arguments:null},ConditionalExpression:{test:null,consequent:null,alternate:null},ExpressionStatement:{expression:null},File:{program:null,comments:null,tokens:null},FunctionExpression:{id:null,params:null,body:null,generator:!1,async:!1},FunctionDeclaration:{id:null,params:null,body:null,generator:!1},GenericTypeAnnotation:{id:null,typeParameters:null},Identifier:{name:null},IfStatement:{test:null,consequent:null,alternate:null},ImportDeclaration:{specifiers:null,source:null},ImportSpecifier:{local:null,imported:null},LabeledStatement:{label:null,body:null},Literal:{value:null},LogicalExpression:{operator:null,left:null,right:null},MemberExpression:{object:null,property:null,computed:!1},MethodDefinition:{key:null,value:null,kind:"method",computed:!1,"static":!1},NewExpression:{callee:null,arguments:null},ObjectExpression:{properties:null},Program:{body:null},Property:{kind:null,key:null,value:null,computed:!1},ReturnStatement:{argument:null},SequenceExpression:{expressions:null},TemplateLiteral:{quasis:null,expressions:null},ThrowExpression:{argument:null},UnaryExpression:{operator:null,argument:null,prefix:null},VariableDeclaration:{kind:null,declarations:null},VariableDeclarator:{id:null,init:null},WithStatement:{object:null,body:null},YieldExpression:{argument:null,delegate:null}}},{}],152:[function(e,t,n){"use strict";function r(e){var t=void 0===arguments[1]?e.key||e.property:arguments[1];return function(){return e.computed||v.isIdentifier(t)&&(t=v.literal(t.name)),t}()}function l(e,t){function n(e){for(var t=!1,i=[],s=0;s<e.length;s++){var a=e[s];if(v.isExpression(a))i.push(a);else if(v.isExpressionStatement(a))i.push(a.expression);else{if(v.isVariableDeclaration(a)){if("var"!==a.kind)return l=!0;b(a.declarations,function(e){var t=v.getBindingIdentifiers(e);for(var n in t)r.push({kind:a.kind,id:t[n]});e.init&&i.push(v.assignmentExpression("=",e.id,e.init))}),t=!0;continue}if(v.isIfStatement(a)){var o=a.consequent?n([a.consequent]):v.identifier("undefined"),u=a.alternate?n([a.alternate]):v.identifier("undefined");if(!o||!u)return l=!0;i.push(v.conditionalExpression(a.test,o,u))}else{if(!v.isBlockStatement(a))return l=!0;i.push(n(a.body))}}t=!1}return t&&i.push(v.identifier("undefined")),1===i.length?i[0]:v.sequenceExpression(i)}var r=[],l=!1,i=n(e);if(!l){for(var s=0;s<r.length;s++)t.push(r[s]);return i}}function i(e){var t=void 0===arguments[1]?e.key:arguments[1];return function(){var n;return n=v.isIdentifier(t)?t.name:JSON.stringify(v.isLiteral(t)?t.value:y.removeProperties(v.cloneDeep(t))),e.computed&&(n="["+n+"]"),n}()}function s(e){return v.isIdentifier(e)?e.name:(e+="",e=e.replace(/[^a-zA-Z0-9$_]/g,"-"),e=e.replace(/^[-0-9]+/,""),e=e.replace(/[-\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""}),v.isValidIdentifier(e)||(e="_"+e),e||"_")}function a(e,t){if(v.isStatement(e))return e;var n,r=!1;if(v.isClass(e))r=!0,n="ClassDeclaration";else if(v.isFunction(e))r=!0,n="FunctionDeclaration";else if(v.isAssignmentExpression(e))return v.expressionStatement(e);if(r&&!e.id&&(n=!1),!n){if(t)return!1;throw new Error("cannot turn "+e.type+" to a statement")}return e.type=n,e}function o(e){if(v.isExpressionStatement(e)&&(e=e.expression),v.isClass(e)?e.type="ClassExpression":v.isFunction(e)&&(e.type="FunctionExpression"),v.isExpression(e))return e;throw new Error("cannot turn "+e.type+" to an expression")}function u(e,t){return v.isBlockStatement(e)?e:(v.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(v.isStatement(e)||(e=v.isFunction(t)?v.returnStatement(e):v.expressionStatement(e)),e=[e]),v.blockStatement(e))}function p(e){if(void 0===e)return v.identifier("undefined");if(e===!0||e===!1||null===e||g(e)||h(e)||m(e))return v.literal(e);if(Array.isArray(e))return v.arrayExpression(e.map(v.valueToNode));if(f(e)){var t=[];for(var n in e){var r;r=v.isValidIdentifier(n)?v.identifier(n):v.literal(n),t.push(v.property("init",r,v.valueToNode(e[n])))}return v.objectExpression(t)}throw new Error("don't know how to turn this value into a node")}var c=function(e){return e&&e.__esModule?e:{"default":e}},d=function(e){return e&&e.__esModule?e["default"]:e};n.toComputedKey=r,n.toSequenceExpression=l,n.toKeyAlias=i,n.toIdentifier=s,n.toStatement=a,n.toExpression=o,n.toBlock=u,n.valueToNode=p,n.__esModule=!0;var f=d(e("lodash/lang/isPlainObject")),h=d(e("lodash/lang/isNumber")),m=d(e("lodash/lang/isRegExp")),g=d(e("lodash/lang/isString")),y=d(e("../traversal")),b=d(e("lodash/collection/each")),v=c(e("./index"))},{"../traversal":144,"./index":153,"lodash/collection/each":316,"lodash/lang/isNumber":397,"lodash/lang/isPlainObject":399,"lodash/lang/isRegExp":400,"lodash/lang/isString":401}],153:[function(e,t,n){"use strict";function r(e,t){var n=_["is"+e]=function(n,r){return _.is(e,n,r,t)};_["assert"+e]=function(t,r){if(r||(r={}),!n(t,r))throw new Error("Expected type "+JSON.stringify(e)+" with option "+JSON.stringify(r))}}function l(e,t,n){if(!t)return!1;var r=i(t.type,e);return r?"undefined"==typeof n?!0:_.shallowEqual(t,n):!1}function i(e,t){if(e===t)return!0;var n=_.FLIPPED_ALIAS_KEYS[t];return n?n.indexOf(e)>-1:!1}function s(e,t){for(var n=Object.keys(t),r=0;r<n.length;r++){var l=n[r];if(e[l]!==t[l])return!1}return!0}function a(e,t,n){return e.object=_.memberExpression(e.object,e.property,e.computed),e.property=t,e.computed=!!n,e}function o(e,t){return e.object=_.memberExpression(t,e.object),e}function u(e){var t=void 0===arguments[1]?"body":arguments[1];return e[t]=_.toBlock(e[t],e)}function p(e){var t={};for(var n in e)"_"!==n[0]&&(t[n]=e[n]);return t}function c(e){var t={};for(var n in e)if("_"!==n[0]){var r=e[n];r&&(r.type?r=_.cloneDeep(r):Array.isArray(r)&&(r=r.map(_.cloneDeep))),t[n]=r}return t}function d(e,t){var n=e.split(".");return function(e){if(!_.isMemberExpression(e))return!1;for(var r=[e],l=0;r.length;){var i=r.shift();if(t&&l===n.length)return!0;if(_.isIdentifier(i)){if(n[l]!==i.name)return!1}else{if(!_.isLiteral(i)){if(_.isMemberExpression(i)){if(i.computed&&!_.isLiteral(i.property))return!1;r.push(i.object),r.push(i.property);continue}return!1}if(n[l]!==i.value)return!1}if(++l>n.length)return!1}return!0}}function f(e){return x(A,function(t){delete e[t]}),e}function h(e,t){return e&&t&&x(A,function(n){e[n]=E(b([].concat(e[n],t[n])))}),e}function m(e,t){return e&&t?(e._declarations=t._declarations,e._scopeInfo=t._scopeInfo,e.range=t.range,e.start=t.start,e.loc=t.loc,e.end=t.end,e.typeAnnotation=t.typeAnnotation,e.returnType=t.returnType,_.inheritsComments(e,t),e):e}var g=function(e){return e&&e.__esModule?e["default"]:e};n.is=l,n.isType=i,n.shallowEqual=s,n.appendToMemberExpression=a,n.prependToMemberExpression=o,n.ensureBlock=u,n.clone=p,n.cloneDeep=c,n.buildMatchMemberExpression=d,n.removeComments=f,n.inheritsComments=h,n.inherits=m,n.__esModule=!0;var y=g(e("to-fast-properties")),b=g(e("lodash/array/compact")),v=g(e("lodash/object/assign")),x=g(e("lodash/collection/each")),E=g(e("lodash/array/uniq")),_=n,S=["consequent","body","alternate"];n.STATEMENT_OR_BLOCK_KEYS=S;var I=["Array","Object","Number","Boolean","Date","Array","String","Promise","Set","Map","WeakMap","WeakSet","Uint16Array","ArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Uint32Array","Int32Array","Float32Array","Int16Array","Float64Array"];n.NATIVE_TYPE_NAMES=I;var w=["body","expressions"];n.FLATTENABLE_KEYS=w;var k=["left","init"];n.FOR_INIT_KEYS=k;var A=["leadingComments","trailingComments"];n.COMMENT_KEYS=A;var C=e("./visitor-keys");n.VISITOR_KEYS=C;var T=e("./builder-keys");n.BUILDER_KEYS=T;var j=e("./alias-keys");n.ALIAS_KEYS=j,_.FLIPPED_ALIAS_KEYS={},x(_.VISITOR_KEYS,function(e,t){r(t,!0)}),x(_.ALIAS_KEYS,function(e,t){x(e,function(e){var n,r,l=(n=_.FLIPPED_ALIAS_KEYS,r=e,!n[r]&&(n[r]=[]),n[r]);l.push(t)})}),x(_.FLIPPED_ALIAS_KEYS,function(e,t){_[t.toUpperCase()+"_TYPES"]=e,r(t,!1)});var M=Object.keys(_.VISITOR_KEYS).concat(Object.keys(_.FLIPPED_ALIAS_KEYS));n.TYPES=M,x(_.VISITOR_KEYS,function(e,t){if(!_.BUILDER_KEYS[t]){var n={};x(e,function(e){n[e]=null}),_.BUILDER_KEYS[t]=n}}),x(_.BUILDER_KEYS,function(e,t){_[t[0].toLowerCase()+t.slice(1)]=function(){var n={};n.start=null,n.type=t;var r=0;for(var l in e){var i=arguments[r++];void 0===i&&(i=e[l]),n[l]=i}return n}}),y(_),y(_.VISITOR_KEYS),n.__esModule=!0,v(_,e("./retrievers")),v(_,e("./validators")),v(_,e("./converters"))},{"./alias-keys":150,"./builder-keys":151,"./converters":152,"./retrievers":154,"./validators":155,"./visitor-keys":156,"lodash/array/compact":310,"lodash/array/uniq":314,"lodash/collection/each":316,"lodash/object/assign":404,"to-fast-properties":452}],154:[function(e,t,n){"use strict";function r(e){for(var t=[].concat(e),n=a();t.length;){var r=t.shift();if(r){var l=o.getBindingIdentifiers.keys[r.type];if(o.isIdentifier(r))n[r.name]=r;else if(o.isExportDeclaration(r))o.isDeclaration(e.declaration)&&t.push(e.declaration);else if(l)for(var i=0;i<l.length;i++){var s=l[i];t=t.concat(r[s]||[])}}}return n}function l(e){var t=[],n=function(e){t=t.concat(l(e))};return o.isIfStatement(e)?(n(e.consequent),n(e.alternate)):o.isFor(e)||o.isWhile(e)?n(e.body):o.isProgram(e)||o.isBlockStatement(e)?n(e.body[e.body.length-1]):o.isLoop()||e&&t.push(e),t}var i=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.getBindingIdentifiers=r,n.getLastStatements=l,n.__esModule=!0;var a=s(e("../helpers/object")),o=i(e("./index"));r.keys={UnaryExpression:["argument"],AssignmentExpression:["left"],ImportSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportDefaultSpecifier:["local"],VariableDeclarator:["id"],FunctionDeclaration:["id"],FunctionExpression:["id"],ClassDeclaration:["id"],ClassExpression:["id"],SpreadElement:["argument"],RestElement:["argument"],UpdateExpression:["argument"],SpreadProperty:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"],ComprehensionExpression:["blocks"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]}},{"../helpers/object":41,"./index":153}],155:[function(e,t,n){"use strict";function r(e,t){switch(t.type){case"MemberExpression":return t.property===e&&t.computed?!0:t.object===e?!0:!1;case"MetaProperty":return!1;case"Property":if(t.key===e)return t.computed;case"VariableDeclarator":return t.id!==e;case"ArrowFunctionExpression":case"FunctionDeclaration":case"FunctionExpression":for(var n=0;n<t.params.length;n++){var r=t.params[n];if(r===e)return!1}return t.id!==e;case"ExportSpecifier":return t.exported!==e;case"ImportSpecifier":return t.imported!==e;case"ClassDeclaration":case"ClassExpression":return t.id!==e;case"MethodDefinition":return t.key===e&&t.computed;case"LabeledStatement":return!1;case"CatchClause":return t.param!==e;case"RestElement":return!1;case"AssignmentPattern":return t.right===e;case"ObjectPattern":case"ArrayPattern":return!1;case"ImportSpecifier":return!1;case"ImportNamespaceSpecifier":return!1}return!0}function l(e,t,n){return(g.isIdentifier(e,n)||g.isJSXIdentifier(e,n))&&g.isReferenced(e,t)}function i(e){return h(e)&&m.keyword.isIdentifierName(e)&&!m.keyword.isReservedWordES6(e,!0)}function s(e){return g.isVariableDeclaration(e)&&("var"!==e.kind||e._let)}function a(e){return g.isFunctionDeclaration(e)||g.isClassDeclaration(e)||g.isLet(e)}function o(e){return g.isVariableDeclaration(e,{kind:"var"})&&!e._let}function u(e){return g.isImportDefaultSpecifier(e)||g.isExportDefaultSpecifier(e)||g.isIdentifier(e.imported||e.exported,{name:"default"})}function p(e,t){return g.isBlockStatement(e)&&g.isFunction(t,{body:e})?!1:g.isScopable(e)}function c(e){return g.isType(e.type,"Immutable")?!0:g.isLiteral(e)?e.regex?!1:!0:g.isIdentifier(e)&&"undefined"===e.name?!0:!1}var d=function(e){return e&&e.__esModule?e:{"default":e}},f=function(e){return e&&e.__esModule?e["default"]:e};n.isReferenced=r,n.isReferencedIdentifier=l,n.isValidIdentifier=i,n.isLet=s,n.isBlockScoped=a,n.isVar=o,n.isSpecifierDefault=u,n.isScope=p,n.isImmutable=c,n.__esModule=!0;var h=f(e("lodash/lang/isString")),m=f(e("esutils")),g=d(e("./index"))},{"./index":153,esutils:300,"lodash/lang/isString":401}],156:[function(e,t){t.exports={ArrayExpression:["elements"],ArrayPattern:["elements","typeAnnotation"],ArrowFunctionExpression:["params","body","returnType"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass","typeParameters","superTypeParameters","implements","decorators"],ClassExpression:["id","body","superClass","typeParameters","superTypeParameters","implements","decorators"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],Decorator:["expression"],DebuggerStatement:[],DoWhileStatement:["body","test"],DoExpression:["body"],EmptyStatement:[],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","body","returnType","typeParameters"],FunctionExpression:["id","params","body","returnType","typeParameters"],Identifier:["typeAnnotation"],IfStatement:["test","consequent","alternate"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["imported","local"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value","decorators"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties","typeAnnotation"],Program:["body"],Property:["key","value","decorators"],RestElement:["argument","typeAnnotation"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],Super:[],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],ExportAllDeclaration:["source","exported"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportDefaultSpecifier:["exported"],ExportNamespaceSpecifier:["exported"],ExportSpecifier:["local","exported"],AnyTypeAnnotation:[],ArrayTypeAnnotation:["elementType"],BooleanTypeAnnotation:[],ClassImplements:["id","typeParameters"],ClassProperty:["key","value","typeAnnotation"],DeclareClass:["id","typeParameters","extends","body"],DeclareFunction:["id"],DeclareModule:["id","body"],DeclareVariable:["id"],FunctionTypeAnnotation:["typeParameters","params","rest","returnType"],FunctionTypeParam:["name","typeAnnotation"],GenericTypeAnnotation:["id","typeParameters"],InterfaceExtends:["id","typeParameters"],InterfaceDeclaration:["id","typeParameters","extends","body"],IntersectionTypeAnnotation:["types"],NullableTypeAnnotation:["typeAnnotation"],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:["types"],TypeofTypeAnnotation:["argument"],TypeAlias:["id","typeParameters","right"],TypeAnnotation:["typeAnnotation"],TypeCastExpression:["expression","typeAnnotation"],TypeParameterDeclaration:["params"],TypeParameterInstantiation:["params"],ObjectTypeAnnotation:["properties","indexers","callProperties"],ObjectTypeCallProperty:["value"],ObjectTypeIndexer:["id","key","value"],ObjectTypeProperty:["key","value"],QualifiedTypeIdentifier:["id","qualification"],UnionTypeAnnotation:["types"],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],157:[function(e,t,n){(function(t,r){"use strict";function l(e,t){var n=t||l.EXTENSIONS,r=j.extname(e);return S(n,r)}function i(t){try{return e.resolve(t)}catch(n){return null}}function s(e){N||(N=new A,N.paths=A._nodeModulePaths(t.cwd()));try{return A._resolveFilename(e,N)}catch(n){return null}}function a(e){return e?Array.isArray(e)?e:"string"==typeof e?e.split(","):[e]:[]}function o(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e)&&(e=new RegExp(e.map(y).join("|"),"i")),w(e))return _.makeRe(e,{nocase:!0});if(k(e))return e;throw new TypeError("illegal type for regexify")}function u(e,t){if(!e)return[];if(x(e))return u([e],t);if(w(e))return u(a(e),t);if(Array.isArray(e))return t&&(e=e.map(t)),e;throw new TypeError("illegal type for arrayify")}function p(e){return"true"===e?!0:"false"===e?!1:e}function c(e,t,n){if(n.length){for(var r=0;r<n.length;r++)if(n[r].test(e))return!1;return!0}if(t.length)for(var r=0;r<t.length;r++)if(t[r].test(e))return!0;return!1}function d(e,t,r){var l=n.templates[e];if(!l)throw new ReferenceError("unknown template "+e);if(t===!0&&(r=!0,t=null),l=v(l),C(t)||I(l,F,null,t),l.body.length>1)return l.body;var i=l.body[0];return!r&&O.isExpressionStatement(i)?i.expression:i}function f(e,t){var n=T({filename:e,looseModules:!0},t).program;return n=I.removeProperties(n)}function h(){var e={},t=j.join(r,"transformation/templates");if(!L.existsSync(t))throw new ReferenceError(E.get("missingTemplatesDirectory"));return M(L.readdirSync(t),function(n){if("."!==n[0]){var r=j.basename(n,j.extname(n)),l=j.join(t,n),i=L.readFileSync(l,"utf8");e[r]=f(l,i)}}),e}var m=function(e){return e&&e.__esModule?e:{"default":e}},g=function(e){return e&&e.__esModule?e["default"]:e};n.canCompile=l,n.resolve=i,n.resolveRelative=s,n.list=a,n.regexify=o,n.arrayify=u,n.booleanify=p,n.shouldIgnore=c,n.template=d,n.parseTemplate=f,n.__esModule=!0,e("./patch");var y=g(e("lodash/string/escapeRegExp")),b=g(e("debug/node")),v=g(e("lodash/lang/cloneDeep")),x=g(e("lodash/lang/isBoolean")),E=m(e("./messages")),_=g(e("minimatch")),S=g(e("lodash/collection/contains")),I=g(e("./traversal")),w=g(e("lodash/lang/isString")),k=g(e("lodash/lang/isRegExp")),A=g(e("module")),C=g(e("lodash/lang/isEmpty")),T=g(e("./helpers/parse")),j=g(e("path")),M=g(e("lodash/collection/each")),P=g(e("lodash/object/has")),L=g(e("fs")),O=m(e("./types")),D=e("util");n.inherits=D.inherits,n.inspect=D.inspect;var R=b("babel");n.debug=R,l.EXTENSIONS=[".js",".jsx",".es6",".es"];var N,F={enter:function(e,t,n,r){O.isExpressionStatement(e)&&(e=e.expression),O.isIdentifier(e)&&P(r,e.name)&&(this.skip(),this.replaceInline(r[e.name]))}};try{n.templates=e("../../templates.json")}catch(B){if("MODULE_NOT_FOUND"!==B.code)throw B;n.templates=h()}}).call(this,e("_process"),"/lib/babel")},{"../../templates.json":455,"./helpers/parse":42,"./messages":43,"./patch":44,"./traversal":144,"./types":153,_process:183,"debug/node":293,fs:172,"lodash/collection/contains":315,"lodash/collection/each":316,"lodash/lang/cloneDeep":390,"lodash/lang/isBoolean":393,"lodash/lang/isEmpty":394,"lodash/lang/isRegExp":400,"lodash/lang/isString":401,"lodash/object/has":407,"lodash/string/escapeRegExp":412,minimatch:416,module:172,path:182,util:199}],158:[function(e){var t=e("../lib/types"),n=t.Type,r=n.def,l=n.or,i=t.builtInTypes,s=i.string,a=i.number,o=i.boolean,u=i.RegExp,p=e("../lib/shared"),c=p.defaults,d=p.geq;r("Printable").field("loc",l(r("SourceLocation"),null),c["null"],!0),r("Node").bases("Printable").field("type",s).field("comments",l([r("Comment")],null),c["null"],!0),r("SourceLocation").build("start","end","source").field("start",r("Position")).field("end",r("Position")).field("source",l(s,null),c["null"]),r("Position").build("line","column").field("line",d(1)).field("column",d(0)),r("Program").bases("Node").build("body").field("body",[r("Statement")]),r("Function").bases("Node").field("id",l(r("Identifier"),null),c["null"]).field("params",[r("Pattern")]).field("body",r("BlockStatement")),r("Statement").bases("Node"),r("EmptyStatement").bases("Statement").build(),r("BlockStatement").bases("Statement").build("body").field("body",[r("Statement")]),r("ExpressionStatement").bases("Statement").build("expression").field("expression",r("Expression")),r("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",r("Expression")).field("consequent",r("Statement")).field("alternate",l(r("Statement"),null),c["null"]),r("LabeledStatement").bases("Statement").build("label","body").field("label",r("Identifier")).field("body",r("Statement")),r("BreakStatement").bases("Statement").build("label").field("label",l(r("Identifier"),null),c["null"]),r("ContinueStatement").bases("Statement").build("label").field("label",l(r("Identifier"),null),c["null"]),r("WithStatement").bases("Statement").build("object","body").field("object",r("Expression")).field("body",r("Statement")),r("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",r("Expression")).field("cases",[r("SwitchCase")]).field("lexical",o,c["false"]),r("ReturnStatement").bases("Statement").build("argument").field("argument",l(r("Expression"),null)),r("ThrowStatement").bases("Statement").build("argument").field("argument",r("Expression")),r("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",r("BlockStatement")).field("handler",l(r("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[r("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[r("CatchClause")],c.emptyArray).field("finalizer",l(r("BlockStatement"),null),c["null"]),r("CatchClause").bases("Node").build("param","guard","body").field("param",r("Pattern")).field("guard",l(r("Expression"),null),c["null"]).field("body",r("BlockStatement")),r("WhileStatement").bases("Statement").build("test","body").field("test",r("Expression")).field("body",r("Statement")),r("DoWhileStatement").bases("Statement").build("body","test").field("body",r("Statement")).field("test",r("Expression")),r("ForStatement").bases("Statement").build("init","test","update","body").field("init",l(r("VariableDeclaration"),r("Expression"),null)).field("test",l(r("Expression"),null)).field("update",l(r("Expression"),null)).field("body",r("Statement")),r("ForInStatement").bases("Statement").build("left","right","body","each").field("left",l(r("VariableDeclaration"),r("Expression"))).field("right",r("Expression")).field("body",r("Statement")).field("each",o),r("DebuggerStatement").bases("Statement").build(),r("Declaration").bases("Statement"),r("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",r("Identifier")),r("FunctionExpression").bases("Function","Expression").build("id","params","body"),r("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",l("var","let","const")).field("declarations",[l(r("VariableDeclarator"),r("Identifier"))]),r("VariableDeclarator").bases("Node").build("id","init").field("id",r("Pattern")).field("init",l(r("Expression"),null)),r("Expression").bases("Node","Pattern"),r("ThisExpression").bases("Expression").build(),r("ArrayExpression").bases("Expression").build("elements").field("elements",[l(r("Expression"),null)]),r("ObjectExpression").bases("Expression").build("properties").field("properties",[r("Property")]),r("Property").bases("Node").build("kind","key","value").field("kind",l("init","get","set")).field("key",l(r("Literal"),r("Identifier"))).field("value",l(r("Expression"),r("Pattern"))),r("SequenceExpression").bases("Expression").build("expressions").field("expressions",[r("Expression")]);
var f=l("-","+","!","~","typeof","void","delete");r("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",f).field("argument",r("Expression")).field("prefix",o,c["true"]);var h=l("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");r("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",r("Expression")).field("right",r("Expression"));var m=l("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");r("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",m).field("left",r("Pattern")).field("right",r("Expression"));var g=l("++","--");r("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",g).field("argument",r("Expression")).field("prefix",o);var y=l("||","&&");r("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",y).field("left",r("Expression")).field("right",r("Expression")),r("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",r("Expression")).field("consequent",r("Expression")).field("alternate",r("Expression")),r("NewExpression").bases("Expression").build("callee","arguments").field("callee",r("Expression")).field("arguments",[r("Expression")]),r("CallExpression").bases("Expression").build("callee","arguments").field("callee",r("Expression")).field("arguments",[r("Expression")]),r("MemberExpression").bases("Expression").build("object","property","computed").field("object",r("Expression")).field("property",l(r("Identifier"),r("Expression"))).field("computed",o,c["false"]),r("Pattern").bases("Node"),r("ObjectPattern").bases("Pattern").build("properties").field("properties",[l(r("PropertyPattern"),r("Property"))]),r("PropertyPattern").bases("Pattern").build("key","pattern").field("key",l(r("Literal"),r("Identifier"))).field("pattern",r("Pattern")),r("ArrayPattern").bases("Pattern").build("elements").field("elements",[l(r("Pattern"),null)]),r("SwitchCase").bases("Node").build("test","consequent").field("test",l(r("Expression"),null)).field("consequent",[r("Statement")]),r("Identifier").bases("Node","Expression","Pattern").build("name").field("name",s),r("Literal").bases("Node","Expression").build("value").field("value",l(s,o,null,a,u)),r("Comment").bases("Printable").field("value",s).field("leading",o,c["true"]).field("trailing",o,c["false"]),r("Block").bases("Comment").build("value","leading","trailing"),r("Line").bases("Comment").build("value","leading","trailing")},{"../lib/shared":169,"../lib/types":170}],159:[function(e){e("./core");var t=e("../lib/types"),n=t.Type.def,r=t.Type.or,l=t.builtInTypes,i=l.string,s=l.boolean;n("XMLDefaultDeclaration").bases("Declaration").field("namespace",n("Expression")),n("XMLAnyName").bases("Expression"),n("XMLQualifiedIdentifier").bases("Expression").field("left",r(n("Identifier"),n("XMLAnyName"))).field("right",r(n("Identifier"),n("Expression"))).field("computed",s),n("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",r(n("Identifier"),n("Expression"))).field("computed",s),n("XMLAttributeSelector").bases("Expression").field("attribute",n("Expression")),n("XMLFilterExpression").bases("Expression").field("left",n("Expression")).field("right",n("Expression")),n("XMLElement").bases("XML","Expression").field("contents",[n("XML")]),n("XMLList").bases("XML","Expression").field("contents",[n("XML")]),n("XML").bases("Node"),n("XMLEscape").bases("XML").field("expression",n("Expression")),n("XMLText").bases("XML").field("text",i),n("XMLStartTag").bases("XML").field("contents",[n("XML")]),n("XMLEndTag").bases("XML").field("contents",[n("XML")]),n("XMLPointTag").bases("XML").field("contents",[n("XML")]),n("XMLName").bases("XML").field("contents",r(i,[n("XML")])),n("XMLAttribute").bases("XML").field("value",i),n("XMLCdata").bases("XML").field("contents",i),n("XMLComment").bases("XML").field("contents",i),n("XMLProcessingInstruction").bases("XML").field("target",i).field("contents",r(i,null))},{"../lib/types":170,"./core":158}],160:[function(e){e("./core");var t=e("../lib/types"),n=t.Type.def,r=t.Type.or,l=t.builtInTypes,i=l.boolean,s=(l.object,l.string),a=e("../lib/shared").defaults;n("Function").field("generator",i,a["false"]).field("expression",i,a["false"]).field("defaults",[r(n("Expression"),null)],a.emptyArray).field("rest",r(n("Identifier"),null),a["null"]),n("FunctionDeclaration").build("id","params","body","generator","expression"),n("FunctionExpression").build("id","params","body","generator","expression"),n("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,a["null"]).field("body",r(n("BlockStatement"),n("Expression"))).field("generator",!1,a["false"]),n("YieldExpression").bases("Expression").build("argument","delegate").field("argument",r(n("Expression"),null)).field("delegate",i,a["false"]),n("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",r(n("Expression"),null)),n("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",r(n("Expression"),null)),n("ComprehensionBlock").bases("Node").build("left","right","each").field("left",n("Pattern")).field("right",n("Expression")).field("each",i),n("ModuleSpecifier").bases("Literal").build("value").field("value",s),n("Property").field("key",r(n("Literal"),n("Identifier"),n("Expression"))).field("method",i,a["false"]).field("shorthand",i,a["false"]).field("computed",i,a["false"]),n("PropertyPattern").field("key",r(n("Literal"),n("Identifier"),n("Expression"))).field("computed",i,a["false"]),n("MethodDefinition").bases("Declaration").build("kind","key","value","static").field("kind",r("init","get","set","")).field("key",r(n("Literal"),n("Identifier"),n("Expression"))).field("value",n("Function")).field("computed",i,a["false"]).field("static",i,a["false"]),n("SpreadElement").bases("Node").build("argument").field("argument",n("Expression")),n("ArrayExpression").field("elements",[r(n("Expression"),n("SpreadElement"),null)]),n("NewExpression").field("arguments",[r(n("Expression"),n("SpreadElement"))]),n("CallExpression").field("arguments",[r(n("Expression"),n("SpreadElement"))]),n("SpreadElementPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("ArrayPattern").field("elements",[r(n("Pattern"),null,n("SpreadElement"))]);var o=r(n("MethodDefinition"),n("VariableDeclarator"),n("ClassPropertyDefinition"),n("ClassProperty"));n("ClassProperty").bases("Declaration").build("key").field("key",r(n("Literal"),n("Identifier"),n("Expression"))).field("computed",i,a["false"]),n("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",o),n("ClassBody").bases("Declaration").build("body").field("body",[o]),n("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",r(n("Identifier"),null)).field("body",n("ClassBody")).field("superClass",r(n("Expression"),null),a["null"]),n("ClassExpression").bases("Expression").build("id","body","superClass").field("id",r(n("Identifier"),null),a["null"]).field("body",n("ClassBody")).field("superClass",r(n("Expression"),null),a["null"]).field("implements",[n("ClassImplements")],a.emptyArray),n("ClassImplements").bases("Node").build("id").field("id",n("Identifier")).field("superClass",r(n("Expression"),null),a["null"]),n("Specifier").bases("Node"),n("NamedSpecifier").bases("Specifier").field("id",n("Identifier")).field("name",r(n("Identifier"),null),a["null"]),n("ExportSpecifier").bases("NamedSpecifier").build("id","name"),n("ExportBatchSpecifier").bases("Specifier").build(),n("ImportSpecifier").bases("NamedSpecifier").build("id","name"),n("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",n("Identifier")),n("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",n("Identifier")),n("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",i).field("declaration",r(n("Declaration"),n("Expression"),null)).field("specifiers",[r(n("ExportSpecifier"),n("ExportBatchSpecifier"))],a.emptyArray).field("source",r(n("ModuleSpecifier"),null),a["null"]),n("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[r(n("ImportSpecifier"),n("ImportNamespaceSpecifier"),n("ImportDefaultSpecifier"))],a.emptyArray).field("source",n("ModuleSpecifier")),n("TaggedTemplateExpression").bases("Expression").field("tag",n("Expression")).field("quasi",n("TemplateLiteral")),n("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[n("TemplateElement")]).field("expressions",[n("Expression")]),n("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:s,raw:s}).field("tail",i)},{"../lib/shared":169,"../lib/types":170,"./core":158}],161:[function(e){e("./core");var t=e("../lib/types"),n=t.Type.def,r=t.Type.or,l=t.builtInTypes,i=l.boolean,s=e("../lib/shared").defaults;n("Function").field("async",i,s["false"]),n("SpreadProperty").bases("Node").build("argument").field("argument",n("Expression")),n("ObjectExpression").field("properties",[r(n("Property"),n("SpreadProperty"))]),n("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("ObjectPattern").field("properties",[r(n("PropertyPattern"),n("SpreadPropertyPattern"),n("Property"),n("SpreadProperty"))]),n("AwaitExpression").bases("Expression").build("argument","all").field("argument",r(n("Expression"),null)).field("all",i,s["false"])},{"../lib/shared":169,"../lib/types":170,"./core":158}],162:[function(e){e("./core");var t=e("../lib/types"),n=t.Type.def,r=t.Type.or,l=t.builtInTypes,i=l.string,s=l.boolean,a=e("../lib/shared").defaults;n("JSXAttribute").bases("Node").build("name","value").field("name",r(n("JSXIdentifier"),n("JSXNamespacedName"))).field("value",r(n("Literal"),n("JSXExpressionContainer"),null),a["null"]),n("JSXIdentifier").bases("Identifier").build("name").field("name",i),n("JSXNamespacedName").bases("Node").build("namespace","name").field("namespace",n("JSXIdentifier")).field("name",n("JSXIdentifier")),n("JSXMemberExpression").bases("MemberExpression").build("object","property").field("object",r(n("JSXIdentifier"),n("JSXMemberExpression"))).field("property",n("JSXIdentifier")).field("computed",s,a.false);var o=r(n("JSXIdentifier"),n("JSXNamespacedName"),n("JSXMemberExpression"));n("JSXSpreadAttribute").bases("Node").build("argument").field("argument",n("Expression"));var u=[r(n("JSXAttribute"),n("JSXSpreadAttribute"))];n("JSXExpressionContainer").bases("Expression").build("expression").field("expression",n("Expression")),n("JSXElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",n("JSXOpeningElement")).field("closingElement",r(n("JSXClosingElement"),null),a["null"]).field("children",[r(n("JSXElement"),n("JSXExpressionContainer"),n("JSXText"),n("Literal"))],a.emptyArray).field("name",o,function(){return this.openingElement.name}).field("selfClosing",s,function(){return this.openingElement.selfClosing}).field("attributes",u,function(){return this.openingElement.attributes}),n("JSXOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",o).field("attributes",u,a.emptyArray).field("selfClosing",s,a["false"]),n("JSXClosingElement").bases("Node").build("name").field("name",o),n("JSXText").bases("Literal").build("value").field("value",i),n("JSXEmptyExpression").bases("Expression").build(),n("Type").bases("Node"),n("AnyTypeAnnotation").bases("Type"),n("VoidTypeAnnotation").bases("Type"),n("NumberTypeAnnotation").bases("Type"),n("StringTypeAnnotation").bases("Type"),n("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",i).field("raw",i),n("BooleanTypeAnnotation").bases("Type"),n("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",n("Type")),n("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",n("Type")),n("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[n("FunctionTypeParam")]).field("returnType",n("Type")).field("rest",r(n("FunctionTypeParam"),null)).field("typeParameters",r(n("TypeParameterDeclaration"),null)),n("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",n("Identifier")).field("typeAnnotation",n("Type")).field("optional",s),n("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",n("Type")),n("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[n("ObjectTypeProperty")]).field("indexers",[n("ObjectTypeIndexer")],a.emptyArray).field("callProperties",[n("ObjectTypeCallProperty")],a.emptyArray),n("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",r(n("Literal"),n("Identifier"))).field("value",n("Type")).field("optional",s),n("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",n("Identifier")).field("key",n("Type")).field("value",n("Type")),n("ObjectTypeCallProperty").bases("Node").build("value").field("value",n("FunctionTypeAnnotation")).field("static",s,!1),n("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",r(n("Identifier"),n("QualifiedTypeIdentifier"))).field("id",n("Identifier")),n("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",r(n("Identifier"),n("QualifiedTypeIdentifier"))).field("typeParameters",r(n("TypeParameterInstantiation"),null)),n("MemberTypeAnnotation").bases("Type").build("object","property").field("object",n("Identifier")).field("property",r(n("MemberTypeAnnotation"),n("GenericTypeAnnotation"))),n("UnionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",n("Type")),n("Identifier").field("typeAnnotation",r(n("TypeAnnotation"),null),a["null"]),n("TypeParameterDeclaration").bases("Node").build("params").field("params",[n("Identifier")]),n("TypeParameterInstantiation").bases("Node").build("params").field("params",[n("Type")]),n("Function").field("returnType",r(n("TypeAnnotation"),null),a["null"]).field("typeParameters",r(n("TypeParameterDeclaration"),null),a["null"]),n("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",n("TypeAnnotation")).field("static",s,!1),n("ClassImplements").field("typeParameters",r(n("TypeParameterInstantiation"),null),a["null"]),n("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",n("Identifier")).field("typeParameters",r(n("TypeParameterDeclaration"),null),a["null"]).field("body",n("ObjectTypeAnnotation")).field("extends",[n("InterfaceExtends")]),n("InterfaceExtends").bases("Node").build("id").field("id",n("Identifier")).field("typeParameters",r(n("TypeParameterInstantiation"),null)),n("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",n("Identifier")).field("typeParameters",r(n("TypeParameterDeclaration"),null)).field("right",n("Type")),n("TypeCastExpression").bases("Expression").build("expression","typeAnnotation").field("expression",n("Expression")).field("typeAnnotation",n("TypeAnnotation")),n("TupleTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("DeclareVariable").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareFunction").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareClass").bases("InterfaceDeclaration").build("id"),n("DeclareModule").bases("Statement").build("id","body").field("id",r(n("Identifier"),n("Literal"))).field("body",n("BlockStatement"))},{"../lib/shared":169,"../lib/types":170,"./core":158}],163:[function(e){e("./core");var t=e("../lib/types"),n=t.Type.def,r=t.Type.or,l=e("../lib/shared").geq;n("Function").field("body",r(n("BlockStatement"),n("Expression"))),n("ForOfStatement").bases("Statement").build("left","right","body").field("left",r(n("VariableDeclaration"),n("Expression"))).field("right",n("Expression")).field("body",n("Statement")),n("LetStatement").bases("Statement").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Statement")),n("LetExpression").bases("Expression").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Expression")),n("GraphExpression").bases("Expression").build("index","expression").field("index",l(0)).field("expression",n("Literal")),n("GraphIndexExpression").bases("Expression").build("index").field("index",l(0))},{"../lib/shared":169,"../lib/types":170,"./core":158}],164:[function(e,t){function n(e,t,n){return c.check(n)?n.length=0:n=null,l(e,t,n)}function r(e){return/[_$a-z][_$a-z0-9]*/i.test(e)?"."+e:"["+JSON.stringify(e)+"]"}function l(e,t,n){return e===t?!0:c.check(e)?i(e,t,n):d.check(e)?s(e,t,n):f.check(e)?f.check(t)&&+e===+t:h.check(e)?h.check(t)&&e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.ignoreCase===t.ignoreCase:e==t}function i(e,t,n){c.assert(e);var r=e.length;if(!c.check(t)||t.length!==r)return n&&n.push("length"),!1;for(var i=0;r>i;++i){if(n&&n.push(i),i in e!=i in t)return!1;if(!l(e[i],t[i],n))return!1;n&&a.strictEqual(n.pop(),i)}return!0}function s(e,t,n){if(d.assert(e),!d.check(t))return!1;if(e.type!==t.type)return n&&n.push("type"),!1;var r=u(e),i=r.length,s=u(t),o=s.length;if(i===o){for(var c=0;i>c;++c){var f=r[c],h=p(e,f),g=p(t,f);if(n&&n.push(f),!l(h,g,n))return!1;n&&a.strictEqual(n.pop(),f)}return!0}if(!n)return!1;var y=Object.create(null);for(c=0;i>c;++c)y[r[c]]=!0;for(c=0;o>c;++c){if(f=s[c],!m.call(y,f))return n.push(f),!1;delete y[f]}for(f in y){n.push(f);break}return!1}var a=e("assert"),o=e("../main"),u=o.getFieldNames,p=o.getFieldValue,c=o.builtInTypes.array,d=o.builtInTypes.object,f=o.builtInTypes.Date,h=o.builtInTypes.RegExp,m=Object.prototype.hasOwnProperty;n.assert=function(e,t){var l=[];n(e,t,l)||(0===l.length?a.strictEqual(e,t):a.ok(!1,"Nodes differ in the following path: "+l.map(r).join("")))},t.exports=n},{"../main":171,assert:173}],165:[function(e,t){function n(e,t,r){o.ok(this instanceof n),h.call(this,e,t,r)}function r(e){return p.BinaryExpression.check(e)||p.LogicalExpression.check(e)}function l(e){return p.CallExpression.check(e)?!0:f.check(e)?e.some(l):p.Node.check(e)?u.someField(e,function(e,t){return l(t)}):!1}function i(e){for(var t,n;e.parent;e=e.parent){if(t=e.node,n=e.parent.node,p.BlockStatement.check(n)&&"body"===e.parent.name&&0===e.name)return o.strictEqual(n.body[0],t),!0;if(p.ExpressionStatement.check(n)&&"expression"===e.name)return o.strictEqual(n.expression,t),!0;if(p.SequenceExpression.check(n)&&"expressions"===e.parent.name&&0===e.name)o.strictEqual(n.expressions[0],t);else if(p.CallExpression.check(n)&&"callee"===e.name)o.strictEqual(n.callee,t);else if(p.MemberExpression.check(n)&&"object"===e.name)o.strictEqual(n.object,t);else if(p.ConditionalExpression.check(n)&&"test"===e.name)o.strictEqual(n.test,t);else if(r(n)&&"left"===e.name)o.strictEqual(n.left,t);else{if(!p.UnaryExpression.check(n)||n.prefix||"argument"!==e.name)return!1;o.strictEqual(n.argument,t)}}return!0}function s(e){if(p.VariableDeclaration.check(e.node)){var t=e.get("declarations").value;if(!t||0===t.length)return e.prune()}else if(p.ExpressionStatement.check(e.node)){if(!e.get("expression").value)return e.prune()}else p.IfStatement.check(e.node)&&a(e);return e}function a(e){var t=e.get("test").value,n=e.get("alternate").value,r=e.get("consequent").value;if(r||n){if(!r&&n){var l=c.unaryExpression("!",t,!0);p.UnaryExpression.check(t)&&"!"===t.operator&&(l=t.argument),e.get("test").replace(l),e.get("consequent").replace(n),e.get("alternate").replace()}}else{var i=c.expressionStatement(t);e.replace(i)}}var o=e("assert"),u=e("./types"),p=u.namedTypes,c=u.builders,d=u.builtInTypes.number,f=u.builtInTypes.array,h=e("./path"),m=e("./scope");e("util").inherits(n,h);var g=n.prototype;Object.defineProperties(g,{node:{get:function(){return Object.defineProperty(this,"node",{configurable:!0,value:this._computeNode()}),this.node}},parent:{get:function(){return Object.defineProperty(this,"parent",{configurable:!0,value:this._computeParent()}),this.parent}},scope:{get:function(){return Object.defineProperty(this,"scope",{configurable:!0,value:this._computeScope()}),this.scope}}}),g.replace=function(){return delete this.node,delete this.parent,delete this.scope,h.prototype.replace.apply(this,arguments)},g.prune=function(){var e=this.parent;return this.replace(),s(e)},g._computeNode=function(){var e=this.value;if(p.Node.check(e))return e;var t=this.parentPath;return t&&t.node||null},g._computeParent=function(){var e=this.value,t=this.parentPath;if(!p.Node.check(e)){for(;t&&!p.Node.check(t.value);)t=t.parentPath;t&&(t=t.parentPath)}for(;t&&!p.Node.check(t.value);)t=t.parentPath;return t||null},g._computeScope=function(){var e=this.value,t=this.parentPath,n=t&&t.scope;return p.Node.check(e)&&m.isEstablishedBy(e)&&(n=new m(this,n)),n||null},g.getValueProperty=function(e){return u.getFieldValue(this.value,e)},g.needsParens=function(e){var t=this.parentPath;if(!t)return!1;var n=this.value;if(!p.Expression.check(n))return!1;if("Identifier"===n.type)return!1;for(;!p.Node.check(t.value);)if(t=t.parentPath,!t)return!1;var r=t.value;switch(n.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return"MemberExpression"===r.type&&"object"===this.name&&r.object===n;case"BinaryExpression":case"LogicalExpression":switch(r.type){case"CallExpression":return"callee"===this.name&&r.callee===n;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return!0;case"MemberExpression":return"object"===this.name&&r.object===n;case"BinaryExpression":case"LogicalExpression":var i=r.operator,t=y[i],s=n.operator,a=y[s];if(t>a)return!0;if(t===a&&"right"===this.name)return o.strictEqual(r.right,n),!0;default:return!1}case"SequenceExpression":switch(r.type){case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==this.name;default:return!0}case"YieldExpression":switch(r.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return!0;default:return!1}case"Literal":return"MemberExpression"===r.type&&d.check(n.value)&&"object"===this.name&&r.object===n;case"AssignmentExpression":case"ConditionalExpression":switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===this.name&&r.callee===n;case"ConditionalExpression":return"test"===this.name&&r.test===n;case"MemberExpression":return"object"===this.name&&r.object===n;default:return!1}default:if("NewExpression"===r.type&&"callee"===this.name&&r.callee===n)return l(n)}return e!==!0&&!this.canBeFirstInStatement()&&this.firstInStatement()?!0:!1};var y={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){y[e]=t})}),g.canBeFirstInStatement=function(){var e=this.node;return!p.FunctionExpression.check(e)&&!p.ObjectExpression.check(e)},g.firstInStatement=function(){return i(this)},t.exports=n},{"./path":167,"./scope":168,"./types":170,assert:173,util:199}],166:[function(e,t){function n(){o.ok(this instanceof n),this._reusableContextStack=[],this._methodNameTable=r(this),this._shouldVisitComments=m.call(this._methodNameTable,"Block")||m.call(this._methodNameTable,"Line"),this.Context=s(this),this._visiting=!1,this._changeReported=!1}function r(e){var t=Object.create(null);for(var n in e)/^visit[A-Z]/.test(n)&&(t[n.slice("visit".length)]=!0);for(var r=u.computeSupertypeLookupTable(t),l=Object.create(null),t=Object.keys(r),i=t.length,s=0;i>s;++s){var a=t[s];n="visit"+r[a],h.check(e[n])&&(l[a]=n)}return l}function l(e,t){for(var n in t)m.call(t,n)&&(e[n]=t[n]);return e}function i(e,t){o.ok(e instanceof p),o.ok(t instanceof n);var r=e.value;if(d.check(r))e.each(t.visitWithoutReset,t);else if(f.check(r)){var l=u.getFieldNames(r);t._shouldVisitComments&&r.comments&&l.indexOf("comments")<0&&l.push("comments");for(var i=l.length,s=[],a=0;i>a;++a){var c=l[a];m.call(r,c)||(r[c]=u.getFieldValue(r,c)),s.push(e.get(c))}for(var a=0;i>a;++a)t.visitWithoutReset(s[a])}else;return e.value}function s(e){function t(r){o.ok(this instanceof t),o.ok(this instanceof n),o.ok(r instanceof p),Object.defineProperty(this,"visitor",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.currentPath=r,this.needToCallTraverse=!0,Object.seal(this)}o.ok(e instanceof n);var r=t.prototype=Object.create(e);return r.constructor=t,l(r,b),t}var a,o=e("assert"),u=e("./types"),p=e("./node-path"),c=u.namedTypes.Printable,d=u.builtInTypes.array,f=u.builtInTypes.object,h=u.builtInTypes.function,m=Object.prototype.hasOwnProperty;n.fromMethodsObject=function(e){function t(){o.ok(this instanceof t),n.call(this)}if(e instanceof n)return e;if(!f.check(e))return new n;var r=t.prototype=Object.create(g);return r.constructor=t,l(r,e),l(t,n),h.assert(t.fromMethodsObject),h.assert(t.visit),new t},n.visit=function(e,t){return n.fromMethodsObject(t).visit(e)};var g=n.prototype,y=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");g.visit=function(){o.ok(!this._visiting,y),this._visiting=!0,this._changeReported=!1,this._abortRequested=!1;for(var e=arguments.length,t=new Array(e),n=0;e>n;++n)t[n]=arguments[n];t[0]instanceof p||(t[0]=new p({root:t[0]}).get("root")),this.reset.apply(this,t);try{var r=this.visitWithoutReset(t[0]),l=!0}finally{if(this._visiting=!1,!l&&this._abortRequested)return t[0].value}return r},g.AbortRequest=function(){},g.abort=function(){var e=this;e._abortRequested=!0;var t=new e.AbortRequest;throw t.cancel=function(){e._abortRequested=!1},t},g.reset=function(){},g.visitWithoutReset=function(e){if(this instanceof this.Context)return this.visitor.visitWithoutReset(e);o.ok(e instanceof p);var t=e.value,n=c.check(t)&&this._methodNameTable[t.type];if(!n)return i(e,this);var r=this.acquireContext(e);try{return r.invokeVisitorMethod(n)}finally{this.releaseContext(r)}},g.acquireContext=function(e){return 0===this._reusableContextStack.length?new this.Context(e):this._reusableContextStack.pop().reset(e)},g.releaseContext=function(e){o.ok(e instanceof this.Context),this._reusableContextStack.push(e),e.currentPath=null},g.reportChanged=function(){this._changeReported=!0},g.wasChangeReported=function(){return this._changeReported};var b=Object.create(null);b.reset=function(e){return o.ok(this instanceof this.Context),o.ok(e instanceof p),this.currentPath=e,this.needToCallTraverse=!0,this},b.invokeVisitorMethod=function(e){o.ok(this instanceof this.Context),o.ok(this.currentPath instanceof p);var t=this.visitor[e].call(this,this.currentPath);t===!1?this.needToCallTraverse=!1:t!==a&&(this.currentPath=this.currentPath.replace(t)[0],this.needToCallTraverse&&this.traverse(this.currentPath)),o.strictEqual(this.needToCallTraverse,!1,"Must either call this.traverse or return false in "+e);var n=this.currentPath;return n&&n.value},b.traverse=function(e,t){return o.ok(this instanceof this.Context),o.ok(e instanceof p),o.ok(this.currentPath instanceof p),this.needToCallTraverse=!1,i(e,n.fromMethodsObject(t||this.visitor))},b.visit=function(e,t){return o.ok(this instanceof this.Context),o.ok(e instanceof p),o.ok(this.currentPath instanceof p),this.needToCallTraverse=!1,n.fromMethodsObject(t||this.visitor).visitWithoutReset(e)},b.reportChanged=function(){this.visitor.reportChanged()},b.abort=function(){this.needToCallTraverse=!1,this.visitor.abort()},t.exports=n},{"./node-path":165,"./types":170,assert:173}],167:[function(e,t){function n(e,t,r){o.ok(this instanceof n),t?o.ok(t instanceof n):(t=null,r=null),this.value=e,this.parentPath=t,this.name=r,this.__childCache=null}function r(e){return e.__childCache||(e.__childCache=Object.create(null))}function l(e,t){var n=r(e),l=e.getValueProperty(t),i=n[t];return p.call(n,t)&&i.value===l||(i=n[t]=new e.constructor(l,e,t)),i}function i(){}function s(e,t,n,l){if(d.assert(e.value),0===t)return i;var s=e.value.length;if(1>s)return i;var a=arguments.length;2===a?(n=0,l=s):3===a?(n=Math.max(n,0),l=s):(n=Math.max(n,0),l=Math.min(l,s)),f.assert(n),f.assert(l);for(var u=Object.create(null),c=r(e),h=n;l>h;++h)if(p.call(e.value,h)){var m=e.get(h);o.strictEqual(m.name,h);var g=h+t;m.name=g,u[g]=m,delete c[h]}return delete c.length,function(){for(var t in u){var n=u[t];o.strictEqual(n.name,+t),c[t]=n,e.value[t]=n.value}}}function a(e){o.ok(e instanceof n);var t=e.parentPath;if(!t)return e;var l=t.value,i=r(t);if(l[e.name]===e.value)i[e.name]=e;else if(d.check(l)){var s=l.indexOf(e.value);s>=0&&(i[e.name=s]=e)}else l[e.name]=e.value,i[e.name]=e;return o.strictEqual(l[e.name],e.value),o.strictEqual(e.parentPath.get(e.name),e),e}var o=e("assert"),u=Object.prototype,p=u.hasOwnProperty,c=e("./types"),d=c.builtInTypes.array,f=c.builtInTypes.number,h=Array.prototype,m=(h.slice,h.map,n.prototype);m.getValueProperty=function(e){return this.value[e]},m.get=function(){for(var e=this,t=arguments,n=t.length,r=0;n>r;++r)e=l(e,t[r]);return e},m.each=function(e,t){for(var n=[],r=this.value.length,l=0,l=0;r>l;++l)p.call(this.value,l)&&(n[l]=this.get(l));for(t=t||this,l=0;r>l;++l)p.call(n,l)&&e.call(t,n[l])},m.map=function(e,t){var n=[];return this.each(function(t){n.push(e.call(this,t))},t),n},m.filter=function(e,t){var n=[];return this.each(function(t){e.call(this,t)&&n.push(t)},t),n},m.shift=function(){var e=s(this,-1),t=this.value.shift();return e(),t},m.unshift=function(){var e=s(this,arguments.length),t=this.value.unshift.apply(this.value,arguments);return e(),t},m.push=function(){return d.assert(this.value),delete r(this).length,this.value.push.apply(this.value,arguments)},m.pop=function(){d.assert(this.value);var e=r(this);return delete e[this.value.length-1],delete e.length,this.value.pop()},m.insertAt=function(e){var t=arguments.length,n=s(this,t-1,e);if(n===i)return this;e=Math.max(e,0);for(var r=1;t>r;++r)this.value[e+r-1]=arguments[r];return n(),this},m.insertBefore=function(){for(var e=this.parentPath,t=arguments.length,n=[this.name],r=0;t>r;++r)n.push(arguments[r]);return e.insertAt.apply(e,n)},m.insertAfter=function(){for(var e=this.parentPath,t=arguments.length,n=[this.name+1],r=0;t>r;++r)n.push(arguments[r]);return e.insertAt.apply(e,n)},m.replace=function(e){var t=[],n=this.parentPath.value,l=r(this.parentPath),i=arguments.length;if(a(this),d.check(n)){for(var u=n.length,p=s(this.parentPath,i-1,this.name+1),c=[this.name,1],f=0;i>f;++f)c.push(arguments[f]);var h=n.splice.apply(n,c);if(o.strictEqual(h[0],this.value),o.strictEqual(n.length,u-1+i),p(),0===i)delete this.value,delete l[this.name],this.__childCache=null;else{for(o.strictEqual(n[this.name],e),this.value!==e&&(this.value=e,this.__childCache=null),f=0;i>f;++f)t.push(this.parentPath.get(this.name+f));o.strictEqual(t[0],this)}}else 1===i?(this.value!==e&&(this.__childCache=null),this.value=n[this.name]=e,t.push(this)):0===i?(delete n[this.name],delete this.value,this.__childCache=null):o.ok(!1,"Could not replace path");return t},t.exports=n},{"./types":170,assert:173}],168:[function(e,t){function n(t,r){a.ok(this instanceof n),a.ok(t instanceof e("./node-path")),y.assert(t.value);var l;r?(a.ok(r instanceof n),l=r.depth+1):(r=null,l=0),Object.defineProperties(this,{path:{value:t},node:{value:t.value},isGlobal:{value:!r,enumerable:!0},depth:{value:l},parent:{value:r},bindings:{value:{}}})
}function r(e,t){var n=e.value;y.assert(n),p.CatchClause.check(n)?s(e.get("param"),t):l(e,t)}function l(e,t){var n=e.value;e.parent&&p.FunctionExpression.check(e.parent.node)&&e.parent.node.id&&s(e.parent.get("id"),t),n&&(f.check(n)?e.each(function(e){i(e,t)}):p.Function.check(n)?(e.get("params").each(function(e){s(e,t)}),i(e.get("body"),t)):p.VariableDeclarator.check(n)?(s(e.get("id"),t),i(e.get("init"),t)):"ImportSpecifier"===n.type||"ImportNamespaceSpecifier"===n.type||"ImportDefaultSpecifier"===n.type?s(e.get(n.name?"name":"id"),t):c.check(n)&&!d.check(n)&&o.eachField(n,function(n,r){var l=e.get(n);a.strictEqual(l.value,r),i(l,t)}))}function i(e,t){var n=e.value;if(!n||d.check(n));else if(p.FunctionDeclaration.check(n))s(e.get("id"),t);else if(p.ClassDeclaration&&p.ClassDeclaration.check(n))s(e.get("id"),t);else if(y.check(n)){if(p.CatchClause.check(n)){var r=n.param.name,i=h.call(t,r);l(e.get("body"),t),i||delete t[r]}}else l(e,t)}function s(e,t){var n=e.value;p.Pattern.assert(n),p.Identifier.check(n)?h.call(t,n.name)?t[n.name].push(e):t[n.name]=[e]:p.ObjectPattern&&p.ObjectPattern.check(n)?e.get("properties").each(function(e){var n=e.value;p.Pattern.check(n)?s(e,t):p.Property.check(n)?s(e.get("value"),t):p.SpreadProperty&&p.SpreadProperty.check(n)&&s(e.get("argument"),t)}):p.ArrayPattern&&p.ArrayPattern.check(n)?e.get("elements").each(function(e){var n=e.value;p.Pattern.check(n)?s(e,t):p.SpreadElement&&p.SpreadElement.check(n)&&s(e.get("argument"),t)}):p.PropertyPattern&&p.PropertyPattern.check(n)?s(e.get("pattern"),t):(p.SpreadElementPattern&&p.SpreadElementPattern.check(n)||p.SpreadPropertyPattern&&p.SpreadPropertyPattern.check(n))&&s(e.get("argument"),t)}var a=e("assert"),o=e("./types"),u=o.Type,p=o.namedTypes,c=p.Node,d=p.Expression,f=o.builtInTypes.array,h=Object.prototype.hasOwnProperty,m=o.builders,g=[p.Program,p.Function,p.CatchClause],y=u.or.apply(u,g);n.isEstablishedBy=function(e){return y.check(e)};var b=n.prototype;b.didScan=!1,b.declares=function(e){return this.scan(),h.call(this.bindings,e)},b.declareTemporary=function(e){e?a.ok(/^[a-z$_]/i.test(e),e):e="t$",e+=this.depth.toString(36)+"$",this.scan();for(var t=0;this.declares(e+t);)++t;var n=e+t;return this.bindings[n]=o.builders.identifier(n)},b.injectTemporary=function(e,t){e||(e=this.declareTemporary());var n=this.path.get("body");return p.BlockStatement.check(n.value)&&(n=n.get("body")),n.unshift(m.variableDeclaration("var",[m.variableDeclarator(e,t||null)])),e},b.scan=function(e){if(e||!this.didScan){for(var t in this.bindings)delete this.bindings[t];r(this.path,this.bindings),this.didScan=!0}},b.getBindings=function(){return this.scan(),this.bindings},b.lookup=function(e){for(var t=this;t&&!t.declares(e);t=t.parent);return t},b.getGlobalScope=function(){for(var e=this;!e.isGlobal;)e=e.parent;return e},t.exports=n},{"./node-path":165,"./types":170,assert:173}],169:[function(e,t,n){var r=e("../lib/types"),l=r.Type,i=r.builtInTypes,s=i.number;n.geq=function(e){return new l(function(t){return s.check(t)&&t>=e},s+" >= "+e)},n.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return!1},"true":function(){return!0},undefined:function(){}};var a=l.or(i.string,i.number,i.boolean,i.null,i.undefined);n.isPrimitive=new l(function(e){if(null===e)return!0;var t=typeof e;return!("object"===t||"function"===t)},a.toString())},{"../lib/types":170}],170:[function(e,t,n){function r(e,t){var n=this;h.ok(n instanceof r,n),h.strictEqual(v.call(e),x,e+" is not a function");var l=v.call(t);h.ok(l===x||l===E,t+" is neither a function nor a string"),Object.defineProperties(n,{name:{value:t},check:{value:function(t,r){var l=e.call(n,t,r);return!l&&r&&v.call(r)===x&&r(n,t),l}}})}function l(e){return C.check(e)?"{"+Object.keys(e).map(function(t){return t+": "+e[t]}).join(", ")+"}":A.check(e)?"["+e.map(l).join(", ")+"]":JSON.stringify(e)}function i(e,t){var n=v.call(e);return Object.defineProperty(I,t,{enumerable:!0,value:new r(function(e){return v.call(e)===n},t)}),I[t]}function s(e,t){return e instanceof r?e:e instanceof o?e.type:A.check(e)?r.fromArray(e):C.check(e)?r.fromObject(e):k.check(e)?new r(e,t):new r(function(t){return t===e},j.check(t)?function(){return e+""}:t)}function a(e,t,n,r){var l=this;h.ok(l instanceof a),w.assert(e),t=s(t);var i={name:{value:e},type:{value:t},hidden:{value:!!r}};k.check(n)&&(i.defaultFn={value:n}),Object.defineProperties(l,i)}function o(e){var t=this;h.ok(t instanceof o),Object.defineProperties(t,{typeName:{value:e},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new r(function(e,n){return t.check(e,n)},e)}})}function u(e){return e.replace(/^[A-Z]+/,function(e){var t=e.length;switch(t){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,t-1).toLowerCase()+e.charAt(t-1)}})}function p(e){var t=o.fromValue(e);return t?t.fieldNames.slice(0):("type"in e&&h.ok(!1,"did not recognize object of type "+JSON.stringify(e.type)),Object.keys(e))}function c(e,t){var n=o.fromValue(e);if(n){var r=n.allFields[t];if(r)return r.getValue(e)}return e[t]}function d(e,t){t.length=0,t.push(e);for(var n=Object.create(null),r=0;r<t.length;++r){e=t[r];var l=P[e];h.strictEqual(l.finalized,!0),_.call(n,e)&&delete t[n[e]],n[e]=r,t.push.apply(t,l.baseNames)}for(var i=0,s=i,a=t.length;a>s;++s)_.call(t,s)&&(t[i++]=t[s]);t.length=i}function f(e,t){return Object.keys(t).forEach(function(n){e[n]=t[n]}),e}var h=e("assert"),m=Array.prototype,g=m.slice,y=(m.map,m.forEach),b=Object.prototype,v=b.toString,x=v.call(function(){}),E=v.call(""),_=b.hasOwnProperty,S=r.prototype;n.Type=r,S.assert=function(e,t){if(!this.check(e,t)){var n=l(e);return h.ok(!1,n+" does not match type "+this),!1}return!0},S.toString=function(){var e=this.name;return w.check(e)?e:k.check(e)?e.call(this)+"":e+" type"};var I={};n.builtInTypes=I;var w=i("","string"),k=i(function(){},"function"),A=i([],"array"),C=i({},"object"),T=(i(/./,"RegExp"),i(new Date,"Date"),i(3,"number")),j=(i(!0,"boolean"),i(null,"null"),i(void 0,"undefined"));r.or=function(){for(var e=[],t=arguments.length,n=0;t>n;++n)e.push(s(arguments[n]));return new r(function(n,r){for(var l=0;t>l;++l)if(e[l].check(n,r))return!0;return!1},function(){return e.join(" | ")})},r.fromArray=function(e){return h.ok(A.check(e)),h.strictEqual(e.length,1,"only one element type is permitted for typed arrays"),s(e[0]).arrayOf()},S.arrayOf=function(){var e=this;return new r(function(t,n){return A.check(t)&&t.every(function(t){return e.check(t,n)})},function(){return"["+e+"]"})},r.fromObject=function(e){var t=Object.keys(e).map(function(t){return new a(t,e[t])});return new r(function(e,n){return C.check(e)&&t.every(function(t){return t.type.check(e[t.name],n)})},function(){return"{ "+t.join(", ")+" }"})};var M=a.prototype;M.toString=function(){return JSON.stringify(this.name)+": "+this.type},M.getValue=function(e){var t=e[this.name];return j.check(t)?(this.defaultFn&&(t=this.defaultFn.call(e)),t):t},r.def=function(e){return w.assert(e),_.call(P,e)?P[e]:P[e]=new o(e)};var P=Object.create(null);o.fromValue=function(e){if(e&&"object"==typeof e){var t=e.type;if("string"==typeof t&&_.call(P,t)){var n=P[t];if(n.finalized)return n}}return null};var L=o.prototype;L.isSupertypeOf=function(e){return e instanceof o?(h.strictEqual(this.finalized,!0),h.strictEqual(e.finalized,!0),_.call(e.allSupertypes,this.typeName)):void h.ok(!1,e+" is not a Def")},n.getSupertypeNames=function(e){h.ok(_.call(P,e));var t=P[e];return h.strictEqual(t.finalized,!0),t.supertypeList.slice(1)},n.computeSupertypeLookupTable=function(e){for(var t={},n=Object.keys(P),r=n.length,l=0;r>l;++l){var i=n[l],s=P[i];h.strictEqual(s.finalized,!0);for(var a=0;a<s.supertypeList.length;++a){var o=s.supertypeList[a];if(_.call(e,o)){t[i]=o;break}}}return t},L.checkAllFields=function(e,t){function n(n){var l=r[n],i=l.type,s=l.getValue(e);return i.check(s,t)}var r=this.allFields;return h.strictEqual(this.finalized,!0),C.check(e)&&Object.keys(r).every(n)},L.check=function(e,t){if(h.strictEqual(this.finalized,!0,"prematurely checking unfinalized type "+this.typeName),!C.check(e))return!1;var n=o.fromValue(e);return n?t&&n===this?this.checkAllFields(e,t):this.isSupertypeOf(n)?t?n.checkAllFields(e,t)&&this.checkAllFields(e,!1):!0:!1:"SourceLocation"===this.typeName||"Position"===this.typeName?this.checkAllFields(e,t):!1},L.bases=function(){var e=this.baseNames;return h.strictEqual(this.finalized,!1),y.call(arguments,function(t){w.assert(t),e.indexOf(t)<0&&e.push(t)}),this},Object.defineProperty(L,"buildable",{value:!1});var O={};n.builders=O;var D={};n.defineMethod=function(e,t){var n=D[e];return j.check(t)?delete D[e]:(k.assert(t),Object.defineProperty(D,e,{enumerable:!0,configurable:!0,value:t})),n},L.build=function(){var e=this;return Object.defineProperty(e,"buildParams",{value:g.call(arguments),writable:!1,enumerable:!1,configurable:!0}),h.strictEqual(e.finalized,!1),w.arrayOf().assert(e.buildParams),e.buildable?e:(e.field("type",e.typeName,function(){return e.typeName}),Object.defineProperty(e,"buildable",{value:!0}),Object.defineProperty(O,u(e.typeName),{enumerable:!0,value:function(){function t(t,s){if(!_.call(i,t)){var a=e.allFields;h.ok(_.call(a,t),t);var o,u=a[t],p=u.type;if(T.check(s)&&r>s)o=n[s];else if(u.defaultFn)o=u.defaultFn.call(i);else{var c="no value or default function given for field "+JSON.stringify(t)+" of "+e.typeName+"("+e.buildParams.map(function(e){return a[e]}).join(", ")+")";h.ok(!1,c)}p.check(o)||h.ok(!1,l(o)+" does not match field "+u+" of type "+e.typeName),i[t]=o}}var n=arguments,r=n.length,i=Object.create(D);return h.ok(e.finalized,"attempting to instantiate unfinalized type "+e.typeName),e.buildParams.forEach(function(e,n){t(e,n)}),Object.keys(e.allFields).forEach(function(e){t(e)}),h.strictEqual(i.type,e.typeName),i}}),e)},L.field=function(e,t,n,r){return h.strictEqual(this.finalized,!1),this.ownFields[e]=new a(e,t,n,r),this};var R={};n.namedTypes=R,n.getFieldNames=p,n.getFieldValue=c,n.eachField=function(e,t,n){p(e).forEach(function(n){t.call(this,n,c(e,n))},n)},n.someField=function(e,t,n){return p(e).some(function(n){return t.call(this,n,c(e,n))},n)},Object.defineProperty(L,"finalized",{value:!1}),L.finalize=function(){if(!this.finalized){var e=this.allFields,t=this.allSupertypes;this.baseNames.forEach(function(n){var r=P[n];r.finalize(),f(e,r.allFields),f(t,r.allSupertypes)}),f(e,this.ownFields),t[this.typeName]=this,this.fieldNames.length=0;for(var n in e)_.call(e,n)&&!e[n].hidden&&this.fieldNames.push(n);Object.defineProperty(R,this.typeName,{enumerable:!0,value:this.type}),Object.defineProperty(this,"finalized",{value:!0}),d(this.typeName,this.supertypeList)}},n.finalize=function(){Object.keys(P).forEach(function(e){P[e].finalize()})}},{assert:173}],171:[function(e,t,n){var r=e("./lib/types");e("./def/core"),e("./def/es6"),e("./def/es7"),e("./def/mozilla"),e("./def/e4x"),e("./def/fb-harmony"),r.finalize(),n.Type=r.Type,n.builtInTypes=r.builtInTypes,n.namedTypes=r.namedTypes,n.builders=r.builders,n.defineMethod=r.defineMethod,n.getFieldNames=r.getFieldNames,n.getFieldValue=r.getFieldValue,n.eachField=r.eachField,n.someField=r.someField,n.getSupertypeNames=r.getSupertypeNames,n.astNodesAreEquivalent=e("./lib/equiv"),n.finalize=r.finalize,n.NodePath=e("./lib/node-path"),n.PathVisitor=e("./lib/path-visitor"),n.visit=n.PathVisitor.visit},{"./def/core":158,"./def/e4x":159,"./def/es6":160,"./def/es7":161,"./def/fb-harmony":162,"./def/mozilla":163,"./lib/equiv":164,"./lib/node-path":165,"./lib/path-visitor":166,"./lib/types":170}],172:[function(){},{}],173:[function(e,t){function n(e,t){return d.isUndefined(t)?""+t:d.isNumber(t)&&!isFinite(t)?t.toString():d.isFunction(t)||d.isRegExp(t)?t.toString():t}function r(e,t){return d.isString(e)?e.length<t?e:e.slice(0,t):e}function l(e){return r(JSON.stringify(e.actual,n),128)+" "+e.operator+" "+r(JSON.stringify(e.expected,n),128)}function i(e,t,n,r,l){throw new m.AssertionError({message:n,actual:e,expected:t,operator:r,stackStartFunction:l})}function s(e,t){e||i(e,!0,t,"==",m.ok)}function a(e,t){if(e===t)return!0;if(d.isBuffer(e)&&d.isBuffer(t)){if(e.length!=t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}return d.isDate(e)&&d.isDate(t)?e.getTime()===t.getTime():d.isRegExp(e)&&d.isRegExp(t)?e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.lastIndex===t.lastIndex&&e.ignoreCase===t.ignoreCase:d.isObject(e)||d.isObject(t)?u(e,t):e==t}function o(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function u(e,t){if(d.isNullOrUndefined(e)||d.isNullOrUndefined(t))return!1;if(e.prototype!==t.prototype)return!1;if(d.isPrimitive(e)||d.isPrimitive(t))return e===t;var n=o(e),r=o(t);if(n&&!r||!n&&r)return!1;if(n)return e=f.call(e),t=f.call(t),a(e,t);var l,i,s=g(e),u=g(t);if(s.length!=u.length)return!1;for(s.sort(),u.sort(),i=s.length-1;i>=0;i--)if(s[i]!=u[i])return!1;for(i=s.length-1;i>=0;i--)if(l=s[i],!a(e[l],t[l]))return!1;return!0}function p(e,t){return e&&t?"[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t?!0:t.call({},e)===!0?!0:!1:!1}function c(e,t,n,r){var l;d.isString(n)&&(r=n,n=null);try{t()}catch(s){l=s}if(r=(n&&n.name?" ("+n.name+").":".")+(r?" "+r:"."),e&&!l&&i(l,n,"Missing expected exception"+r),!e&&p(l,n)&&i(l,n,"Got unwanted exception"+r),e&&l&&n&&!p(l,n)||!e&&l)throw l}var d=e("util/"),f=Array.prototype.slice,h=Object.prototype.hasOwnProperty,m=t.exports=s;m.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=l(this),this.generatedMessage=!0);var t=e.stackStartFunction||i;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var n=new Error;if(n.stack){var r=n.stack,s=t.name,a=r.indexOf("\n"+s);if(a>=0){var o=r.indexOf("\n",a+1);r=r.substring(o+1)}this.stack=r}}},d.inherits(m.AssertionError,Error),m.fail=i,m.ok=s,m.equal=function(e,t,n){e!=t&&i(e,t,n,"==",m.equal)},m.notEqual=function(e,t,n){e==t&&i(e,t,n,"!=",m.notEqual)},m.deepEqual=function(e,t,n){a(e,t)||i(e,t,n,"deepEqual",m.deepEqual)},m.notDeepEqual=function(e,t,n){a(e,t)&&i(e,t,n,"notDeepEqual",m.notDeepEqual)},m.strictEqual=function(e,t,n){e!==t&&i(e,t,n,"===",m.strictEqual)},m.notStrictEqual=function(e,t,n){e===t&&i(e,t,n,"!==",m.notStrictEqual)},m.throws=function(){c.apply(this,[!0].concat(f.call(arguments)))},m.doesNotThrow=function(){c.apply(this,[!1].concat(f.call(arguments)))},m.ifError=function(e){if(e)throw e};var g=Object.keys||function(e){var t=[];for(var n in e)h.call(e,n)&&t.push(n);return t}},{"util/":199}],174:[function(e,t,n){arguments[4][172][0].apply(n,arguments)},{dup:172}],175:[function(e,t,n){function r(e,t){var n=this;if(!(n instanceof r))return new r(e,t);var l,i=typeof e;if("number"===i)l=+e;else if("string"===i)l=r.byteLength(e,t);else{if("object"!==i||null===e)throw new TypeError("must start with number, buffer, array or string");"Buffer"===e.type&&R(e.data)&&(e=e.data),l=+e.length}if(l>N)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+N.toString(16)+" bytes");0>l?l=0:l>>>=0,r.TYPED_ARRAY_SUPPORT?n=r._augment(new Uint8Array(l)):(n.length=l,n._isBuffer=!0);var s;if(r.TYPED_ARRAY_SUPPORT&&"number"==typeof e.byteLength)n._set(e);else if(k(e))if(r.isBuffer(e))for(s=0;l>s;s++)n[s]=e.readUInt8(s);else for(s=0;l>s;s++)n[s]=(e[s]%256+256)%256;else if("string"===i)n.write(e,0,t);else if("number"===i&&!r.TYPED_ARRAY_SUPPORT)for(s=0;l>s;s++)n[s]=0;return l>0&&l<=r.poolSize&&(n.parent=F),n}function l(e,t){if(!(this instanceof l))return new l(e,t);var n=new r(e,t);return delete n.parent,n}function i(e,t,n,r){n=Number(n)||0;var l=e.length-n;r?(r=Number(r),r>l&&(r=l)):r=l;var i=t.length;if(i%2!==0)throw new Error("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;r>s;s++){var a=parseInt(t.substr(2*s,2),16);if(isNaN(a))throw new Error("Invalid hex string");e[n+s]=a}return s}function s(e,t,n,r){var l=P(C(t,e.length-n),e,n,r);return l}function a(e,t,n,r){var l=P(T(t),e,n,r);return l}function o(e,t,n,r){return a(e,t,n,r)}function u(e,t,n,r){var l=P(M(t),e,n,r);return l}function p(e,t,n,r){var l=P(j(t,e.length-n),e,n,r);return l}function c(e,t,n){return O.fromByteArray(0===t&&n===e.length?e:e.slice(t,n))}function d(e,t,n){var r="",l="";n=Math.min(e.length,n);for(var i=t;n>i;i++)e[i]<=127?(r+=L(l)+String.fromCharCode(e[i]),l=""):l+="%"+e[i].toString(16);return r+L(l)}function f(e,t,n){var r="";n=Math.min(e.length,n);for(var l=t;n>l;l++)r+=String.fromCharCode(127&e[l]);return r}function h(e,t,n){var r="";n=Math.min(e.length,n);for(var l=t;n>l;l++)r+=String.fromCharCode(e[l]);return r}function m(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var l="",i=t;n>i;i++)l+=A(e[i]);return l}function g(e,t,n){for(var r=e.slice(t,n),l="",i=0;i<r.length;i+=2)l+=String.fromCharCode(r[i]+256*r[i+1]);return l}function y(e,t,n){if(e%1!==0||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function b(e,t,n,l,i,s){if(!r.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||s>t)throw new RangeError("value is out of bounds");if(n+l>e.length)throw new RangeError("index out of range")}function v(e,t,n,r){0>t&&(t=65535+t+1);for(var l=0,i=Math.min(e.length-n,2);i>l;l++)e[n+l]=(t&255<<8*(r?l:1-l))>>>8*(r?l:1-l)}function x(e,t,n,r){0>t&&(t=4294967295+t+1);for(var l=0,i=Math.min(e.length-n,4);i>l;l++)e[n+l]=t>>>8*(r?l:3-l)&255}function E(e,t,n,r,l,i){if(t>l||i>t)throw new RangeError("value is out of bounds");if(n+r>e.length)throw new RangeError("index out of range");if(0>n)throw new RangeError("index out of range")}function _(e,t,n,r,l){return l||E(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),D.write(e,t,n,r,23,4),n+4}function S(e,t,n,r,l){return l||E(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),D.write(e,t,n,r,52,8),n+8}function I(e){if(e=w(e).replace($,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function w(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function k(e){return R(e)||r.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function A(e){return 16>e?"0"+e.toString(16):e.toString(16)}function C(e,t){t=t||1/0;for(var n,r=e.length,l=null,i=[],s=0;r>s;s++){if(n=e.charCodeAt(s),n>55295&&57344>n){if(!l){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}l=n;continue}if(56320>n){(t-=3)>-1&&i.push(239,191,189),l=n;continue}n=l-55296<<10|n-56320|65536,l=null}else l&&((t-=3)>-1&&i.push(239,191,189),l=null);if(128>n){if((t-=1)<0)break;i.push(n)}else if(2048>n){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(65536>n){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(2097152>n))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function T(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}function j(e,t){for(var n,r,l,i=[],s=0;s<e.length&&!((t-=2)<0);s++)n=e.charCodeAt(s),r=n>>8,l=n%256,i.push(l),i.push(r);return i}function M(e){return O.toByteArray(I(e))}function P(e,t,n,r){for(var l=0;r>l&&!(l+n>=t.length||l>=e.length);l++)t[l+n]=e[l];return l}function L(e){try{return decodeURIComponent(e)}catch(t){return String.fromCharCode(65533)}}var O=e("base64-js"),D=e("ieee754"),R=e("is-array");n.Buffer=r,n.SlowBuffer=l,n.INSPECT_MAX_BYTES=50,r.poolSize=8192;var N=1073741823,F={};r.TYPED_ARRAY_SUPPORT=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===new Uint8Array(1).subarray(1,1).byteLength}catch(n){return!1}}(),r.isBuffer=function(e){return!(null==e||!e._isBuffer)},r.compare=function(e,t){if(!r.isBuffer(e)||!r.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,l=t.length,i=0,s=Math.min(n,l);s>i&&e[i]===t[i];i++);return i!==s&&(n=e[i],l=t[i]),l>n?-1:n>l?1:0},r.isEncoding=function(e){switch(String(e).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!0;default:return!1}},r.concat=function(e,t){if(!R(e))throw new TypeError("list argument must be an Array of Buffers.");if(0===e.length)return new r(0);if(1===e.length)return e[0];var n;if(void 0===t)for(t=0,n=0;n<e.length;n++)t+=e[n].length;var l=new r(t),i=0;for(n=0;n<e.length;n++){var s=e[n];s.copy(l,i),i+=s.length}return l},r.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"ascii":case"binary":case"raw":n=e.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;case"hex":n=e.length>>>1;break;case"utf8":case"utf-8":n=C(e).length;break;case"base64":n=M(e).length;break;default:n=e.length}return n},r.prototype.length=void 0,r.prototype.parent=void 0,r.prototype.toString=function(e,t,n){var r=!1;if(t>>>=0,n=void 0===n||1/0===n?this.length:n>>>0,e||(e="utf8"),0>t&&(t=0),n>this.length&&(n=this.length),t>=n)return"";for(;;)switch(e){case"hex":return m(this,t,n);case"utf8":case"utf-8":return d(this,t,n);case"ascii":return f(this,t,n);case"binary":return h(this,t,n);case"base64":return c(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}},r.prototype.equals=function(e){if(!r.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:0===r.compare(this,e)},r.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),"<Buffer "+e+">"},r.prototype.compare=function(e){if(!r.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?0:r.compare(this,e)},r.prototype.indexOf=function(e,t){function n(e,t,n){for(var r=-1,l=0;n+l<e.length;l++)if(e[n+l]===t[-1===r?0:l-r]){if(-1===r&&(r=l),l-r+1===t.length)return n+r}else r=-1;return-1}if(t>2147483647?t=2147483647:-2147483648>t&&(t=-2147483648),t>>=0,0===this.length)return-1;if(t>=this.length)return-1;if(0>t&&(t=Math.max(this.length+t,0)),"string"==typeof e)return 0===e.length?-1:String.prototype.indexOf.call(this,e,t);if(r.isBuffer(e))return n(this,e,t);if("number"==typeof e)return r.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,e,t):n(this,[e],t);throw new TypeError("val must be string, number or Buffer")},r.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},r.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},r.prototype.write=function(e,t,n,r){if(isFinite(t))isFinite(n)||(r=n,n=void 0);else{var l=r;r=t,t=n,n=l}if(t=Number(t)||0,0>n||0>t||t>this.length)throw new RangeError("attempt to write outside buffer bounds");var c=this.length-t;n?(n=Number(n),n>c&&(n=c)):n=c,r=String(r||"utf8").toLowerCase();var d;switch(r){case"hex":d=i(this,e,t,n);break;case"utf8":case"utf-8":d=s(this,e,t,n);break;case"ascii":d=a(this,e,t,n);break;case"binary":d=o(this,e,t,n);break;case"base64":d=u(this,e,t,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":d=p(this,e,t,n);break;default:throw new TypeError("Unknown encoding: "+r)}return d},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},r.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,0>e?(e+=n,0>e&&(e=0)):e>n&&(e=n),0>t?(t+=n,0>t&&(t=0)):t>n&&(t=n),e>t&&(t=e);var l;if(r.TYPED_ARRAY_SUPPORT)l=r._augment(this.subarray(e,t));else{var i=t-e;l=new r(i,void 0);for(var s=0;i>s;s++)l[s]=this[s+e]}return l.length&&(l.parent=this.parent||this),l},r.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e],l=1,i=0;++i<t&&(l*=256);)r+=this[e+i]*l;return r},r.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e+--t],l=1;t>0&&(l*=256);)r+=this[e+--t]*l;return r},r.prototype.readUInt8=function(e,t){return t||y(e,1,this.length),this[e]},r.prototype.readUInt16LE=function(e,t){return t||y(e,2,this.length),this[e]|this[e+1]<<8},r.prototype.readUInt16BE=function(e,t){return t||y(e,2,this.length),this[e]<<8|this[e+1]},r.prototype.readUInt32LE=function(e,t){return t||y(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},r.prototype.readUInt32BE=function(e,t){return t||y(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},r.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=this[e],l=1,i=0;++i<t&&(l*=256);)r+=this[e+i]*l;return l*=128,r>=l&&(r-=Math.pow(2,8*t)),r},r.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||y(e,t,this.length);for(var r=t,l=1,i=this[e+--r];r>0&&(l*=256);)i+=this[e+--r]*l;return l*=128,i>=l&&(i-=Math.pow(2,8*t)),i},r.prototype.readInt8=function(e,t){return t||y(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},r.prototype.readInt16LE=function(e,t){t||y(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},r.prototype.readInt16BE=function(e,t){t||y(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},r.prototype.readInt32LE=function(e,t){return t||y(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},r.prototype.readInt32BE=function(e,t){return t||y(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},r.prototype.readFloatLE=function(e,t){return t||y(e,4,this.length),D.read(this,e,!0,23,4)},r.prototype.readFloatBE=function(e,t){return t||y(e,4,this.length),D.read(this,e,!1,23,4)},r.prototype.readDoubleLE=function(e,t){return t||y(e,8,this.length),D.read(this,e,!0,52,8)},r.prototype.readDoubleBE=function(e,t){return t||y(e,8,this.length),D.read(this,e,!1,52,8)},r.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||b(this,e,t,n,Math.pow(2,8*n),0);var l=1,i=0;for(this[t]=255&e;++i<n&&(l*=256);)this[t+i]=e/l>>>0&255;return t+n},r.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||b(this,e,t,n,Math.pow(2,8*n),0);var l=n-1,i=1;for(this[t+l]=255&e;--l>=0&&(i*=256);)this[t+l]=e/i>>>0&255;return t+n},r.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,1,255,0),r.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e,t+1},r.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):v(this,e,t,!0),t+2},r.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):v(this,e,t,!1),t+2},r.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e):x(this,e,t,!0),t+4},r.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e):x(this,e,t,!1),t+4},r.prototype.writeIntLE=function(e,t,n,r){e=+e,t>>>=0,r||b(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var l=0,i=1,s=0>e?1:0;for(this[t]=255&e;++l<n&&(i*=256);)this[t+l]=(e/i>>0)-s&255;return t+n},r.prototype.writeIntBE=function(e,t,n,r){e=+e,t>>>=0,r||b(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var l=n-1,i=1,s=0>e?1:0;for(this[t+l]=255&e;--l>=0&&(i*=256);)this[t+l]=(e/i>>0)-s&255;return t+n},r.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,1,127,-128),r.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),0>e&&(e=255+e+1),this[t]=e,t+1},r.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):v(this,e,t,!0),t+2},r.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):v(this,e,t,!1),t+2},r.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},r.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||b(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e):x(this,e,t,!1),t+4},r.prototype.writeFloatLE=function(e,t,n){return _(this,e,t,!0,n)},r.prototype.writeFloatBE=function(e,t,n){return _(this,e,t,!1,n)},r.prototype.writeDoubleLE=function(e,t,n){return S(this,e,t,!0,n)},r.prototype.writeDoubleBE=function(e,t,n){return S(this,e,t,!1,n)},r.prototype.copy=function(e,t,n,l){if(n||(n=0),l||0===l||(l=this.length),t>=e.length&&(t=e.length),t||(t=0),l>0&&n>l&&(l=n),l===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("sourceStart out of bounds");if(0>l)throw new RangeError("sourceEnd out of bounds");l>this.length&&(l=this.length),e.length-t<l-n&&(l=e.length-t+n);var i=l-n;if(1e3>i||!r.TYPED_ARRAY_SUPPORT)for(var s=0;i>s;s++)e[s+t]=this[s+n];else e._set(this.subarray(n,n+i),t);return i},r.prototype.fill=function(e,t,n){if(e||(e=0),t||(t=0),n||(n=this.length),t>n)throw new RangeError("end < start");if(n!==t&&0!==this.length){if(0>t||t>=this.length)throw new RangeError("start out of bounds");if(0>n||n>this.length)throw new RangeError("end out of bounds");var r;if("number"==typeof e)for(r=t;n>r;r++)this[r]=e;else{var l=C(e.toString()),i=l.length;for(r=t;n>r;r++)this[r]=l[r%i]}return this}},r.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(r.TYPED_ARRAY_SUPPORT)return new r(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;n>t;t+=1)e[t]=this[t];return e.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var B=r.prototype;r._augment=function(e){return e.constructor=r,e._isBuffer=!0,e._set=e.set,e.get=B.get,e.set=B.set,e.write=B.write,e.toString=B.toString,e.toLocaleString=B.toString,e.toJSON=B.toJSON,e.equals=B.equals,e.compare=B.compare,e.indexOf=B.indexOf,e.copy=B.copy,e.slice=B.slice,e.readUIntLE=B.readUIntLE,e.readUIntBE=B.readUIntBE,e.readUInt8=B.readUInt8,e.readUInt16LE=B.readUInt16LE,e.readUInt16BE=B.readUInt16BE,e.readUInt32LE=B.readUInt32LE,e.readUInt32BE=B.readUInt32BE,e.readIntLE=B.readIntLE,e.readIntBE=B.readIntBE,e.readInt8=B.readInt8,e.readInt16LE=B.readInt16LE,e.readInt16BE=B.readInt16BE,e.readInt32LE=B.readInt32LE,e.readInt32BE=B.readInt32BE,e.readFloatLE=B.readFloatLE,e.readFloatBE=B.readFloatBE,e.readDoubleLE=B.readDoubleLE,e.readDoubleBE=B.readDoubleBE,e.writeUInt8=B.writeUInt8,e.writeUIntLE=B.writeUIntLE,e.writeUIntBE=B.writeUIntBE,e.writeUInt16LE=B.writeUInt16LE,e.writeUInt16BE=B.writeUInt16BE,e.writeUInt32LE=B.writeUInt32LE,e.writeUInt32BE=B.writeUInt32BE,e.writeIntLE=B.writeIntLE,e.writeIntBE=B.writeIntBE,e.writeInt8=B.writeInt8,e.writeInt16LE=B.writeInt16LE,e.writeInt16BE=B.writeInt16BE,e.writeInt32LE=B.writeInt32LE,e.writeInt32BE=B.writeInt32BE,e.writeFloatLE=B.writeFloatLE,e.writeFloatBE=B.writeFloatBE,e.writeDoubleLE=B.writeDoubleLE,e.writeDoubleBE=B.writeDoubleBE,e.fill=B.fill,e.inspect=B.inspect,e.toArrayBuffer=B.toArrayBuffer,e};var $=/[^+\/0-9A-z\-]/g},{"base64-js":176,ieee754:177,"is-array":178}],176:[function(e,t,n){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(e){"use strict";function t(e){var t=e.charCodeAt(0);return t===s||t===c?62:t===a||t===d?63:o>t?-1:o+10>t?t-o+26+26:p+26>t?t-p:u+26>t?t-u+26:void 0}function n(e){function n(e){u[c++]=e}var r,l,s,a,o,u;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var p=e.length;
o="="===e.charAt(p-2)?2:"="===e.charAt(p-1)?1:0,u=new i(3*e.length/4-o),s=o>0?e.length-4:e.length;var c=0;for(r=0,l=0;s>r;r+=4,l+=3)a=t(e.charAt(r))<<18|t(e.charAt(r+1))<<12|t(e.charAt(r+2))<<6|t(e.charAt(r+3)),n((16711680&a)>>16),n((65280&a)>>8),n(255&a);return 2===o?(a=t(e.charAt(r))<<2|t(e.charAt(r+1))>>4,n(255&a)):1===o&&(a=t(e.charAt(r))<<10|t(e.charAt(r+1))<<4|t(e.charAt(r+2))>>2,n(a>>8&255),n(255&a)),u}function l(e){function t(e){return r.charAt(e)}function n(e){return t(e>>18&63)+t(e>>12&63)+t(e>>6&63)+t(63&e)}var l,i,s,a=e.length%3,o="";for(l=0,s=e.length-a;s>l;l+=3)i=(e[l]<<16)+(e[l+1]<<8)+e[l+2],o+=n(i);switch(a){case 1:i=e[e.length-1],o+=t(i>>2),o+=t(i<<4&63),o+="==";break;case 2:i=(e[e.length-2]<<8)+e[e.length-1],o+=t(i>>10),o+=t(i>>4&63),o+=t(i<<2&63),o+="="}return o}var i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),a="/".charCodeAt(0),o="0".charCodeAt(0),u="a".charCodeAt(0),p="A".charCodeAt(0),c="-".charCodeAt(0),d="_".charCodeAt(0);e.toByteArray=n,e.fromByteArray=l}("undefined"==typeof n?this.base64js={}:n)},{}],177:[function(e,t,n){n.read=function(e,t,n,r,l){var i,s,a=8*l-r-1,o=(1<<a)-1,u=o>>1,p=-7,c=n?l-1:0,d=n?-1:1,f=e[t+c];for(c+=d,i=f&(1<<-p)-1,f>>=-p,p+=a;p>0;i=256*i+e[t+c],c+=d,p-=8);for(s=i&(1<<-p)-1,i>>=-p,p+=r;p>0;s=256*s+e[t+c],c+=d,p-=8);if(0===i)i=1-u;else{if(i===o)return s?0/0:1/0*(f?-1:1);s+=Math.pow(2,r),i-=u}return(f?-1:1)*s*Math.pow(2,i-r)},n.write=function(e,t,n,r,l,i){var s,a,o,u=8*i-l-1,p=(1<<u)-1,c=p>>1,d=23===l?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,h=r?1:-1,m=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||1/0===t?(a=isNaN(t)?1:0,s=p):(s=Math.floor(Math.log(t)/Math.LN2),t*(o=Math.pow(2,-s))<1&&(s--,o*=2),t+=s+c>=1?d/o:d*Math.pow(2,1-c),t*o>=2&&(s++,o/=2),s+c>=p?(a=0,s=p):s+c>=1?(a=(t*o-1)*Math.pow(2,l),s+=c):(a=t*Math.pow(2,c-1)*Math.pow(2,l),s=0));l>=8;e[n+f]=255&a,f+=h,a/=256,l-=8);for(s=s<<l|a,u+=l;u>0;e[n+f]=255&s,f+=h,s/=256,u-=8);e[n+f-h]|=128*m}},{}],178:[function(e,t){var n=Array.isArray,r=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==r.call(e)}},{}],179:[function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function l(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!l(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,l,a,o,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(l=arguments.length,a=new Array(l-1),o=1;l>o;o++)a[o-1]=arguments[o];n.apply(this,a)}else if(i(n)){for(l=arguments.length,a=new Array(l-1),o=1;l>o;o++)a[o-1]=arguments[o];for(u=n.slice(),l=u.length,o=0;l>o;o++)u[o].apply(this,a)}return!0},n.prototype.addListener=function(e,t){var l;if(!r(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned){var l;l=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,l&&l>0&&this._events[e].length>l&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),l||(l=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var l=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,l,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,l=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){l=a;break}if(0>l)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(l,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0}},{}],180:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],181:[function(e,t){t.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},{}],182:[function(e,t,n){(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var l=e[r];"."===l?e.splice(r,1):".."===l?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}var l=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(e){return l.exec(e).slice(1)};n.resolve=function(){for(var n="",l=!1,i=arguments.length-1;i>=-1&&!l;i--){var s=i>=0?arguments[i]:e.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(n=s+"/"+n,l="/"===s.charAt(0))}return n=t(r(n.split("/"),function(e){return!!e}),!l).join("/"),(l?"/":"")+n||"."},n.normalize=function(e){var l=n.isAbsolute(e),i="/"===s(e,-1);return e=t(r(e.split("/"),function(e){return!!e}),!l).join("/"),e||l||(e="."),e&&i&&(e+="/"),(l?"/":"")+e},n.isAbsolute=function(e){return"/"===e.charAt(0)},n.join=function(){var e=Array.prototype.slice.call(arguments,0);return n.normalize(r(e,function(e){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},n.relative=function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var n=e.length-1;n>=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var l=r(e.split("/")),i=r(t.split("/")),s=Math.min(l.length,i.length),a=s,o=0;s>o;o++)if(l[o]!==i[o]){a=o;break}for(var u=[],o=a;o<l.length;o++)u.push("..");return u=u.concat(i.slice(a)),u.join("/")},n.sep="/",n.delimiter=":",n.dirname=function(e){var t=i(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},n.basename=function(e,t){var n=i(e)[2];return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},n.extname=function(e){return i(e)[3]};var s="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return 0>t&&(t=e.length+t),e.substr(t,n)}}).call(this,e("_process"))},{_process:183}],183:[function(e,t){function n(){if(!s){s=!0;for(var e,t=i.length;t;){e=i,i=[];for(var n=-1;++n<t;)e[n]();t=i.length}s=!1}}function r(){}var l=t.exports={},i=[],s=!1;l.nextTick=function(e){i.push(e),s||setTimeout(n,0)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=r,l.addListener=r,l.once=r,l.off=r,l.removeListener=r,l.removeAllListeners=r,l.emit=r,l.binding=function(){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},{}],184:[function(e,t){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":185}],185:[function(e,t){(function(n){function r(e){return this instanceof r?(o.call(this,e),u.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",l)):new r(e)}function l(){this.allowHalfOpen||this._writableState.ended||n.nextTick(this.end.bind(this))}function i(e,t){for(var n=0,r=e.length;r>n;n++)t(e[n],n)}t.exports=r;var s=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t},a=e("core-util-is");a.inherits=e("inherits");var o=e("./_stream_readable"),u=e("./_stream_writable");a.inherits(r,o),i(s(u.prototype),function(e){r.prototype[e]||(r.prototype[e]=u.prototype[e])})}).call(this,e("_process"))},{"./_stream_readable":187,"./_stream_writable":189,_process:183,"core-util-is":190,inherits:180}],186:[function(e,t){function n(e){return this instanceof n?void r.call(this,e):new n(e)}t.exports=n;var r=e("./_stream_transform"),l=e("core-util-is");l.inherits=e("inherits"),l.inherits(n,r),n.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":188,"core-util-is":190,inherits:180}],187:[function(e,t){(function(n){function r(t,n){var r=e("./_stream_duplex");t=t||{};var l=t.highWaterMark,i=t.objectMode?16:16384;this.highWaterMark=l||0===l?l:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!t.objectMode,n instanceof r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(C||(C=e("string_decoder/").StringDecoder),this.decoder=new C(t.encoding),this.encoding=t.encoding)}function l(t){e("./_stream_duplex");return this instanceof l?(this._readableState=new r(t,this),this.readable=!0,void k.call(this)):new l(t)}function i(e,t,n,r,l){var i=u(t,n);if(i)e.emit("error",i);else if(A.isNullOrUndefined(n))t.reading=!1,t.ended||p(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!l){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&l){var a=new Error("stream.unshift() after end event");e.emit("error",a)}else!t.decoder||l||r||(n=t.decoder.write(n)),l||(t.reading=!1),t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,l?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&c(e)),f(e,t);else l||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}function a(e){if(e>=j)e=j;else{e--;for(var t=1;32>t;t<<=1)e|=e>>t;e++}return e}function o(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:isNaN(e)||A.isNull(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:0>=e?0:(e>t.highWaterMark&&(t.highWaterMark=a(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function u(e,t){var n=null;return A.isBuffer(t)||A.isString(t)||A.isNullOrUndefined(t)||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function p(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,c(e)}function c(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(T("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?n.nextTick(function(){d(e)}):d(e))}function d(e){T("emit readable"),e.emit("readable"),b(e)}function f(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){h(e,t)}))}function h(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(T("maybeReadMore read 0"),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}function m(e){return function(){var t=e._readableState;T("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&w.listenerCount(e,"data")&&(t.flowing=!0,b(e))}}function g(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(function(){y(e,t)}))}function y(e,t){t.resumeScheduled=!1,e.emit("resume"),b(e),t.flowing&&!t.reading&&e.read(0)}function b(e){var t=e._readableState;if(T("flow",t.flowing),t.flowing)do var n=e.read();while(null!==n&&t.flowing)}function v(e,t){var n,r=t.buffer,l=t.length,i=!!t.decoder,s=!!t.objectMode;if(0===r.length)return null;if(0===l)n=null;else if(s)n=r.shift();else if(!e||e>=l)n=i?r.join(""):I.concat(r,l),r.length=0;else if(e<r[0].length){var a=r[0];n=a.slice(0,e),r[0]=a.slice(e)}else if(e===r[0].length)n=r.shift();else{n=i?"":new I(e);for(var o=0,u=0,p=r.length;p>u&&e>o;u++){var a=r[0],c=Math.min(e-o,a.length);i?n+=a.slice(0,c):a.copy(n,o,0,c),c<a.length?r[0]=a.slice(c):r.shift(),o+=c}}return n}function x(e){var t=e._readableState;if(t.length>0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function E(e,t){for(var n=0,r=e.length;r>n;n++)t(e[n],n)}function _(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1}t.exports=l;var S=e("isarray"),I=e("buffer").Buffer;l.ReadableState=r;var w=e("events").EventEmitter;w.listenerCount||(w.listenerCount=function(e,t){return e.listeners(t).length});var k=e("stream"),A=e("core-util-is");A.inherits=e("inherits");var C,T=e("util");T=T&&T.debuglog?T.debuglog("stream"):function(){},A.inherits(l,k),l.prototype.push=function(e,t){var n=this._readableState;return A.isString(e)&&!n.objectMode&&(t=t||n.defaultEncoding,t!==n.encoding&&(e=new I(e,t),t="")),i(this,n,e,t,!1)},l.prototype.unshift=function(e){var t=this._readableState;return i(this,t,e,"",!0)},l.prototype.setEncoding=function(t){return C||(C=e("string_decoder/").StringDecoder),this._readableState.decoder=new C(t),this._readableState.encoding=t,this};var j=8388608;l.prototype.read=function(e){T("read",e);var t=this._readableState,n=e;if((!A.isNumber(e)||e>0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return T("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):c(this),null;if(e=o(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;T("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&(r=!0,T("length less than watermark",r)),(t.ended||t.reading)&&(r=!1,T("reading or ended",r)),r&&(T("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),r&&!t.reading&&(e=o(n,t));var l;return l=e>0?v(e,t):null,A.isNull(l)&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&x(this),A.isNull(l)||this.emit("data",l),l},l.prototype._read=function(){this.emit("error",new Error("not implemented"))},l.prototype.pipe=function(e,t){function r(e){T("onunpipe"),e===c&&i()}function l(){T("onend"),e.end()}function i(){T("cleanup"),e.removeListener("close",o),e.removeListener("finish",u),e.removeListener("drain",g),e.removeListener("error",a),e.removeListener("unpipe",r),c.removeListener("end",l),c.removeListener("end",i),c.removeListener("data",s),!d.awaitDrain||e._writableState&&!e._writableState.needDrain||g()}function s(t){T("ondata");var n=e.write(t);!1===n&&(T("false write response, pause",c._readableState.awaitDrain),c._readableState.awaitDrain++,c.pause())}function a(t){T("onerror",t),p(),e.removeListener("error",a),0===w.listenerCount(e,"error")&&e.emit("error",t)}function o(){e.removeListener("finish",u),p()}function u(){T("onfinish"),e.removeListener("close",o),p()}function p(){T("unpipe"),c.unpipe(e)}var c=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,T("pipe count=%d opts=%j",d.pipesCount,t);var f=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,h=f?l:i;d.endEmitted?n.nextTick(h):c.once("end",h),e.on("unpipe",r);var g=m(c);return e.on("drain",g),c.on("data",s),e._events&&e._events.error?S(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",o),e.once("finish",u),e.emit("pipe",c),d.flowing||(T("pipe resume"),c.resume()),e},l.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var l=0;r>l;l++)n[l].emit("unpipe",this);return this}var l=_(t.pipes,e);return-1===l?this:(t.pipes.splice(l,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this),this)},l.prototype.on=function(e,t){var r=k.prototype.on.call(this,e,t);if("data"===e&&!1!==this._readableState.flowing&&this.resume(),"readable"===e&&this.readable){var l=this._readableState;if(!l.readableListening)if(l.readableListening=!0,l.emittedReadable=!1,l.needReadable=!0,l.reading)l.length&&c(this,l);else{var i=this;n.nextTick(function(){T("readable nexttick read 0"),i.read(0)})}}return r},l.prototype.addListener=l.prototype.on,l.prototype.resume=function(){var e=this._readableState;return e.flowing||(T("resume"),e.flowing=!0,e.reading||(T("resume read 0"),this.read(0)),g(this,e)),this},l.prototype.pause=function(){return T("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(T("pause"),this._readableState.flowing=!1,this.emit("pause")),this},l.prototype.wrap=function(e){var t=this._readableState,n=!1,r=this;e.on("end",function(){if(T("wrapped end"),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&r.push(e)}r.push(null)}),e.on("data",function(l){if(T("wrapped data"),t.decoder&&(l=t.decoder.write(l)),l&&(t.objectMode||l.length)){var i=r.push(l);i||(n=!0,e.pause())}});for(var l in e)A.isFunction(e[l])&&A.isUndefined(this[l])&&(this[l]=function(t){return function(){return e[t].apply(e,arguments)}}(l));var i=["error","close","destroy","pause","resume"];return E(i,function(t){e.on(t,r.emit.bind(r,t))}),r._read=function(t){T("wrapped _read",t),n&&(n=!1,e.resume())},r},l._fromList=v}).call(this,e("_process"))},{"./_stream_duplex":185,_process:183,buffer:175,"core-util-is":190,events:179,inherits:180,isarray:181,stream:195,"string_decoder/":196,util:174}],188:[function(e,t){function n(e,t){this.afterTransform=function(e,n){return r(t,e,n)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function r(e,t,n){var r=e._transformState;r.transforming=!1;var l=r.writecb;if(!l)return e.emit("error",new Error("no writecb in Transform class"));r.writechunk=null,r.writecb=null,a.isNullOrUndefined(n)||e.push(n),l&&l(t);var i=e._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&e._read(i.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState=new n(e,this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,this.once("prefinish",function(){a.isFunction(this._flush)?this._flush(function(e){i(t,e)}):i(t)})}function i(e,t){if(t)return e.emit("error",t);var n=e._writableState,r=e._transformState;if(n.length)throw new Error("calling transform done when ws.length != 0");if(r.transforming)throw new Error("calling transform done when still transforming");return e.push(null)}t.exports=l;var s=e("./_stream_duplex"),a=e("core-util-is");a.inherits=e("inherits"),a.inherits(l,s),l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(){throw new Error("not implemented")},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var l=this._readableState;(r.needTransform||l.needReadable||l.length<l.highWaterMark)&&this._read(l.highWaterMark)}},l.prototype._read=function(){var e=this._transformState;a.isNull(e.writechunk)||!e.writecb||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))}},{"./_stream_duplex":185,"core-util-is":190,inherits:180}],189:[function(e,t){(function(n){function r(e,t,n){this.chunk=e,this.encoding=t,this.callback=n}function l(t,n){var r=e("./_stream_duplex");t=t||{};var l=t.highWaterMark,i=t.objectMode?16:16384;this.highWaterMark=l||0===l?l:i,this.objectMode=!!t.objectMode,n instanceof r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var s=t.decodeStrings===!1;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){f(n,e)},this.writecb=null,this.writelen=0,this.buffer=[],this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1}function i(t){var n=e("./_stream_duplex");return this instanceof i||this instanceof n?(this._writableState=new l(t,this),this.writable=!0,void S.call(this)):new i(t)}function s(e,t,r){var l=new Error("write after end");e.emit("error",l),n.nextTick(function(){r(l)})}function a(e,t,r,l){var i=!0;if(!(_.isBuffer(r)||_.isString(r)||_.isNullOrUndefined(r)||t.objectMode)){var s=new TypeError("Invalid non-string/buffer chunk");e.emit("error",s),n.nextTick(function(){l(s)}),i=!1}return i}function o(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&_.isString(t)&&(t=new E(t,n)),t}function u(e,t,n,l,i){n=o(t,n,l),_.isBuffer(n)&&(l="buffer");var s=t.objectMode?1:n.length;t.length+=s;var a=t.length<t.highWaterMark;return a||(t.needDrain=!0),t.writing||t.corked?t.buffer.push(new r(n,l,i)):p(e,t,!1,s,n,l,i),a}function p(e,t,n,r,l,i,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(l,t.onwrite):e._write(l,i,t.onwrite),t.sync=!1}function c(e,t,r,l,i){r?n.nextTick(function(){t.pendingcb--,i(l)}):(t.pendingcb--,i(l)),e._writableState.errorEmitted=!0,e.emit("error",l)}function d(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function f(e,t){var r=e._writableState,l=r.sync,i=r.writecb;if(d(r),t)c(e,r,l,t,i);else{var s=y(e,r);s||r.corked||r.bufferProcessing||!r.buffer.length||g(e,r),l?n.nextTick(function(){h(e,r,s,i)}):h(e,r,s,i)}}function h(e,t,n,r){n||m(e,t),t.pendingcb--,r(),v(e,t)}function m(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function g(e,t){if(t.bufferProcessing=!0,e._writev&&t.buffer.length>1){for(var n=[],r=0;r<t.buffer.length;r++)n.push(t.buffer[r].callback);t.pendingcb++,p(e,t,!0,t.length,t.buffer,"",function(e){for(var r=0;r<n.length;r++)t.pendingcb--,n[r](e)}),t.buffer=[]}else{for(var r=0;r<t.buffer.length;r++){var l=t.buffer[r],i=l.chunk,s=l.encoding,a=l.callback,o=t.objectMode?1:i.length;if(p(e,t,!1,o,i,s,a),t.writing){r++;break}}r<t.buffer.length?t.buffer=t.buffer.slice(r):t.buffer.length=0}t.bufferProcessing=!1}function y(e,t){return t.ending&&0===t.length&&!t.finished&&!t.writing}function b(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function v(e,t){var n=y(e,t);return n&&(0===t.pendingcb?(b(e,t),t.finished=!0,e.emit("finish")):b(e,t)),n}function x(e,t,r){t.ending=!0,v(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0}t.exports=i;var E=e("buffer").Buffer;i.WritableState=l;var _=e("core-util-is");_.inherits=e("inherits");var S=e("stream");_.inherits(i,S),i.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},i.prototype.write=function(e,t,n){var r=this._writableState,l=!1;return _.isFunction(t)&&(n=t,t=null),_.isBuffer(e)?t="buffer":t||(t=r.defaultEncoding),_.isFunction(n)||(n=function(){}),r.ended?s(this,r,n):a(this,r,e,n)&&(r.pendingcb++,l=u(this,r,e,t,n)),l},i.prototype.cork=function(){var e=this._writableState;e.corked++},i.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.buffer.length||g(this,e))},i.prototype._write=function(e,t,n){n(new Error("not implemented"))},i.prototype._writev=null,i.prototype.end=function(e,t,n){var r=this._writableState;_.isFunction(e)?(n=e,e=null,t=null):_.isFunction(t)&&(n=t,t=null),_.isNullOrUndefined(e)||this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||x(this,r,n)}}).call(this,e("_process"))},{"./_stream_duplex":185,_process:183,buffer:175,"core-util-is":190,inherits:180,stream:195}],190:[function(e,t,n){(function(e){function t(e){return Array.isArray(e)}function r(e){return"boolean"==typeof e}function l(e){return null===e}function i(e){return null==e}function s(e){return"number"==typeof e}function a(e){return"string"==typeof e}function o(e){return"symbol"==typeof e}function u(e){return void 0===e}function p(e){return c(e)&&"[object RegExp]"===y(e)}function c(e){return"object"==typeof e&&null!==e}function d(e){return c(e)&&"[object Date]"===y(e)}function f(e){return c(e)&&("[object Error]"===y(e)||e instanceof Error)}function h(e){return"function"==typeof e}function m(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function g(t){return e.isBuffer(t)}function y(e){return Object.prototype.toString.call(e)}n.isArray=t,n.isBoolean=r,n.isNull=l,n.isNullOrUndefined=i,n.isNumber=s,n.isString=a,n.isSymbol=o,n.isUndefined=u,n.isRegExp=p,n.isObject=c,n.isDate=d,n.isError=f,n.isFunction=h,n.isPrimitive=m,n.isBuffer=g}).call(this,e("buffer").Buffer)},{buffer:175}],191:[function(e,t){t.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":186}],192:[function(e,t,n){n=t.exports=e("./lib/_stream_readable.js"),n.Stream=e("stream"),n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":185,"./lib/_stream_passthrough.js":186,"./lib/_stream_readable.js":187,"./lib/_stream_transform.js":188,"./lib/_stream_writable.js":189,stream:195}],193:[function(e,t){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":188}],194:[function(e,t){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":189}],195:[function(e,t){function n(){r.call(this)}t.exports=n;var r=e("events").EventEmitter,l=e("inherits");l(n,r),n.Readable=e("readable-stream/readable.js"),n.Writable=e("readable-stream/writable.js"),n.Duplex=e("readable-stream/duplex.js"),n.Transform=e("readable-stream/transform.js"),n.PassThrough=e("readable-stream/passthrough.js"),n.Stream=n,n.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&u.pause&&u.pause()}function l(){u.readable&&u.resume&&u.resume()}function i(){p||(p=!0,e.end())}function s(){p||(p=!0,"function"==typeof e.destroy&&e.destroy())}function a(e){if(o(),0===r.listenerCount(this,"error"))throw e}function o(){u.removeListener("data",n),e.removeListener("drain",l),u.removeListener("end",i),u.removeListener("close",s),u.removeListener("error",a),e.removeListener("error",a),u.removeListener("end",o),u.removeListener("close",o),e.removeListener("close",o)}var u=this;u.on("data",n),e.on("drain",l),e._isStdio||t&&t.end===!1||(u.on("end",i),u.on("close",s));var p=!1;return u.on("error",a),e.on("error",a),u.on("end",o),u.on("close",o),e.on("close",o),e.emit("pipe",u),e}},{events:179,inherits:180,"readable-stream/duplex.js":184,"readable-stream/passthrough.js":191,"readable-stream/readable.js":192,"readable-stream/transform.js":193,"readable-stream/writable.js":194}],196:[function(e,t,n){function r(e){if(e&&!o(e))throw new Error("Unknown encoding: "+e)}function l(e){return e.toString(this.encoding)}function i(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function s(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var a=e("buffer").Buffer,o=a.isEncoding||function(e){switch(e&&e.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!0;default:return!1}},u=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=i;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=s;break;default:return void(this.write=l)}this.charBuffer=new a(6),this.charReceived=0,this.charLength=0};u.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived<this.charLength)return"";e=e.slice(n,e.length),t=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var r=t.charCodeAt(t.length-1);if(!(r>=55296&&56319>=r)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var l=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,l),l-=this.charReceived),t+=e.toString(this.encoding,0,l);var l=t.length-1,r=t.charCodeAt(l);if(r>=55296&&56319>=r){var i=this.surrogateSize;return this.charLength+=i,this.charReceived+=i,this.charBuffer.copy(this.charBuffer,i,0,i),e.copy(this.charBuffer,0,0,i),t.substring(0,l)}return t},u.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(2>=t&&n>>4==14){this.charLength=3;break}if(3>=t&&n>>3==30){this.charLength=4;break}}this.charReceived=t},u.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,l=this.encoding;t+=r.slice(0,n).toString(l)}return t}},{buffer:175}],197:[function(e,t,n){function r(){throw new Error("tty.ReadStream is not implemented")}function l(){throw new Error("tty.ReadStream is not implemented")}n.isatty=function(){return!1},n.ReadStream=r,n.WriteStream=l},{}],198:[function(e,t){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],199:[function(e,t,n){(function(t,r){function l(e,t){var r={seen:[],stylize:s};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(t)?r.showHidden=t:t&&n._extend(r,t),E(r.showHidden)&&(r.showHidden=!1),E(r.depth)&&(r.depth=2),E(r.colors)&&(r.colors=!1),E(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),o(r,e,r.depth)}function i(e,t){var n=l.styles[t];return n?"["+l.colors[n][0]+"m"+e+"["+l.colors[n][1]+"m":e}function s(e){return e}function a(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function o(e,t,r){if(e.customInspect&&t&&k(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var l=t.inspect(r,e);return v(l)||(l=o(e,l,r)),l}var i=u(e,t);if(i)return i;var s=Object.keys(t),m=a(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),w(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return p(t);if(0===s.length){if(k(t)){var g=t.name?": "+t.name:"";
return e.stylize("[Function"+g+"]","special")}if(_(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(I(t))return e.stylize(Date.prototype.toString.call(t),"date");if(w(t))return p(t)}var y="",b=!1,x=["{","}"];if(h(t)&&(b=!0,x=["[","]"]),k(t)){var E=t.name?": "+t.name:"";y=" [Function"+E+"]"}if(_(t)&&(y=" "+RegExp.prototype.toString.call(t)),I(t)&&(y=" "+Date.prototype.toUTCString.call(t)),w(t)&&(y=" "+p(t)),0===s.length&&(!b||0==t.length))return x[0]+y+x[1];if(0>r)return _(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var S;return S=b?c(e,t,r,m,s):s.map(function(n){return d(e,t,r,m,n,b)}),e.seen.pop(),f(S,y,x)}function u(e,t){if(E(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function c(e,t,n,r,l){for(var i=[],s=0,a=t.length;a>s;++s)i.push(M(t,String(s))?d(e,t,n,r,String(s),!0):"");return l.forEach(function(l){l.match(/^\d+$/)||i.push(d(e,t,n,r,l,!0))}),i}function d(e,t,n,r,l,i){var s,a,u;if(u=Object.getOwnPropertyDescriptor(t,l)||{value:t[l]},u.get?a=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(a=e.stylize("[Setter]","special")),M(r,l)||(s="["+l+"]"),a||(e.seen.indexOf(u.value)<0?(a=g(n)?o(e,u.value,null):o(e,u.value,n-1),a.indexOf("\n")>-1&&(a=i?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n"))):a=e.stylize("[Circular]","special")),E(s)){if(i&&l.match(/^\d+$/))return a;s=JSON.stringify(""+l),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function f(e,t,n){var r=0,l=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return l>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function h(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function g(e){return null===e}function y(e){return null==e}function b(e){return"number"==typeof e}function v(e){return"string"==typeof e}function x(e){return"symbol"==typeof e}function E(e){return void 0===e}function _(e){return S(e)&&"[object RegExp]"===C(e)}function S(e){return"object"==typeof e&&null!==e}function I(e){return S(e)&&"[object Date]"===C(e)}function w(e){return S(e)&&("[object Error]"===C(e)||e instanceof Error)}function k(e){return"function"==typeof e}function A(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function C(e){return Object.prototype.toString.call(e)}function T(e){return 10>e?"0"+e.toString(10):e.toString(10)}function j(){var e=new Date,t=[T(e.getHours()),T(e.getMinutes()),T(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var P=/%[sdj%]/g;n.format=function(e){if(!v(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(l(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,s=String(e).replace(P,function(e){if("%%"===e)return"%";if(n>=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),a=r[n];i>n;a=r[++n])s+=g(a)||!S(a)?" "+a:" "+l(a);return s},n.deprecate=function(e,l){function i(){if(!s){if(t.throwDeprecation)throw new Error(l);t.traceDeprecation?console.trace(l):console.error(l),s=!0}return e.apply(this,arguments)}if(E(r.process))return function(){return n.deprecate(e,l).apply(this,arguments)};if(t.noDeprecation===!0)return e;var s=!1;return i};var L,O={};n.debuglog=function(e){if(E(L)&&(L=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!O[e])if(new RegExp("\\b"+e+"\\b","i").test(L)){var r=t.pid;O[e]=function(){var t=n.format.apply(n,arguments);console.error("%s %d: %s",e,r,t)}}else O[e]=function(){};return O[e]},n.inspect=l,l.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]},l.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},n.isArray=h,n.isBoolean=m,n.isNull=g,n.isNullOrUndefined=y,n.isNumber=b,n.isString=v,n.isSymbol=x,n.isUndefined=E,n.isRegExp=_,n.isObject=S,n.isDate=I,n.isError=w,n.isFunction=k,n.isPrimitive=A,n.isBuffer=e("./support/isBuffer");var D=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",j(),n.format.apply(n,arguments))},n.inherits=e("inherits"),n._extend=function(e,t){if(!t||!S(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":198,_process:183,inherits:180}],200:[function(e,t){(function(n){"use strict";function r(e){this.enabled=e&&void 0!==e.enabled?e.enabled:c}function l(e){var t=function n(){return i.apply(n,arguments)};return t._styles=e,t.enabled=this.enabled,t.__proto__=h,t}function i(){var e=arguments,t=e.length,n=0!==t&&String(arguments[0]);if(t>1)for(var r=1;t>r;r++)n+=" "+e[r];if(!this.enabled||!n)return n;for(var l=this._styles,i=l.length;i--;){var s=o[l[i]];n=s.open+n.replace(s.closeRe,s.open)+s.close}return n}function s(){var e={};return Object.keys(f).forEach(function(t){e[t]={get:function(){return l.call(this,[t])}}}),e}var a=e("escape-string-regexp"),o=e("ansi-styles"),u=e("strip-ansi"),p=e("has-ansi"),c=e("supports-color"),d=Object.defineProperties;"win32"===n.platform&&(o.blue.open="[94m");var f=function(){var e={};return Object.keys(o).forEach(function(t){o[t].closeRe=new RegExp(a(o[t].close),"g"),e[t]={get:function(){return l.call(this,this._styles.concat(t))}}}),e}(),h=d(function(){},f);d(r.prototype,s()),t.exports=new r,t.exports.styles=o,t.exports.hasColor=p,t.exports.stripColor=u,t.exports.supportsColor=c}).call(this,e("_process"))},{_process:183,"ansi-styles":201,"escape-string-regexp":202,"has-ansi":203,"strip-ansi":205,"supports-color":207}],201:[function(e,t){"use strict";var n=t.exports={modifiers:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},colors:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39]},bgColors:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]}};n.colors.grey=n.colors.gray,Object.keys(n).forEach(function(e){var t=n[e];Object.keys(t).forEach(function(e){var r=t[e];n[e]=t[e]={open:"["+r[0]+"m",close:"["+r[1]+"m"}}),Object.defineProperty(n,e,{value:t,enumerable:!1})})},{}],202:[function(e,t){"use strict";var n=/[|\\{}()[\]^$+*?.]/g;t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(n,"\\$&")}},{}],203:[function(e,t){"use strict";var n=e("ansi-regex"),r=new RegExp(n().source);t.exports=r.test.bind(r)},{"ansi-regex":204}],204:[function(e,t){"use strict";t.exports=function(){return/(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/g}},{}],205:[function(e,t){"use strict";var n=e("ansi-regex")();t.exports=function(e){return"string"==typeof e?e.replace(n,""):e}},{"ansi-regex":206}],206:[function(e,t,n){arguments[4][204][0].apply(n,arguments)},{dup:204}],207:[function(e,t){(function(e){"use strict";var n=e.argv;t.exports=function(){return"FORCE_COLOR"in e.env?!0:-1!==n.indexOf("--no-color")||-1!==n.indexOf("--no-colors")||-1!==n.indexOf("--color=false")?!1:-1!==n.indexOf("--color")||-1!==n.indexOf("--colors")||-1!==n.indexOf("--color=true")||-1!==n.indexOf("--color=always")?!0:e.stdout&&!e.stdout.isTTY?!1:"win32"===e.platform?!0:"COLORTERM"in e.env?!0:"dumb"===e.env.TERM?!1:/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(e.env.TERM)?!0:!1}()}).call(this,e("_process"))},{_process:183}],208:[function(e,t,n){(function(t){"use strict";function r(e){return new t(e,"base64").toString()}function l(e){return e.split(",").pop()}function i(e,t){var n=p.exec(e);p.lastIndex=0;var r=n[1]||n[2],l=o.join(t,r);try{return a.readFileSync(l,"utf8")}catch(i){throw new Error("An error occurred while trying to read the map file at "+l+"\n"+i)}}function s(e,t){t=t||{};try{t.isFileComment&&(e=i(e,t.commentFileDir)),t.hasComment&&(e=l(e)),t.isEncoded&&(e=r(e)),(t.isJSON||t.isEncoded)&&(e=JSON.parse(e)),this.sourcemap=e}catch(n){return console.error(n),null}}var a=e("fs"),o=e("path"),u=/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+;)?base64,(.*)$/gm,p=/(?:\/\/[@#][ \t]+sourceMappingURL=(.+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/gm;s.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},s.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")},s.prototype.toComment=function(){var e=this.toBase64();return"//# sourceMappingURL=data:application/json;base64,"+e},s.prototype.toObject=function(){return JSON.parse(this.toJSON())},s.prototype.addProperty=function(e,t){if(this.sourcemap.hasOwnProperty(e))throw new Error("property %s already exists on the sourcemap, use set property instead");return this.setProperty(e,t)},s.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},s.prototype.getProperty=function(e){return this.sourcemap[e]},n.fromObject=function(e){return new s(e)},n.fromJSON=function(e){return new s(e,{isJSON:!0})},n.fromBase64=function(e){return new s(e,{isEncoded:!0})},n.fromComment=function(e){return e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),new s(e,{isEncoded:!0,hasComment:!0})},n.fromMapFileComment=function(e,t){return new s(e,{commentFileDir:t,isFileComment:!0,isJSON:!0})},n.fromSource=function(e){var t=e.match(u);return u.lastIndex=0,t?n.fromComment(t.pop()):null},n.fromMapFileSource=function(e,t){var r=e.match(p);return p.lastIndex=0,r?n.fromMapFileComment(r.pop(),t):null},n.removeComments=function(e){return u.lastIndex=0,e.replace(u,"")},n.removeMapFileComments=function(e){return p.lastIndex=0,e.replace(p,"")},n.__defineGetter__("commentRegex",function(){return u.lastIndex=0,u}),n.__defineGetter__("mapFileCommentRegex",function(){return p.lastIndex=0,p})}).call(this,e("buffer").Buffer)},{buffer:175,fs:172,path:182}],209:[function(e,t){e("./shim"),e("./modules/core.dict"),e("./modules/core.iter-helpers"),e("./modules/core.$for"),e("./modules/core.delay"),e("./modules/core.binding"),e("./modules/core.object"),e("./modules/core.array.turn"),e("./modules/core.number.iterator"),e("./modules/core.number.math"),e("./modules/core.string.escape-html"),e("./modules/core.date"),e("./modules/core.global"),e("./modules/core.log"),t.exports=e("./modules/$").core},{"./modules/$":223,"./modules/core.$for":235,"./modules/core.array.turn":236,"./modules/core.binding":237,"./modules/core.date":238,"./modules/core.delay":239,"./modules/core.dict":240,"./modules/core.global":241,"./modules/core.iter-helpers":242,"./modules/core.log":243,"./modules/core.number.iterator":244,"./modules/core.number.math":245,"./modules/core.object":246,"./modules/core.string.escape-html":247,"./shim":291}],210:[function(e,t){"use strict";var n=e("./$");t.exports=function(e){return function(t){var r,l=n.toObject(this),i=n.toLength(l.length),s=n.toIndex(arguments[1],i);if(e&&t!=t){for(;i>s;)if(r=l[s++],r!=r)return!0}else for(;i>s;s++)if((e||s in l)&&l[s]===t)return e||s;return!e&&-1}}},{"./$":223}],211:[function(e,t){"use strict";var n=e("./$"),r=e("./$.ctx");t.exports=function(e){var t=1==e,l=2==e,i=3==e,s=4==e,a=6==e,o=5==e||a;return function(u){for(var p,c,d=Object(n.assertDefined(this)),f=n.ES5Object(d),h=r(u,arguments[1],3),m=n.toLength(f.length),g=0,y=t?Array(m):l?[]:void 0;m>g;g++)if((o||g in f)&&(p=f[g],c=h(p,g,d),e))if(t)y[g]=c;else if(c)switch(e){case 3:return!0;case 5:return p;case 6:return g;case 2:y.push(p)}else if(s)return!1;return a?-1:i||s?s:y}}},{"./$":223,"./$.ctx":218}],212:[function(e,t){function n(e,t,n){if(!e)throw TypeError(n?t+n:t)}var r=e("./$");n.def=r.assertDefined,n.fn=function(e){if(!r.isFunction(e))throw TypeError(e+" is not a function!");return e},n.obj=function(e){if(!r.isObject(e))throw TypeError(e+" is not an object!");return e},n.inst=function(e,t,n){if(!(e instanceof t))throw TypeError(n+": use the 'new' operator!");return e},t.exports=n},{"./$":223}],213:[function(e,t){var n=e("./$");t.exports=Object.assign||function(e){for(var t=Object(n.assertDefined(e)),r=arguments.length,l=1;r>l;)for(var i,s=n.ES5Object(arguments[l++]),a=n.getKeys(s),o=a.length,u=0;o>u;)t[i=a[u++]]=s[i];return t}},{"./$":223}],214:[function(e,t){function n(e){return i.call(e).slice(8,-1)}var r=e("./$"),l=e("./$.wks")("toStringTag"),i={}.toString;n.classof=function(e){var t,r;return void 0==e?void 0===e?"Undefined":"Null":"string"==typeof(r=(t=Object(e))[l])?r:n(t)},n.set=function(e,t,n){e&&!r.has(e=n?e:e.prototype,l)&&r.hide(e,l,t)},t.exports=n},{"./$":223,"./$.wks":234}],215:[function(e,t){"use strict";function n(e,t){if(!c(e))return("string"==typeof e?"S":"P")+e;if(h(e))return"F";if(!u(e,m)){if(!t)return"E";d(e,m,++E)}return"O"+e[m]}function r(e,t){var r,l=n(t);if("F"!=l)return e[g][l];for(r=e[b];r;r=r.n)if(r.k==t)return r}var l=e("./$"),i=e("./$.ctx"),s=e("./$.uid").safe,a=e("./$.assert"),o=e("./$.iter"),u=l.has,p=l.set,c=l.isObject,d=l.hide,f=o.step,h=Object.isFrozen||l.core.Object.isFrozen,m=s("id"),g=s("O1"),y=s("last"),b=s("first"),v=s("iter"),x=l.DESC?s("size"):"size",E=0;t.exports={getConstructor:function(e,t,n){function s(r){var i=a.inst(this,s,e);p(i,g,l.create(null)),p(i,x,0),p(i,y,void 0),p(i,b,void 0),void 0!=r&&o.forOf(r,t,i[n],i)}return l.mix(s.prototype,{clear:function(){for(var e=this,t=e[g],n=e[b];n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete t[n.i];e[b]=e[y]=void 0,e[x]=0},"delete":function(e){var t=this,n=r(t,e);if(n){var l=n.n,i=n.p;delete t[g][n.i],n.r=!0,i&&(i.n=l),l&&(l.p=i),t[b]==n&&(t[b]=l),t[y]==n&&(t[y]=i),t[x]--}return!!n},forEach:function(e){for(var t,n=i(e,arguments[1],3);t=t?t.n:this[b];)for(n(t.v,t.k,this);t&&t.r;)t=t.p},has:function(e){return!!r(this,e)}}),l.DESC&&l.setDesc(s.prototype,"size",{get:function(){return a.def(this[x])}}),s},def:function(e,t,l){var i,s,a=r(e,t);return a?a.v=l:(e[y]=a={i:s=n(t,!0),k:t,v:l,p:i=e[y],n:void 0,r:!1},e[b]||(e[b]=a),i&&(i.n=a),e[x]++,"F"!=s&&(e[g][s]=a)),e},getEntry:r,getIterConstructor:function(){return function(e,t){p(this,v,{o:e,k:t})}},next:function(){for(var e=this[v],t=e.k,n=e.l;n&&n.r;)n=n.p;return e.o&&(e.l=n=n?n.n:e.o[b])?"key"==t?f(0,n.k):"value"==t?f(0,n.v):f(0,[n.k,n.v]):(e.o=void 0,f(1))}}},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.iter":222,"./$.uid":232}],216:[function(e,t){"use strict";function n(e,t){return y.call(e.array,function(e){return e[0]===t})}function r(e){return e[m]||p(e,m,{array:[],get:function(e){var t=n(this,e);return t?t[1]:void 0},has:function(e){return!!n(this,e)},set:function(e,t){var r=n(this,e);r?r[1]=t:this.array.push([e,t])},"delete":function(e){var t=b.call(this.array,function(t){return t[0]===e});return~t&&this.array.splice(t,1),!!~t}})[m]}var l=e("./$"),i=e("./$.uid").safe,s=e("./$.assert"),a=e("./$.iter").forOf,o=l.has,u=l.isObject,p=l.hide,c=Object.isFrozen||l.core.Object.isFrozen,d=0,f=i("id"),h=i("weak"),m=i("leak"),g=e("./$.array-methods"),y=g(5),b=g(6);t.exports={getConstructor:function(e,t,n){function i(r){l.set(s.inst(this,i,e),f,d++),void 0!=r&&a(r,t,this[n],this)}return l.mix(i.prototype,{"delete":function(e){return u(e)?c(e)?r(this)["delete"](e):o(e,h)&&o(e[h],this[f])&&delete e[h][this[f]]:!1},has:function(e){return u(e)?c(e)?r(this).has(e):o(e,h)&&o(e[h],this[f]):!1}}),i},def:function(e,t,n){return c(s.obj(t))?r(e).set(t,n):(o(t,h)||p(t,h,{}),t[h][e[f]]=n),e},leakStore:r,WEAK:h,ID:f}},{"./$":223,"./$.array-methods":211,"./$.assert":212,"./$.iter":222,"./$.uid":232}],217:[function(e,t){"use strict";var n=e("./$"),r=e("./$.def"),l=e("./$.iter"),i=e("./$.assert").inst;t.exports=function(t,s,a,o,u){function p(e,t){var r=h[e];n.FW&&(h[e]=function(e,n){var l=r.call(this,0===e?0:e,n);return t?this:l})}var c=n.g[t],d=c,f=o?"set":"add",h=d&&d.prototype,m={};if(n.isFunction(d)&&(u||!l.BUGGY&&h.forEach&&h.entries)){var g,y=new d,b=y[f](u?{}:-0,1);(l.fail(function(e){new d(e)})||l.DANGER_CLOSING)&&(d=function(e){i(this,d,t);var n=new c;return void 0!=e&&l.forOf(e,o,n[f],n),n},d.prototype=h,n.FW&&(h.constructor=d)),u||y.forEach(function(e,t){g=1/t===-1/0}),g&&(p("delete"),p("has"),o&&p("get")),(g||b!==y)&&p(f,!0)}else d=a.getConstructor(t,o,f),n.mix(d.prototype,s);return e("./$.cof").set(d,t),e("./$.species")(d),m[t]=d,r(r.G+r.W+r.F*(d!=c),m),u||l.std(d,t,a.getIterConstructor(),a.next,o?"key+value":"value",!o,!0),d}},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.def":219,"./$.iter":222,"./$.species":229}],218:[function(e,t){var n=e("./$.assert").fn;t.exports=function(e,t,r){if(n(e),~r&&void 0===t)return e;switch(r){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,l){return e.call(t,n,r,l)}}return function(){return e.apply(t,arguments)}}},{"./$.assert":212}],219:[function(e,t){function n(e,t){return function(){return e.apply(t,arguments)}}function r(e,t,o){var u,p,c,d,f=e&r.G,h=f?i:e&r.S?i[t]:(i[t]||{}).prototype,m=f?s:s[t]||(s[t]={});f&&(o=t);for(u in o)p=!(e&r.F)&&h&&u in h,p&&u in m||(c=p?h[u]:o[u],f&&!a(h[u])?d=o[u]:e&r.B&&p?d=n(c,i):e&r.W&&h[u]==c?!function(e){d=function(t){return this instanceof e?new e(t):e(t)},d.prototype=e.prototype}(c):d=e&r.P&&a(c)?n(Function.call,c):c,l.hide(m,u,d))}var l=e("./$"),i=l.g,s=l.core,a=l.isFunction;r.F=1,r.G=2,r.S=4,r.P=8,r.B=16,r.W=32,t.exports=r},{"./$":223}],220:[function(e,t){t.exports=function(e){return e.FW=!1,e.path=e.core,e}},{}],221:[function(e,t){t.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3]);case 5:return r?e(t[0],t[1],t[2],t[3],t[4]):e.call(n,t[0],t[1],t[2],t[3],t[4])}return e.apply(n,t)}},{}],222:[function(e,t){"use strict";function n(e,t){a.hide(e,d,t),f in[]&&a.hide(e,f,t)}function r(e,t,r,l){var i=e.prototype,s=i[d]||i[f]||l&&i[l]||r;if(a.FW&&n(i,s),s!==r){var o=a.getProto(s.call(new e));u.set(o,t+" Iterator",!0),a.FW&&a.has(i,f)&&n(o,a.that)}return h[t]=s,h[t+" Iterator"]=a.that,s}function l(e){var t=a.g.Symbol,n=e[t&&t.iterator||f],r=n||e[d]||h[u.classof(e)];return c(r.call(e))}function i(e){var t=e["return"];void 0!==t&&c(t.call(e))}function s(e,t,n,r){try{return r?t(c(n)[0],n[1]):t(n)}catch(l){throw i(e),l}}var a=e("./$"),o=e("./$.ctx"),u=e("./$.cof"),p=e("./$.def"),c=e("./$.assert").obj,d=e("./$.wks")("iterator"),f="@@iterator",h={},m={},g="keys"in[]&&!("next"in[].keys());n(m,a.that);var y=!0;!function(){try{var e=[1].keys();e["return"]=function(){y=!1},Array.from(e,function(){throw 2})}catch(t){}}();var b=t.exports={BUGGY:g,DANGER_CLOSING:y,fail:function(e){var t=!0;try{var n=[[{},1]],r=n[d](),l=r.next;r.next=function(){return t=!1,l.call(this)},n[d]=function(){return r},e(n)}catch(i){}return t},Iterators:h,prototype:m,step:function(e,t){return{value:t,done:!!e}},stepCall:s,close:i,is:function(e){var t=Object(e),n=a.g.Symbol,r=n&&n.iterator||f;return r in t||d in t||a.has(h,u.classof(t))},get:l,set:n,create:function(e,t,n,r){e.prototype=a.create(r||b.prototype,{next:a.desc(1,n)}),u.set(e,t+" Iterator")},define:r,std:function(e,t,n,l,i,s,o){function u(e){return function(){return new n(this,e)}}b.create(n,t,l);var c,d,f=u("key+value"),h=u("value"),m=e.prototype;if("value"==i?h=r(e,t,h,"values"):f=r(e,t,f,"entries"),i&&(c={entries:f,keys:s?h:u("key"),values:h},p(p.P+p.F*g,t,c),o))for(d in c)d in m||a.hide(m,d,c[d])},forOf:function(e,t,n,r){for(var a,u=l(e),p=o(n,r,t?2:1);!(a=u.next()).done;)if(s(u,p,a.value,t)===!1)return i(u)}}},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.ctx":218,"./$.def":219,"./$.wks":234}],223:[function(e,t){"use strict";function n(e){return isNaN(e=+e)?0:(e>0?h:f)(e)}function r(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}function l(e,t,n){return e[t]=n,e}function i(e){return y?function(t,n,l){return v.setDesc(t,n,r(e,l))}:l}function s(e){return null!==e&&("object"==typeof e||"function"==typeof e)}function a(e){return"function"==typeof e}function o(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}var u="undefined"!=typeof self?self:Function("return this")(),p={},c=Object.defineProperty,d={}.hasOwnProperty,f=Math.ceil,h=Math.floor,m=Math.max,g=Math.min,y=!!function(){try{return 2==c({},"a",{get:function(){return 2}}).a}catch(e){}}(),b=i(1),v=t.exports=e("./$.fw")({g:u,core:p,html:u.document&&document.documentElement,isObject:s,isFunction:a,it:function(e){return e},that:function(){return this},toInteger:n,toLength:function(e){return e>0?g(n(e),9007199254740991):0},toIndex:function(e,t){return e=n(e),0>e?m(e+t,0):g(e,t)},has:function(e,t){return d.call(e,t)},create:Object.create,getProto:Object.getPrototypeOf,DESC:y,desc:r,getDesc:Object.getOwnPropertyDescriptor,setDesc:c,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:o,ES5Object:Object,toObject:function(e){return v.ES5Object(o(e))},hide:b,def:i(0),set:u.Symbol?l:b,mix:function(e,t){for(var n in t)b(e,n,t[n]);return e},each:[].forEach});"undefined"!=typeof __e&&(__e=p),"undefined"!=typeof __g&&(__g=u)},{"./$.fw":220}],224:[function(e,t){var n=e("./$");t.exports=function(e,t){for(var r,l=n.toObject(e),i=n.getKeys(l),s=i.length,a=0;s>a;)if(l[r=i[a++]]===t)return r}},{"./$":223}],225:[function(e,t){var n=e("./$"),r=e("./$.assert").obj;t.exports=function(e){return r(e),n.getSymbols?n.getNames(e).concat(n.getSymbols(e)):n.getNames(e)}},{"./$":223,"./$.assert":212}],226:[function(e,t){"use strict";var n=e("./$"),r=e("./$.invoke"),l=e("./$.assert").fn;t.exports=function(){for(var e=l(this),t=arguments.length,i=Array(t),s=0,a=n.path._,o=!1;t>s;)(i[s]=arguments[s++])===a&&(o=!0);return function(){var n,l=this,s=arguments.length,u=0,p=0;if(!o&&!s)return r(e,i,l);if(n=i.slice(),o)for(;t>u;u++)n[u]===a&&(n[u]=arguments[p++]);for(;s>p;)n.push(arguments[p++]);return r(e,n,l)}}},{"./$":223,"./$.assert":212,"./$.invoke":221}],227:[function(e,t){"use strict";t.exports=function(e,t,n){var r=t===Object(t)?function(e){return t[e]}:t;return function(t){return String(n?t:this).replace(e,r)}}},{}],228:[function(e,t){var n=e("./$"),r=e("./$.assert");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(t,l){try{l=e("./$.ctx")(Function.call,n.getDesc(Object.prototype,"__proto__").set,2),l({},[])}catch(i){t=!0}return function(e,i){return r.obj(e),r(null===i||n.isObject(i),i,": can't set as prototype!"),t?e.__proto__=i:l(e,i),e}}():void 0)},{"./$":223,"./$.assert":212,"./$.ctx":218}],229:[function(e,t){var n=e("./$");t.exports=function(t){n.DESC&&n.FW&&n.setDesc(t,e("./$.wks")("species"),{configurable:!0,get:n.that})}},{"./$":223,"./$.wks":234}],230:[function(e,t){"use strict";var n=e("./$");t.exports=function(e){return function(t){var r,l,i=String(n.assertDefined(this)),s=n.toInteger(t),a=i.length;return 0>s||s>=a?e?"":void 0:(r=i.charCodeAt(s),55296>r||r>56319||s+1===a||(l=i.charCodeAt(s+1))<56320||l>57343?e?i.charAt(s):r:e?i.slice(s,s+2):(r-55296<<10)+(l-56320)+65536)}}},{"./$":223}],231:[function(e,t){"use strict";function n(){var e=+this;if(a.has(v,e)){var t=v[e];delete v[e],t()}}function r(e){n.call(e.data)}var l,i,s,a=e("./$"),o=e("./$.ctx"),u=e("./$.cof"),p=e("./$.invoke"),c=a.g,d=a.isFunction,f=c.setImmediate,h=c.clearImmediate,m=c.postMessage,g=c.addEventListener,y=c.MessageChannel,b=0,v={},x="onreadystatechange";d(f)&&d(h)||(f=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return v[++b]=function(){p(d(e)?e:Function(e),t)},l(b),b},h=function(e){delete v[e]},"process"==u(c.process)?l=function(e){c.process.nextTick(o(n,e,1))}:g&&d(m)&&!a.g.importScripts?(l=function(e){m(e,"*")},g("message",r,!1)):d(y)?(i=new y,s=i.port2,i.port1.onmessage=r,l=o(s.postMessage,s,1)):l=a.g.document&&x in document.createElement("script")?function(e){a.html.appendChild(document.createElement("script"))[x]=function(){a.html.removeChild(this),n.call(e)}}:function(e){setTimeout(o(n,e,1),0)}),t.exports={set:f,clear:h}},{"./$":223,"./$.cof":214,"./$.ctx":218,"./$.invoke":221}],232:[function(e,t){function n(e){return"Symbol("+e+")_"+(++r+Math.random()).toString(36)}var r=0;n.safe=e("./$").g.Symbol||n,t.exports=n},{"./$":223}],233:[function(e,t){var n=e("./$"),r=e("./$.wks")("unscopables");!n.FW||r in[]||n.hide(Array.prototype,r,{}),t.exports=function(e){n.FW&&([][r][e]=!0)}},{"./$":223,"./$.wks":234}],234:[function(e,t){var n=e("./$").g,r={};t.exports=function(t){return r[t]||(r[t]=n.Symbol&&n.Symbol[t]||e("./$.uid").safe("Symbol."+t))}},{"./$":223,"./$.uid":232}],235:[function(e){"use strict";function t(e,n){return this instanceof t?(this[p]=f(e),void(this[o]=!!n)):new t(e,n)}function n(e){function t(e,t,n){this[p]=f(e),this[o]=e[o],this[u]=l(t,n,e[o]?2:1)}return m(t,"Chain",e,g),h(t.prototype,r.that),t}var r=e("./$"),l=e("./$.ctx"),i=e("./$.uid").safe,s=e("./$.def"),a=e("./$.iter"),o=i("entries"),u=i("fn"),p=i("iter"),c=a.forOf,d=a.stepCall,f=a.get,h=a.set,m=a.create;m(t,"Wrapper",function(){return this[p].next()});var g=t.prototype;h(g,function(){return this[p]});var y=n(function(){var e=this[p].next();return e.done?e:a.step(0,d(this[p],this[u],e.value,this[o]))}),b=n(function(){for(;;){var e=this[p].next();if(e.done||d(this[p],this[u],e.value,this[o]))return e}});r.mix(g,{of:function(e,t){c(this,this[o],e,t)},array:function(e,t){var n=[];return c(void 0!=e?this.map(e,t):this,!1,n.push,n),n},filter:function(e,t){return new b(this,e,t)},map:function(e,t){return new y(this,e,t)}}),t.isIterable=a.is,t.getIterator=f,s(s.G+s.F,{$for:t})},{"./$":223,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.uid":232}],236:[function(e){"use strict";var t=e("./$"),n=e("./$.def"),r=e("./$.assert").fn;n(n.P+n.F,"Array",{turn:function(e,n){r(e);for(var l=void 0==n?[]:Object(n),i=t.ES5Object(this),s=t.toLength(i.length),a=0;s>a&&e(l,i[a],a++,this)!==!1;);return l}}),e("./$.unscope")("turn")},{"./$":223,"./$.assert":212,"./$.def":219,"./$.unscope":233}],237:[function(e){"use strict";function t(e){var t=this,l={};return s(t,o,function(e){return void 0!==e&&e in t?n.has(l,e)?l[e]:l[e]=r(t[e],t,-1):u.call(t)})[o](e)}var n=e("./$"),r=e("./$.ctx"),l=e("./$.def"),i=e("./$.invoke"),s=n.hide,a=e("./$.assert").fn,o=n.DESC?e("./$.uid")("tie"):"toLocaleString",u={}.toLocaleString;n.core._=n.path._=n.path._||{},l(l.P+l.F,"Function",{part:e("./$.partial"),only:function(e,t){var r=a(this),l=n.toLength(e),s=arguments.length>1;return function(){for(var e=Math.min(l,arguments.length),n=Array(e),a=0;e>a;)n[a]=arguments[a++];return i(r,n,s?t:this)}}}),s(n.path._,"toString",function(){return o}),s(Object.prototype,o,t),n.DESC||s(Array.prototype,o,t)},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.def":219,"./$.invoke":221,"./$.partial":226,"./$.uid":232}],238:[function(e){function t(e){return e>9?e:"0"+e}function n(e){return function(n,r){function i(t){return s[e+t]()}var s=this,o=u[l.has(u,r)?r:p];return String(n).replace(a,function(e){switch(e){case"s":return i(c);case"ss":return t(i(c));case"m":return i(d);case"mm":return t(i(d));case"h":return i(f);case"hh":return t(i(f));case"D":return i(h);case"DD":return t(i(h));case"W":return o[0][i("Day")];case"N":return i(m)+1;case"NN":return t(i(m)+1);case"M":return o[2][i(m)];case"MM":return o[1][i(m)];case"Y":return i(g);case"YY":return t(i(g)%100)}return e})}}function r(e,t){function n(e){var n=[];return l.each.call(t.months.split(","),function(t){n.push(t.replace(o,"$"+e))}),n}return u[e]=[t.weekdays.split(","),n(1),n(2)],s}var l=e("./$"),i=e("./$.def"),s=l.core,a=/\b\w\w?\b/g,o=/:(.*)\|(.*)$/,u={},p="en",c="Seconds",d="Minutes",f="Hours",h="Date",m="Month",g="FullYear";i(i.P+i.F,h,{format:n("get"),formatUTC:n("getUTC")}),r(p,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"}),r("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"}),s.locale=function(e){return l.has(u,e)?p=e:p},s.addLocale=r},{"./$":223,"./$.def":219}],239:[function(e){var t=e("./$"),n=e("./$.def"),r=e("./$.partial");n(n.G+n.F,{delay:function(e){return new(t.core.Promise||t.g.Promise)(function(t){setTimeout(r.call(t,!0),e)})}})},{"./$":223,"./$.def":219,"./$.partial":226}],240:[function(e){function t(e){var t=a.create(null);return void 0!=e&&(h.is(e)?h.forOf(e,!0,function(e,n){t[e]=n}):p(t,e)),t}function n(e,t){a.set(this,d,{o:y(e),a:g(e),i:0,k:t})}function r(e){return function(t){return new n(t,e)}}function l(e,t){return"function"==typeof e?e:t}function i(e){var n=1==e,r=4==e;return function(i,s,a){var u,p,c,d=o(s,a,3),f=y(i),h=n||7==e||2==e?new(l(this,t)):void 0;for(u in f)if(b(f,u)&&(p=f[u],c=d(p,u,i),e))if(n)h[u]=c;else if(c)switch(e){case 2:h[u]=p;break;case 3:return!0;case 5:return p;case 6:return u;case 7:h[c[0]]=c[1]}else if(r)return!1;return 3==e||r?r:h}}function s(e){return function(n,r,i){f.fn(r);var s,a,o,u=y(n),p=g(u),c=p.length,d=0;for(e?s=void 0==i?new(l(this,t)):Object(i):arguments.length<3?(f(c,"Reduce of empty object with no initial value"),s=u[p[d++]]):s=Object(i);c>d;)if(b(u,a=p[d++]))if(o=r(s,u[a],a,n),e){if(o===!1)break}else s=o;return s}}var a=e("./$"),o=e("./$.ctx"),u=e("./$.def"),p=e("./$.assign"),c=e("./$.keyof"),d=e("./$.uid").safe("iter"),f=e("./$.assert"),h=e("./$.iter"),m=h.step,g=a.getKeys,y=a.toObject,b=a.has;t.prototype=null,h.create(n,"Dict",function(){var e,t=this[d],n=t.o,r=t.a,l=t.k;do if(t.i>=r.length)return t.o=void 0,m(1);while(!b(n,e=r[t.i++]));return"key"==l?m(0,e):"value"==l?m(0,n[e]):m(0,[e,n[e]])});var v=i(6);u(u.G+u.F,{Dict:a.mix(t,{keys:r("key"),values:r("value"),entries:r("key+value"),forEach:i(0),map:i(1),filter:i(2),some:i(3),every:i(4),find:i(5),findKey:v,mapPairs:i(7),reduce:s(!1),turn:s(!0),keyOf:c,includes:function(e,t){return void 0!==(t==t?c(e,t):v(e,function(e){return e!=e}))},has:b,get:function(e,t){return b(e,t)?e[t]:void 0},set:a.def,isDict:function(e){return a.isObject(e)&&a.getProto(e)===t.prototype}})})},{"./$":223,"./$.assert":212,"./$.assign":213,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.keyof":224,"./$.uid":232}],241:[function(e){var t=e("./$.def");t(t.G+t.F,{global:e("./$").g})},{"./$":223,"./$.def":219}],242:[function(e){var t=e("./$").core,n=e("./$.iter");t.isIterable=n.is,t.getIterator=n.get},{"./$":223,"./$.iter":222}],243:[function(e){var t=e("./$"),n=e("./$.def"),r={},l=!0;t.each.call("assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(","),function(e){r[e]=function(){return l&&t.g.console&&t.isFunction(console[e])?Function.apply.call(console[e],console,arguments):void 0}}),n(n.G+n.F,{log:e("./$.assign")(r.log,r,{enable:function(){l=!0},disable:function(){l=!1}})})},{"./$":223,"./$.assign":213,"./$.def":219}],244:[function(e){"use strict";
function t(e){n.set(this,r,{l:n.toLength(e),i:0})}var n=e("./$"),r=e("./$.uid").safe("iter"),l=e("./$.iter"),i=l.step,s="Number";l.create(t,s,function(){var e=this[r],t=e.i++;return t<e.l?i(0,t):i(1)}),l.define(Number,s,function(){return new t(this)})},{"./$":223,"./$.iter":222,"./$.uid":232}],245:[function(e){"use strict";var t=e("./$"),n=e("./$.def"),r=e("./$.invoke"),l={};l.random=function(e){var t=+this,n=void 0==e?0:+e,r=Math.min(t,n);return Math.random()*(Math.max(t,n)-r)+r},t.FW&&t.each.call("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc".split(","),function(e){var t=Math[e];t&&(l[e]=function(){for(var e=[+this],n=0;arguments.length>n;)e.push(arguments[n++]);return r(t,e)})}),n(n.P+n.F,"Number",l)},{"./$":223,"./$.def":219,"./$.invoke":221}],246:[function(e){function t(e,t){for(var r,i=l(n.toObject(t)),s=i.length,a=0;s>a;)n.setDesc(e,r=i[a++],n.getDesc(t,r));return e}var n=e("./$"),r=e("./$.def"),l=e("./$.own-keys");r(r.S+r.F,"Object",{isObject:n.isObject,classof:e("./$.cof").classof,define:t,make:function(e,r){return t(n.create(e),r)}})},{"./$":223,"./$.cof":214,"./$.def":219,"./$.own-keys":225}],247:[function(e){var t,n=e("./$.def"),r=e("./$.replacer"),l={"&":"&","<":"<",">":">",'"':""","'":"'"},i={};for(t in l)i[l[t]]=t;n(n.P+n.F,"String",{escapeHTML:r(/[&<>"']/g,l),unescapeHTML:r(/&(?:amp|lt|gt|quot|apos);/g,i)})},{"./$.def":219,"./$.replacer":227}],248:[function(e){function t(e,t){return function(n){var r,l=w(n),i=0,s=[];for(r in l)r!=d&&E(l,r)&&s.push(r);for(;t>i;)E(l,r=e[i++])&&(~b.call(s,r)||s.push(r));return s}}function n(e){return!a.isObject(e)}function r(){}function l(e){return function(){return e.apply(a.ES5Object(this),arguments)}}function i(e){return function(t,n){f.fn(t);var r=w(this),l=k(r.length),i=e?l-1:0,s=e?-1:1;if(arguments.length<2)for(;;){if(i in r){n=r[i],i+=s;break}i+=s,f(e?i>=0:l>i,"Reduce of empty array with no initial value")}for(;e?i>=0:l>i;i+=s)i in r&&(n=t(n,r[i],i,this));return n}}function s(e){return e>9?e:"0"+e}var a=e("./$"),o=e("./$.cof"),u=e("./$.def"),p=e("./$.invoke"),c=e("./$.array-methods"),d=e("./$.uid").safe("__proto__"),f=e("./$.assert"),h=f.obj,m=Object.prototype,g=[],y=g.slice,b=g.indexOf,v=o.classof,x=Object.defineProperties,E=a.has,_=a.setDesc,S=a.getDesc,I=a.isFunction,w=a.toObject,k=a.toLength,A=!1;if(!a.DESC){try{A=8==_(document.createElement("div"),"x",{get:function(){return 8}}).x}catch(C){}a.setDesc=function(e,t,n){if(A)try{return _(e,t,n)}catch(r){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(h(e)[t]=n.value),e},a.getDesc=function(e,t){if(A)try{return S(e,t)}catch(n){}return E(e,t)?a.desc(!m.propertyIsEnumerable.call(e,t),e[t]):void 0},x=function(e,t){h(e);for(var n,r=a.getKeys(t),l=r.length,i=0;l>i;)a.setDesc(e,n=r[i++],t[n]);return e}}u(u.S+u.F*!a.DESC,"Object",{getOwnPropertyDescriptor:a.getDesc,defineProperty:a.setDesc,defineProperties:x});var T="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),j=T.concat("length","prototype"),M=T.length,P=function(){var e,t=document.createElement("iframe"),n=M;for(t.style.display="none",a.html.appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("<script>document.F=Object</script>"),e.close(),P=e.F;n--;)delete P.prototype[T[n]];return P()};u(u.S,"Object",{getPrototypeOf:a.getProto=a.getProto||function(e){return e=Object(f.def(e)),E(e,d)?e[d]:I(e.constructor)&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?m:null},getOwnPropertyNames:a.getNames=a.getNames||t(j,j.length,!0),create:a.create=a.create||function(e,t){var n;return null!==e?(r.prototype=h(e),n=new r,r.prototype=null,n[d]=e):n=P(),void 0===t?n:x(n,t)},keys:a.getKeys=a.getKeys||t(T,M,!1),seal:a.it,freeze:a.it,preventExtensions:a.it,isSealed:n,isFrozen:n,isExtensible:a.isObject}),u(u.P,"Function",{bind:function(e){function t(){var l=r.concat(y.call(arguments));return p(n,l,this instanceof t?a.create(n.prototype):e)}var n=f.fn(this),r=y.call(arguments,1);return n.prototype&&(t.prototype=n.prototype),t}}),0 in Object("z")&&"z"=="z"[0]||(a.ES5Object=function(e){return"String"==o(e)?e.split(""):Object(e)}),u(u.P+u.F*(a.ES5Object!=Object),"Array",{slice:l(y),join:l(g.join)}),u(u.S,"Array",{isArray:function(e){return"Array"==o(e)}}),u(u.P,"Array",{forEach:a.each=a.each||c(0),map:c(1),filter:c(2),some:c(3),every:c(4),reduce:i(!1),reduceRight:i(!0),indexOf:b=b||e("./$.array-includes")(!1),lastIndexOf:function(e,t){var n=w(this),r=k(n.length),l=r-1;for(arguments.length>1&&(l=Math.min(l,a.toInteger(t))),0>l&&(l=k(r+l));l>=0;l--)if(l in n&&n[l]===e)return l;return-1}}),u(u.P,"String",{trim:e("./$.replacer")(/^\s*([\s\S]*\S)?\s*$/,"$1")}),u(u.S,"Date",{now:function(){return+new Date}}),u(u.P,"Date",{toISOString:function(){if(!isFinite(this))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),n=e.getUTCMilliseconds(),r=0>t?"-":t>9999?"+":"";return r+("00000"+Math.abs(t)).slice(r?-6:-4)+"-"+s(e.getUTCMonth()+1)+"-"+s(e.getUTCDate())+"T"+s(e.getUTCHours())+":"+s(e.getUTCMinutes())+":"+s(e.getUTCSeconds())+"."+(n>99?n:"0"+s(n))+"Z"}}),"Object"==v(function(){return arguments}())&&(o.classof=function(e){var t=v(e);return"Object"==t&&I(e.callee)?"Arguments":t})},{"./$":223,"./$.array-includes":210,"./$.array-methods":211,"./$.assert":212,"./$.cof":214,"./$.def":219,"./$.invoke":221,"./$.replacer":227,"./$.uid":232}],249:[function(e){"use strict";var t=e("./$"),n=e("./$.def"),r=t.toIndex;n(n.P,"Array",{copyWithin:function(e,n){var l=Object(t.assertDefined(this)),i=t.toLength(l.length),s=r(e,i),a=r(n,i),o=arguments[2],u=void 0===o?i:r(o,i),p=Math.min(u-a,i-s),c=1;for(s>a&&a+p>s&&(c=-1,a=a+p-1,s=s+p-1);p-->0;)a in l?l[s]=l[a]:delete l[s],s+=c,a+=c;return l}}),e("./$.unscope")("copyWithin")},{"./$":223,"./$.def":219,"./$.unscope":233}],250:[function(e){"use strict";var t=e("./$"),n=e("./$.def"),r=t.toIndex;n(n.P,"Array",{fill:function(e){for(var n=Object(t.assertDefined(this)),l=t.toLength(n.length),i=r(arguments[1],l),s=arguments[2],a=void 0===s?l:r(s,l);a>i;)n[i++]=e;return n}}),e("./$.unscope")("fill")},{"./$":223,"./$.def":219,"./$.unscope":233}],251:[function(e){var t=e("./$.def");t(t.P,"Array",{findIndex:e("./$.array-methods")(6)}),e("./$.unscope")("findIndex")},{"./$.array-methods":211,"./$.def":219,"./$.unscope":233}],252:[function(e){var t=e("./$.def");t(t.P,"Array",{find:e("./$.array-methods")(5)}),e("./$.unscope")("find")},{"./$.array-methods":211,"./$.def":219,"./$.unscope":233}],253:[function(e){var t=e("./$"),n=e("./$.ctx"),r=e("./$.def"),l=e("./$.iter"),i=l.stepCall;r(r.S+r.F*l.DANGER_CLOSING,"Array",{from:function(e){var r,s,a,o,u=Object(t.assertDefined(e)),p=arguments[1],c=void 0!==p,d=c?n(p,arguments[2],2):void 0,f=0;if(l.is(u))for(o=l.get(u),s=new("function"==typeof this?this:Array);!(a=o.next()).done;f++)s[f]=c?i(o,d,[a.value,f],!0):a.value;else for(s=new("function"==typeof this?this:Array)(r=t.toLength(u.length));r>f;f++)s[f]=c?d(u[f],f):u[f];return s.length=f,s}})},{"./$":223,"./$.ctx":218,"./$.def":219,"./$.iter":222}],254:[function(e){var t=e("./$"),n=e("./$.unscope"),r=e("./$.uid").safe("iter"),l=e("./$.iter"),i=l.step,s=l.Iterators;l.std(Array,"Array",function(e,n){t.set(this,r,{o:t.toObject(e),i:0,k:n})},function(){var e=this[r],t=e.o,n=e.k,l=e.i++;return!t||l>=t.length?(e.o=void 0,i(1)):"key"==n?i(0,l):"value"==n?i(0,t[l]):i(0,[l,t[l]])},"value"),s.Arguments=s.Array,n("keys"),n("values"),n("entries")},{"./$":223,"./$.iter":222,"./$.uid":232,"./$.unscope":233}],255:[function(e){var t=e("./$.def");t(t.S,"Array",{of:function(){for(var e=0,t=arguments.length,n=new("function"==typeof this?this:Array)(t);t>e;)n[e]=arguments[e++];return n.length=t,n}})},{"./$.def":219}],256:[function(e){e("./$.species")(Array)},{"./$.species":229}],257:[function(e){"use strict";var t=e("./$"),n="name",r=t.setDesc,l=Function.prototype;n in l||t.FW&&t.DESC&&r(l,n,{configurable:!0,get:function(){var e=String(this).match(/^\s*function ([^ (]*)/),l=e?e[1]:"";return t.has(this,n)||r(this,n,t.desc(5,l)),l},set:function(e){t.has(this,n)||r(this,n,t.desc(0,e))}})},{"./$":223}],258:[function(e){"use strict";var t=e("./$.collection-strong");e("./$.collection")("Map",{get:function(e){var n=t.getEntry(this,e);return n&&n.v},set:function(e,n){return t.def(this,0===e?0:e,n)}},t,!0)},{"./$.collection":217,"./$.collection-strong":215}],259:[function(e){function t(e){return isFinite(e=+e)&&0!=e?0>e?-t(-e):u(e+p(e*e+1)):e}function n(e){return 0==(e=+e)?e:e>-1e-6&&1e-6>e?e+e*e/2:o(e)-1}var r=1/0,l=e("./$.def"),i=Math.E,s=Math.pow,a=Math.abs,o=Math.exp,u=Math.log,p=Math.sqrt,c=Math.ceil,d=Math.floor,f=Math.sign||function(e){return 0==(e=+e)||e!=e?e:0>e?-1:1};l(l.S,"Math",{acosh:function(e){return(e=+e)<1?0/0:isFinite(e)?u(e/i+p(e+1)*p(e-1)/i)+1:e},asinh:t,atanh:function(e){return 0==(e=+e)?e:u((1+e)/(1-e))/2},cbrt:function(e){return f(e=+e)*s(a(e),1/3)},clz32:function(e){return(e>>>=0)?32-e.toString(2).length:32},cosh:function(e){return(o(e=+e)+o(-e))/2},expm1:n,fround:function(e){return new Float32Array([e])[0]},hypot:function(){for(var e,t=0,n=arguments.length,l=n,i=Array(n),a=-r;n--;){if(e=i[n]=+arguments[n],e==r||e==-r)return r;e>a&&(a=e)}for(a=e||1;l--;)t+=s(i[l]/a,2);return a*p(t)},imul:function(e,t){var n=65535,r=+e,l=+t,i=n&r,s=n&l;return 0|i*s+((n&r>>>16)*s+i*(n&l>>>16)<<16>>>0)},log1p:function(e){return(e=+e)>-1e-8&&1e-8>e?e-e*e/2:u(1+e)},log10:function(e){return u(e)/Math.LN10},log2:function(e){return u(e)/Math.LN2},sign:f,sinh:function(e){return a(e=+e)<1?(n(e)-n(-e))/2:(o(e-1)-o(-e-1))*(i/2)},tanh:function(e){var t=n(e=+e),l=n(-e);return t==r?1:l==r?-1:(t-l)/(o(e)+o(-e))},trunc:function(e){return(e>0?d:c)(e)}})},{"./$.def":219}],260:[function(e){"use strict";function t(e){var t,n;if(i(t=e.valueOf)&&!l(n=t.call(e)))return n;if(i(t=e.toString)&&!l(n=t.call(e)))return n;throw TypeError("Can't convert object to number")}function n(e){if(l(e)&&(e=t(e)),"string"==typeof e&&e.length>2&&48==e.charCodeAt(0)){var n=!1;switch(e.charCodeAt(1)){case 66:case 98:n=!0;case 79:case 111:return parseInt(e.slice(2),n?2:8)}}return+e}var r=e("./$"),l=r.isObject,i=r.isFunction,s="Number",a=r.g[s],o=a,u=a.prototype;!r.FW||a("0o1")&&a("0b1")||(a=function p(e){return this instanceof p?new o(n(e)):n(e)},r.each.call(r.DESC?r.getNames(o):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),function(e){r.has(o,e)&&!r.has(a,e)&&r.setDesc(a,e,r.getDesc(o,e))}),a.prototype=u,u.constructor=a,r.hide(r.g,s,a))},{"./$":223}],261:[function(e){function t(e){return!n.isObject(e)&&isFinite(e)&&i(e)===e}var n=e("./$"),r=e("./$.def"),l=Math.abs,i=Math.floor,s=9007199254740991;r(r.S,"Number",{EPSILON:Math.pow(2,-52),isFinite:function(e){return"number"==typeof e&&isFinite(e)},isInteger:t,isNaN:function(e){return e!=e},isSafeInteger:function(e){return t(e)&&l(e)<=s},MAX_SAFE_INTEGER:s,MIN_SAFE_INTEGER:-s,parseFloat:parseFloat,parseInt:parseInt})},{"./$":223,"./$.def":219}],262:[function(e){var t=e("./$.def");t(t.S,"Object",{assign:e("./$.assign")})},{"./$.assign":213,"./$.def":219}],263:[function(e){var t=e("./$.def");t(t.S,"Object",{is:function(e,t){return e===t?0!==e||1/e===1/t:e!=e&&t!=t}})},{"./$.def":219}],264:[function(e){var t=e("./$.def");t(t.S,"Object",{setPrototypeOf:e("./$.set-proto")})},{"./$.def":219,"./$.set-proto":228}],265:[function(e){function t(e,t){var s=(n.core.Object||{})[e]||Object[e],a=0,o={};o[e]=1==t?function(e){return l(e)?s(e):e}:2==t?function(e){return l(e)?s(e):!0}:3==t?function(e){return l(e)?s(e):!1}:4==t?function(e,t){return s(i(e),t)}:5==t?function(e){return s(Object(n.assertDefined(e)))}:function(e){return s(i(e))};try{s("z")}catch(u){a=1}r(r.S+r.F*a,"Object",o)}var n=e("./$"),r=e("./$.def"),l=n.isObject,i=n.toObject;t("freeze",1),t("seal",1),t("preventExtensions",1),t("isFrozen",2),t("isSealed",2),t("isExtensible",3),t("getOwnPropertyDescriptor",4),t("getPrototypeOf",5),t("keys"),t("getOwnPropertyNames")},{"./$":223,"./$.def":219}],266:[function(e){"use strict";var t=e("./$"),n=e("./$.cof"),r={};r[e("./$.wks")("toStringTag")]="z",t.FW&&"z"!=n(r)&&t.hide(Object.prototype,"toString",function(){return"[object "+n.classof(this)+"]"})},{"./$":223,"./$.cof":214,"./$.wks":234}],267:[function(e){"use strict";function t(e){var t=E(e)[u];return void 0!=t?t:e}var n,r=e("./$"),l=e("./$.ctx"),i=e("./$.cof"),s=e("./$.def"),a=e("./$.assert"),o=e("./$.iter"),u=e("./$.wks")("species"),p=e("./$.uid").safe("record"),c=o.forOf,d="Promise",f=r.g,h=f.process,m=h&&h.nextTick||e("./$.task").set,g=f[d],y=g,b=r.isFunction,v=r.isObject,x=a.fn,E=a.obj;b(g)&&b(g.resolve)&&g.resolve(n=new g(function(){}))==n||function(){function e(e){var t;return v(e)&&(t=e.then),b(t)?t:!1}function t(e){var n,r=e[p],l=r.c,i=0;if(r.h)return!0;for(;l.length>i;)if(n=l[i++],n.fail||t(n.P))return!0}function n(n,r){var l=n.c;(r||l.length)&&m(function(){var s=n.p,a=n.v,o=1==n.s,u=0;if(r&&!t(s))setTimeout(function(){t(s)||("process"==i(h)?h.emit("unhandledRejection",a,s):f.console&&b(console.error)&&console.error("Unhandled promise rejection",a))},1e3);else for(;l.length>u;)!function(t){var r,l,i=o?t.ok:t.fail;try{i?(o||(n.h=!0),r=i===!0?a:i(a),r===t.P?t.rej(TypeError(d+"-chain cycle")):(l=e(r))?l.call(r,t.res,t.rej):t.res(r)):t.rej(a)}catch(s){t.rej(s)}}(l[u++]);l.length=0})}function s(e){var t=this;t.d||(t.d=!0,t=t.r||t,t.v=e,t.s=2,n(t,!0))}function o(t){var r,i,a=this;if(!a.d){a.d=!0,a=a.r||a;try{(r=e(t))?(i={r:a,d:!1},r.call(t,l(o,i,1),l(s,i,1))):(a.v=t,a.s=1,n(a))}catch(u){s.call(i||{r:a,d:!1},u)}}}g=function(e){x(e);var t={p:a.inst(this,g,d),c:[],s:0,d:!1,v:void 0,h:!1};r.hide(this,p,t);try{e(l(o,t,1),l(s,t,1))}catch(n){s.call(t,n)}},r.mix(g.prototype,{then:function(e,t){var r=E(E(this).constructor)[u],l={ok:b(e)?e:!0,fail:b(t)?t:!1},i=l.P=new(void 0!=r?r:g)(function(e,t){l.res=x(e),l.rej=x(t)}),s=this[p];return s.c.push(l),s.s&&n(s),i},"catch":function(e){return this.then(void 0,e)}})}(),s(s.G+s.W+s.F*(g!=y),{Promise:g}),s(s.S,d,{reject:function(e){return new(t(this))(function(t,n){n(e)})},resolve:function(e){return v(e)&&p in e&&r.getProto(e)===this.prototype?e:new(t(this))(function(t){t(e)})}}),s(s.S+s.F*(o.fail(function(e){g.all(e)["catch"](function(){})})||o.DANGER_CLOSING),d,{all:function(e){var n=t(this),l=[];return new n(function(t,i){c(e,!1,l.push,l);var s=l.length,a=Array(s);s?r.each.call(l,function(e,r){n.resolve(e).then(function(e){a[r]=e,--s||t(a)},i)}):t(a)})},race:function(e){var n=t(this);return new n(function(t,r){c(e,!1,function(e){n.resolve(e).then(t,r)})})}}),i.set(g,d),e("./$.species")(g)},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.species":229,"./$.task":231,"./$.uid":232,"./$.wks":234}],268:[function(e){function t(e){var t,n=[];for(t in e)n.push(t);i.set(this,u,{o:e,a:n,i:0})}function n(e){return function(t){y(t);try{return e.apply(void 0,arguments),!0}catch(n){return!1}}}function r(e,t){var n,l=arguments.length<3?e:arguments[2],s=f(y(e),t);return s?i.has(s,"value")?s.value:void 0===s.get?void 0:s.get.call(l):d(n=m(e))?r(n,t,l):void 0}function l(e,t,n){var r,s,a=arguments.length<4?e:arguments[3],o=f(y(e),t);if(!o){if(d(s=m(e)))return l(s,t,n,a);o=i.desc(0)}return i.has(o,"value")?o.writable!==!1&&d(a)?(r=f(a,t)||i.desc(0),r.value=n,h(a,t,r),!0):!1:void 0===o.set?!1:(o.set.call(a,n),!0)}var i=e("./$"),s=e("./$.def"),a=e("./$.set-proto"),o=e("./$.iter"),u=e("./$.uid").safe("iter"),p=o.step,c=e("./$.assert"),d=i.isObject,f=i.getDesc,h=i.setDesc,m=i.getProto,g=Function.apply,y=c.obj,b=Object.isExtensible||i.it;o.create(t,"Object",function(){var e,t=this[u],n=t.a;do if(t.i>=n.length)return p(1);while(!((e=n[t.i++])in t.o));return p(0,e)});var v={apply:e("./$.ctx")(Function.call,g,3),construct:function(e,t){var n=c.fn(arguments.length<3?e:arguments[2]).prototype,r=i.create(d(n)?n:Object.prototype),l=g.call(e,r,t);return d(l)?l:r},defineProperty:n(h),deleteProperty:function(e,t){var n=f(y(e),t);return n&&!n.configurable?!1:delete e[t]},enumerate:function(e){return new t(y(e))},get:r,getOwnPropertyDescriptor:function(e,t){return f(y(e),t)},getPrototypeOf:function(e){return m(y(e))},has:function(e,t){return t in e},isExtensible:function(e){return!!b(y(e))},ownKeys:e("./$.own-keys"),preventExtensions:n(Object.preventExtensions||i.it),set:l};a&&(v.setPrototypeOf=function(e,t){return a(y(e),t),!0}),s(s.G,{Reflect:{}}),s(s.S,"Reflect",v)},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.own-keys":225,"./$.set-proto":228,"./$.uid":232}],269:[function(e){var t=e("./$"),n=e("./$.cof"),r=t.g.RegExp,l=r,i=r.prototype;t.FW&&t.DESC&&(function(){try{return"/a/i"==r(/a/g,"i")}catch(e){}}()||(r=function(e,t){return new l("RegExp"==n(e)&&void 0!==t?e.source:e,t)},t.each.call(t.getNames(l),function(e){e in r||t.setDesc(r,e,{configurable:!0,get:function(){return l[e]},set:function(t){l[e]=t}})}),i.constructor=r,r.prototype=i,t.hide(t.g,"RegExp",r)),"g"!=/./g.flags&&t.setDesc(i,"flags",{configurable:!0,get:e("./$.replacer")(/^.*\/(\w*)$/,"$1")})),e("./$.species")(r)},{"./$":223,"./$.cof":214,"./$.replacer":227,"./$.species":229}],270:[function(e){"use strict";var t=e("./$.collection-strong");e("./$.collection")("Set",{add:function(e){return t.def(this,e=0===e?0:e,e)}},t)},{"./$.collection":217,"./$.collection-strong":215}],271:[function(e){var t=e("./$.def");t(t.P,"String",{codePointAt:e("./$.string-at")(!1)})},{"./$.def":219,"./$.string-at":230}],272:[function(e){"use strict";var t=e("./$"),n=e("./$.cof"),r=e("./$.def"),l=t.toLength;r(r.P,"String",{endsWith:function(e){if("RegExp"==n(e))throw TypeError();var r=String(t.assertDefined(this)),i=arguments[1],s=l(r.length),a=void 0===i?s:Math.min(l(i),s);return e+="",r.slice(a-e.length,a)===e}})},{"./$":223,"./$.cof":214,"./$.def":219}],273:[function(e){var t=e("./$.def"),n=e("./$").toIndex,r=String.fromCharCode;t(t.S,"String",{fromCodePoint:function(){for(var e,t=[],l=arguments.length,i=0;l>i;){if(e=+arguments[i++],n(e,1114111)!==e)throw RangeError(e+" is not a valid code point");t.push(65536>e?r(e):r(((e-=65536)>>10)+55296,e%1024+56320))}return t.join("")}})},{"./$":223,"./$.def":219}],274:[function(e){"use strict";var t=e("./$"),n=e("./$.cof"),r=e("./$.def");r(r.P,"String",{includes:function(e){if("RegExp"==n(e))throw TypeError();return!!~String(t.assertDefined(this)).indexOf(e,arguments[1])}})},{"./$":223,"./$.cof":214,"./$.def":219}],275:[function(e){var t=e("./$").set,n=e("./$.string-at")(!0),r=e("./$.uid").safe("iter"),l=e("./$.iter"),i=l.step;l.std(String,"String",function(e){t(this,r,{o:String(e),i:0})},function(){var e,t=this[r],l=t.o,s=t.i;return s>=l.length?i(1):(e=n.call(l,s),t.i+=e.length,i(0,e))})},{"./$":223,"./$.iter":222,"./$.string-at":230,"./$.uid":232}],276:[function(e){var t=e("./$"),n=e("./$.def");n(n.S,"String",{raw:function(e){for(var n=t.toObject(e.raw),r=t.toLength(n.length),l=arguments.length,i=[],s=0;r>s;)i.push(String(n[s++])),l>s&&i.push(String(arguments[s]));return i.join("")}})},{"./$":223,"./$.def":219}],277:[function(e){"use strict";var t=e("./$"),n=e("./$.def");n(n.P,"String",{repeat:function(e){var n=String(t.assertDefined(this)),r="",l=t.toInteger(e);if(0>l||1/0==l)throw RangeError("Count can't be negative");for(;l>0;(l>>>=1)&&(n+=n))1&l&&(r+=n);return r}})},{"./$":223,"./$.def":219}],278:[function(e){"use strict";var t=e("./$"),n=e("./$.cof"),r=e("./$.def");r(r.P,"String",{startsWith:function(e){if("RegExp"==n(e))throw TypeError();var r=String(t.assertDefined(this)),l=t.toLength(Math.min(arguments[1],r.length));return e+="",r.slice(l,l+e.length)===e}})},{"./$":223,"./$.cof":214,"./$.def":219}],279:[function(e){"use strict";function t(e){var t=g[e]=n.set(n.create(c.prototype),h,e);return n.DESC&&f&&n.setDesc(Object.prototype,e,{configurable:!0,set:function(t){o(this,e,t)}}),t}var n=e("./$"),r=e("./$.cof").set,l=e("./$.uid"),i=e("./$.def"),s=e("./$.keyof"),a=n.has,o=n.hide,u=n.getNames,p=n.toObject,c=n.g.Symbol,d=c,f=!1,h=l.safe("tag"),m={},g={};n.isFunction(c)||(c=function(e){if(this instanceof c)throw TypeError("Symbol is not a constructor");return t(l(e))},o(c.prototype,"toString",function(){return this[h]})),i(i.G+i.W,{Symbol:c});var y={"for":function(e){return a(m,e+="")?m[e]:m[e]=c(e)},keyFor:function(e){return s(m,e)},pure:l.safe,set:n.set,useSetter:function(){f=!0},useSimple:function(){f=!1}};n.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),function(n){var r=e("./$.wks")(n);y[n]=c===d?r:t(r)}),f=!0,i(i.S,"Symbol",y),i(i.S+i.F*(c!=d),"Object",{getOwnPropertyNames:function(e){for(var t,n=u(p(e)),r=[],l=0;n.length>l;)a(g,t=n[l++])||r.push(t);return r},getOwnPropertySymbols:function(e){for(var t,n=u(p(e)),r=[],l=0;n.length>l;)a(g,t=n[l++])&&r.push(g[t]);return r}}),r(c,"Symbol"),r(Math,"Math",!0),r(n.g.JSON,"JSON",!0)},{"./$":223,"./$.cof":214,"./$.def":219,"./$.keyof":224,"./$.uid":232,"./$.wks":234}],280:[function(e){"use strict";var t=e("./$"),n=e("./$.collection-weak"),r=n.leakStore,l=n.ID,i=n.WEAK,s=t.has,a=t.isObject,o=Object.isFrozen||t.core.Object.isFrozen,u={},p=e("./$.collection")("WeakMap",{get:function(e){if(a(e)){if(o(e))return r(this).get(e);if(s(e,i))return e[i][this[l]]}},set:function(e,t){return n.def(this,e,t)}},n,!0,!0);t.FW&&7!=(new p).set((Object.freeze||Object)(u),7).get(u)&&t.each.call(["delete","has","get","set"],function(e){var t=p.prototype[e];p.prototype[e]=function(n,l){if(a(n)&&o(n)){var i=r(this)[e](n,l);return"set"==e?this:i}return t.call(this,n,l)}})},{"./$":223,"./$.collection":217,"./$.collection-weak":216}],281:[function(e){"use strict";var t=e("./$.collection-weak");e("./$.collection")("WeakSet",{add:function(e){return t.def(this,e,!0)}},t,!1,!0)},{"./$.collection":217,"./$.collection-weak":216}],282:[function(e){var t=e("./$.def");t(t.P,"Array",{includes:e("./$.array-includes")(!0)}),e("./$.unscope")("includes")},{"./$.array-includes":210,"./$.def":219,"./$.unscope":233}],283:[function(e){var t=e("./$"),n=e("./$.def"),r=e("./$.own-keys");n(n.S,"Object",{getOwnPropertyDescriptors:function(e){var n=t.toObject(e),l={};return t.each.call(r(n),function(e){t.setDesc(l,e,t.desc(0,t.getDesc(n,e)))}),l}})},{"./$":223,"./$.def":219,"./$.own-keys":225}],284:[function(e){function t(e){return function(t){var r,l=n.toObject(t),i=n.getKeys(t),s=i.length,a=0,o=Array(s);if(e)for(;s>a;)o[a]=[r=i[a++],l[r]];else for(;s>a;)o[a]=l[i[a++]];return o}}var n=e("./$"),r=e("./$.def");r(r.S,"Object",{values:t(!1),entries:t(!0)})},{"./$":223,"./$.def":219}],285:[function(e){var t=e("./$.def");t(t.S,"RegExp",{escape:e("./$.replacer")(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",!0)})},{"./$.def":219,"./$.replacer":227}],286:[function(e){var t=e("./$.def");t(t.P,"String",{at:e("./$.string-at")(!0)})},{"./$.def":219,"./$.string-at":230}],287:[function(e){function t(t,r){n.each.call(t.split(","),function(t){void 0==r&&t in l.Array?i[t]=l.Array[t]:t in[]&&(i[t]=e("./$.ctx")(Function.call,[][t],r))})}var n=e("./$"),r=e("./$.def"),l=n.core,i={};t("pop,reverse,shift,keys,values,entries",1),t("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3),t("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill,turn"),r(r.S,"Array",i)},{"./$":223,"./$.ctx":218,"./$.def":219}],288:[function(e){e("./es6.array.iterator");var t=e("./$"),n=e("./$.iter").Iterators,r=e("./$.wks")("iterator"),l=t.g.NodeList;!t.FW||!l||r in l.prototype||t.hide(l.prototype,r,n.Array),n.NodeList=n.Array},{"./$":223,"./$.iter":222,"./$.wks":234,"./es6.array.iterator":254}],289:[function(e){var t=e("./$.def"),n=e("./$.task");t(t.G+t.B,{setImmediate:n.set,clearImmediate:n.clear})},{"./$.def":219,"./$.task":231}],290:[function(e){function t(e){return s?function(t,r){return e(l(i,[].slice.call(arguments,2),n.isFunction(t)?t:Function(t)),r)}:e}var n=e("./$"),r=e("./$.def"),l=e("./$.invoke"),i=e("./$.partial"),s=!!n.g.navigator&&/MSIE .\./.test(navigator.userAgent);r(r.G+r.B+r.F*s,{setTimeout:t(n.g.setTimeout),setInterval:t(n.g.setInterval)})},{"./$":223,"./$.def":219,"./$.invoke":221,"./$.partial":226}],291:[function(e,t){e("./modules/es5"),e("./modules/es6.symbol"),e("./modules/es6.object.assign"),e("./modules/es6.object.is"),e("./modules/es6.object.set-prototype-of"),e("./modules/es6.object.to-string"),e("./modules/es6.object.statics-accept-primitives"),e("./modules/es6.function.name"),e("./modules/es6.number.constructor"),e("./modules/es6.number.statics"),e("./modules/es6.math"),e("./modules/es6.string.from-code-point"),e("./modules/es6.string.raw"),e("./modules/es6.string.iterator"),e("./modules/es6.string.code-point-at"),e("./modules/es6.string.ends-with"),e("./modules/es6.string.includes"),e("./modules/es6.string.repeat"),e("./modules/es6.string.starts-with"),e("./modules/es6.array.from"),e("./modules/es6.array.of"),e("./modules/es6.array.iterator"),e("./modules/es6.array.species"),e("./modules/es6.array.copy-within"),e("./modules/es6.array.fill"),e("./modules/es6.array.find"),e("./modules/es6.array.find-index"),e("./modules/es6.regexp"),e("./modules/es6.promise"),e("./modules/es6.map"),e("./modules/es6.set"),e("./modules/es6.weak-map"),e("./modules/es6.weak-set"),e("./modules/es6.reflect"),e("./modules/es7.array.includes"),e("./modules/es7.string.at"),e("./modules/es7.regexp.escape"),e("./modules/es7.object.get-own-property-descriptors"),e("./modules/es7.object.to-array"),e("./modules/js.array.statics"),e("./modules/web.timers"),e("./modules/web.immediate"),e("./modules/web.dom.iterable"),t.exports=e("./modules/$").core},{"./modules/$":223,"./modules/es5":248,"./modules/es6.array.copy-within":249,"./modules/es6.array.fill":250,"./modules/es6.array.find":252,"./modules/es6.array.find-index":251,"./modules/es6.array.from":253,"./modules/es6.array.iterator":254,"./modules/es6.array.of":255,"./modules/es6.array.species":256,"./modules/es6.function.name":257,"./modules/es6.map":258,"./modules/es6.math":259,"./modules/es6.number.constructor":260,"./modules/es6.number.statics":261,"./modules/es6.object.assign":262,"./modules/es6.object.is":263,"./modules/es6.object.set-prototype-of":264,"./modules/es6.object.statics-accept-primitives":265,"./modules/es6.object.to-string":266,"./modules/es6.promise":267,"./modules/es6.reflect":268,"./modules/es6.regexp":269,"./modules/es6.set":270,"./modules/es6.string.code-point-at":271,"./modules/es6.string.ends-with":272,"./modules/es6.string.from-code-point":273,"./modules/es6.string.includes":274,"./modules/es6.string.iterator":275,"./modules/es6.string.raw":276,"./modules/es6.string.repeat":277,"./modules/es6.string.starts-with":278,"./modules/es6.symbol":279,"./modules/es6.weak-map":280,"./modules/es6.weak-set":281,"./modules/es7.array.includes":282,"./modules/es7.object.get-own-property-descriptors":283,"./modules/es7.object.to-array":284,"./modules/es7.regexp.escape":285,"./modules/es7.string.at":286,"./modules/js.array.statics":287,"./modules/web.dom.iterable":288,"./modules/web.immediate":289,"./modules/web.timers":290}],292:[function(e,t,n){function r(){return n.colors[p++%n.colors.length]}function l(e){function t(){}function l(){var e=l,t=+new Date,i=t-(u||t);e.diff=i,e.prev=u,e.curr=t,u=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var s=Array.prototype.slice.call(arguments);s[0]=n.coerce(s[0]),"string"!=typeof s[0]&&(s=["%o"].concat(s));var a=0;s[0]=s[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;a++;var l=n.formatters[r];if("function"==typeof l){var i=s[a];t=l.call(e,i),s.splice(a,1),a--}return t}),"function"==typeof n.formatArgs&&(s=n.formatArgs.apply(e,s));var o=l.log||n.log||console.log.bind(console);o.apply(e,s)}t.enabled=!1,l.enabled=!0;var i=n.enabled(e)?l:t;return i.namespace=e,i}function i(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,l=0;r>l;l++)t[l]&&(e=t[l].replace(/\*/g,".*?"),"-"===e[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function s(){n.enable("")}function a(e){var t,r;for(t=0,r=n.skips.length;r>t;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;r>t;t++)if(n.names[t].test(e))return!0;return!1}function o(e){return e instanceof Error?e.stack||e.message:e}n=t.exports=l,n.coerce=o,n.disable=s,n.enable=i,n.enabled=a,n.humanize=e("ms"),n.names=[],n.skips=[],n.formatters={};var u,p=0},{ms:294}],293:[function(e,t,n){(function(r){function l(){var e=(r.env.DEBUG_COLORS||"").trim().toLowerCase();return 0===e.length?p.isatty(d):"0"!==e&&"no"!==e&&"false"!==e&&"disabled"!==e}function i(){var e=arguments,t=this.useColors,r=this.namespace;if(t){var l=this.color;e[0]=" [3"+l+";1m"+r+" [0m"+e[0]+"[3"+l+"m +"+n.humanize(this.diff)+"[0m"}else e[0]=(new Date).toUTCString()+" "+r+" "+e[0];return e}function s(){return f.write(c.format.apply(this,arguments)+"\n")}function a(e){null==e?delete r.env.DEBUG:r.env.DEBUG=e}function o(){return r.env.DEBUG}function u(t){var n,l=r.binding("tty_wrap");switch(l.guessHandleType(t)){case"TTY":n=new p.WriteStream(t),n._type="tty",n._handle&&n._handle.unref&&n._handle.unref();break;case"FILE":var i=e("fs");n=new i.SyncWriteStream(t,{autoClose:!1}),n._type="fs";break;case"PIPE":case"TCP":var s=e("net");n=new s.Socket({fd:t,readable:!1,writable:!0}),n.readable=!1,n.read=null,n._type="pipe",n._handle&&n._handle.unref&&n._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return n.fd=t,n._isStdio=!0,n}var p=e("tty"),c=e("util");n=t.exports=e("./debug"),n.log=s,n.formatArgs=i,n.save=a,n.load=o,n.useColors=l,n.colors=[6,2,3,4,5,1];var d=parseInt(r.env.DEBUG_FD,10)||2,f=1===d?r.stdout:2===d?r.stderr:u(d),h=4===c.inspect.length?function(e,t){return c.inspect(e,void 0,void 0,t)}:function(e,t){return c.inspect(e,{colors:t})};n.formatters.o=function(e){return h(e,this.useColors).replace(/\s*\n\s*/g," ")},n.enable(o())}).call(this,e("_process"))},{"./debug":292,_process:183,fs:172,net:172,tty:197,util:199}],294:[function(e,t){function n(e){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*p;case"days":case"day":case"d":return n*u;case"hours":case"hour":case"hrs":case"hr":case"h":return n*o;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;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}}}function r(e){return e>=u?Math.round(e/u)+"d":e>=o?Math.round(e/o)+"h":e>=a?Math.round(e/a)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function l(e){return i(e,u,"day")||i(e,o,"hour")||i(e,a,"minute")||i(e,s,"second")||e+" ms"}function i(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var s=1e3,a=60*s,o=60*a,u=24*o,p=365.25*u;t.exports=function(e,t){return t=t||{},"string"==typeof e?n(e):t.long?l(e):r(e)}},{}],295:[function(e,t){"use strict";function n(e){var t=0,n=0,r=0;for(var l in e){var i=e[l],s=i[0],a=i[1];(s>n||s===n&&a>r)&&(n=s,r=a,t=+l)}return t}var r=e("repeating"),l=/^(?:( )+|\t+)/;t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");var t,i,s=0,a=0,o=0,u={};e.split(/\n/g).forEach(function(e){if(e){var n,r=e.match(l);r?(n=r[0].length,r[1]?a++:s++):n=0;var p=n-o;o=n,p?(i=p>0,t=u[i?p:-p],t?t[0]++:t=u[p]=[1,0]):t&&(t[1]+=+i)}});var p,c,d=n(u);return d?a>=s?(p="space",c=r(" ",d)):(p="tab",c=r(" ",d)):(p=null,c=""),{amount:d,type:p,indent:c}}},{repeating:437}],296:[function(t,n,r){!function(t,n){"use strict";"function"==typeof e&&e.amd?e(["exports"],n):n("undefined"!=typeof r?r:t.estraverse={})}(this,function l(e){"use strict";function t(){}function n(e){var t,r,l={};
for(t in e)e.hasOwnProperty(t)&&(r=e[t],l[t]="object"==typeof r&&null!==r?n(r):r);return l}function r(e){var t,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}function i(e,t){var n,r,l,i;for(r=e.length,l=0;r;)n=r>>>1,i=l+n,t(e[i])?r=n:(l=i+1,r-=n+1);return l}function s(e,t){var n,r,l,i;for(r=e.length,l=0;r;)n=r>>>1,i=l+n,t(e[i])?(l=i+1,r-=n+1):r=n;return l}function a(e,t){var n,r,l,i=_(t);for(r=0,l=i.length;l>r;r+=1)n=i[r],e[n]=t[n];return e}function o(e,t){this.parent=e,this.key=t}function u(e,t,n,r){this.node=e,this.path=t,this.wrap=n,this.ref=r}function p(){}function c(e){return null==e?!1:"object"==typeof e&&"string"==typeof e.type}function d(e,t){return(e===y.ObjectExpression||e===y.ObjectPattern)&&"properties"===t}function f(e,t){var n=new p;return n.traverse(e,t)}function h(e,t){var n=new p;return n.replace(e,t)}function m(e,t){var n;return n=i(t,function(t){return t.range[0]>e.range[0]}),e.extendedRange=[e.range[0],e.range[1]],n!==t.length&&(e.extendedRange[1]=t[n].range[0]),n-=1,n>=0&&(e.extendedRange[0]=t[n].range[1]),e}function g(e,t,r){var l,i,s,a,o=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(s=0,i=t.length;i>s;s+=1)l=n(t[s]),l.extendedRange=[0,e.range[0]],o.push(l);e.leadingComments=o}return e}for(s=0,i=t.length;i>s;s+=1)o.push(m(n(t[s]),r));return a=0,f(e,{enter:function(e){for(var t;a<o.length&&(t=o[a],!(t.extendedRange[1]>e.range[0]));)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),o.splice(a,1)):a+=1;return a===o.length?v.Break:o[a].extendedRange[0]>e.range[1]?v.Skip:void 0}}),a=0,f(e,{leave:function(e){for(var t;a<o.length&&(t=o[a],!(e.range[1]<t.extendedRange[0]));)e.range[1]===t.extendedRange[0]?(e.trailingComments||(e.trailingComments=[]),e.trailingComments.push(t),o.splice(a,1)):a+=1;return a===o.length?v.Break:o[a].extendedRange[0]>e.range[1]?v.Skip:void 0}}),e}var y,b,v,x,E,_,S,I,w;return b=Array.isArray,b||(b=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),t(r),t(s),E=Object.create||function(){function e(){}return function(t){return e.prototype=t,new e}}(),_=Object.keys||function(e){var t,n=[];for(t in e)n.push(t);return n},y={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},x={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},S={},I={},w={},v={Break:S,Skip:I,Remove:w},o.prototype.replace=function(e){this.parent[this.key]=e},o.prototype.remove=function(){return b(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},p.prototype.path=function(){function e(e,t){if(b(t))for(r=0,l=t.length;l>r;++r)e.push(t[r]);else e.push(t)}var t,n,r,l,i,s;if(!this.__current.path)return null;for(i=[],t=2,n=this.__leavelist.length;n>t;++t)s=this.__leavelist[t],e(i,s.path);return e(i,this.__current.path),i},p.prototype.type=function(){var e=this.current();return e.type||this.__current.wrap},p.prototype.parents=function(){var e,t,n;for(n=[],e=1,t=this.__leavelist.length;t>e;++e)n.push(this.__leavelist[e].node);return n},p.prototype.current=function(){return this.__current.node},p.prototype.__execute=function(e,t){var n,r;return r=void 0,n=this.__current,this.__current=t,this.__state=null,e&&(r=e.call(this,t.node,this.__leavelist[this.__leavelist.length-1].node)),this.__current=n,r},p.prototype.notify=function(e){this.__state=e},p.prototype.skip=function(){this.notify(I)},p.prototype["break"]=function(){this.notify(S)},p.prototype.remove=function(){this.notify(w)},p.prototype.__initialize=function(e,t){this.visitor=t,this.root=e,this.__worklist=[],this.__leavelist=[],this.__current=null,this.__state=null,this.__fallback="iteration"===t.fallback,this.__keys=x,t.keys&&(this.__keys=a(E(this.__keys),t.keys))},p.prototype.traverse=function(e,t){var n,r,l,i,s,a,o,p,f,h,m,g;for(this.__initialize(e,t),g={},n=this.__worklist,r=this.__leavelist,n.push(new u(e,null,null,null)),r.push(new u(null,null,null,null));n.length;)if(l=n.pop(),l!==g){if(l.node){if(a=this.__execute(t.enter,l),this.__state===S||a===S)return;if(n.push(g),r.push(l),this.__state===I||a===I)continue;if(i=l.node,s=l.wrap||i.type,h=this.__keys[s],!h){if(!this.__fallback)throw new Error("Unknown node type "+s+".");h=_(i)}for(p=h.length;(p-=1)>=0;)if(o=h[p],m=i[o])if(b(m)){for(f=m.length;(f-=1)>=0;)if(m[f]){if(d(s,h[p]))l=new u(m[f],[o,f],"Property",null);else{if(!c(m[f]))continue;l=new u(m[f],[o,f],null,null)}n.push(l)}}else c(m)&&n.push(new u(m,o,null,null))}}else if(l=r.pop(),a=this.__execute(t.leave,l),this.__state===S||a===S)return},p.prototype.replace=function(e,t){function n(e){var t,n,l,i;if(e.ref.remove())for(n=e.ref.key,i=e.ref.parent,t=r.length;t--;)if(l=r[t],l.ref&&l.ref.parent===i){if(l.ref.key<n)break;--l.ref.key}}var r,l,i,s,a,p,f,h,m,g,y,v,x;for(this.__initialize(e,t),y={},r=this.__worklist,l=this.__leavelist,v={root:e},p=new u(e,null,null,new o(v,"root")),r.push(p),l.push(p);r.length;)if(p=r.pop(),p!==y){if(a=this.__execute(t.enter,p),void 0!==a&&a!==S&&a!==I&&a!==w&&(p.ref.replace(a),p.node=a),(this.__state===w||a===w)&&(n(p),p.node=null),this.__state===S||a===S)return v.root;if(i=p.node,i&&(r.push(y),l.push(p),this.__state!==I&&a!==I)){if(s=p.wrap||i.type,m=this.__keys[s],!m){if(!this.__fallback)throw new Error("Unknown node type "+s+".");m=_(i)}for(f=m.length;(f-=1)>=0;)if(x=m[f],g=i[x])if(b(g)){for(h=g.length;(h-=1)>=0;)if(g[h]){if(d(s,m[f]))p=new u(g[h],[x,h],"Property",new o(g,h));else{if(!c(g[h]))continue;p=new u(g[h],[x,h],null,new o(g,h))}r.push(p)}}else c(g)&&r.push(new u(g,x,null,new o(i,x)))}}else if(p=l.pop(),a=this.__execute(t.leave,p),void 0!==a&&a!==S&&a!==I&&a!==w&&p.ref.replace(a),(this.__state===w||a===w)&&n(p),this.__state===S||a===S)return v.root;return v.root},e.version="1.8.1-dev",e.Syntax=y,e.traverse=f,e.replace=h,e.attachComments=g,e.VisitorKeys=x,e.VisitorOption=v,e.Controller=p,e.cloneEnvironment=function(){return l({})},e})},{}],297:[function(e,t){!function(){"use strict";function e(e){if(null==e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return!0}return!1}function n(e){if(null==e)return!1;switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return!0}return!1}function r(e){if(null==e)return!1;switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return!0}return!1}function l(e){return r(e)||null!=e&&"FunctionDeclaration"===e.type}function i(e){switch(e.type){case"IfStatement":return null!=e.alternate?e.alternate:e.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return e.body}return null}function s(e){var t;if("IfStatement"!==e.type)return!1;if(null==e.alternate)return!1;t=e.consequent;do{if("IfStatement"===t.type&&null==t.alternate)return!0;t=i(t)}while(t);return!1}t.exports={isExpression:e,isStatement:r,isIterationStatement:n,isSourceElement:l,isProblematicIfStatement:s,trailingStatement:i}}()},{}],298:[function(e,t){!function(){"use strict";function e(e){return e>=48&&57>=e}function n(t){return e(t)||t>=97&&102>=t||t>=65&&70>=t}function r(e){return e>=48&&55>=e}function l(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&u.indexOf(e)>=0}function i(e){return 10===e||13===e||8232===e||8233===e}function s(e){return e>=97&&122>=e||e>=65&&90>=e||36===e||95===e||92===e||e>=128&&o.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function a(e){return e>=97&&122>=e||e>=65&&90>=e||e>=48&&57>=e||36===e||95===e||92===e||e>=128&&o.NonAsciiIdentifierPart.test(String.fromCharCode(e))}var o,u;o={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},u=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],t.exports={isDecimalDigit:e,isHexDigit:n,isOctalDigit:r,isWhiteSpace:l,isLineTerminator:i,isIdentifierStart:s,isIdentifierPart:a}}()},{}],299:[function(e,t){!function(){"use strict";function n(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}function r(e,t){return t||"yield"!==e?l(e,t):!1}function l(e,t){if(t&&n(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function i(e,t){return"null"===e||"true"===e||"false"===e||r(e,t)}function s(e,t){return"null"===e||"true"===e||"false"===e||l(e,t)}function a(e){return"eval"===e||"arguments"===e}function o(e){var t,n,r;if(0===e.length)return!1;if(r=e.charCodeAt(0),!c.isIdentifierStart(r)||92===r)return!1;for(t=1,n=e.length;n>t;++t)if(r=e.charCodeAt(t),!c.isIdentifierPart(r)||92===r)return!1;return!0}function u(e,t){return o(e)&&!i(e,t)}function p(e,t){return o(e)&&!s(e,t)}var c=e("./code");t.exports={isKeywordES5:r,isKeywordES6:l,isReservedWordES5:i,isReservedWordES6:s,isRestrictedWord:a,isIdentifierName:o,isIdentifierES5:u,isIdentifierES6:p}}()},{"./code":298}],300:[function(e,t,n){!function(){"use strict";n.ast=e("./ast"),n.code=e("./code"),n.keyword=e("./keyword")}()},{"./ast":297,"./code":298,"./keyword":299}],301:[function(e,t){t.exports={builtin:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},nonstandard:{escape:!1,unescape:!1},browser:{addEventListener:!1,alert:!1,applicationCache:!1,atob:!1,Audio:!1,AudioProcessingEvent:!1,BeforeUnloadEvent:!1,Blob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,CloseEvent:!1,Comment:!1,CompositionEvent:!1,confirm:!1,console:!1,crypto:!1,CSS:!1,CustomEvent:!1,DataView:!1,Debug:!1,defaultStatus:!1,devicePixelRatio:!1,dispatchEvent:!1,document:!1,Document:!1,DocumentFragment:!1,DOMParser:!1,DragEvent:!1,Element:!1,ElementTimeControl:!1,ErrorEvent:!1,event:!1,Event:!1,FileReader:!1,fetch:!1,find:!1,focus:!1,FocusEvent:!1,FormData:!1,frameElement:!1,frames:!1,GamepadEvent:!1,getComputedStyle:!1,getSelection:!1,HashChangeEvent:!1,Headers:!1,history:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBEnvironment:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,Image:!1,indexedDB:!1,innerHeight:!1,innerWidth:!1,InputEvent:!1,Intl:!1,KeyboardEvent:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,navigator:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,OfflineAudioCompletionEvent:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,opera:!1,Option:!1,outerHeight:!1,outerWidth:!1,PageTransitionEvent:!1,pageXOffset:!1,pageYOffset:!1,parent:!1,PopStateEvent:!1,postMessage:!1,print:!1,ProgressEvent:!1,prompt:!1,Range:!1,Request:!1,Response:!1,removeEventListener:!1,requestAnimationFrame:!1,resizeBy:!1,resizeTo:!1,screen:!1,screenX:!1,screenY:!1,scroll:!1,scrollbars:!1,scrollBy:!1,scrollTo:!1,scrollX:!1,scrollY:!1,self:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,showModalDialog:!1,status:!1,stop:!1,StorageEvent:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimationElement:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCSSRule:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGEvent:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLinearGradientElement:!1,SVGLineElement:!1,SVGLocatable:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGMPathElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSVGElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformable:!1,SVGTransformList:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGUnitTypes:!1,SVGURIReference:!1,SVGUseElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGVKernElement:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,TouchEvent:!1,UIEvent:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,WheelEvent:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},worker:{importScripts:!0,postMessage:!0,self:!0},node:{__dirname:!1,__filename:!1,arguments:!1,Buffer:!1,clearImmediate:!1,clearInterval:!1,clearTimeout:!1,console:!1,DataView:!1,exports:!0,GLOBAL:!1,global:!1,module:!1,process:!1,require:!1,setImmediate:!1,setInterval:!1,setTimeout:!1},amd:{define:!1,require:!1},mocha:{after:!1,afterEach:!1,before:!1,beforeEach:!1,context:!1,describe:!1,it:!1,setup:!1,specify:!1,suite:!1,suiteSetup:!1,suiteTeardown:!1,teardown:!1,test:!1,xcontext:!1,xdescribe:!1,xit:!1,xspecify:!1},jasmine:{afterAll:!1,afterEach:!1,beforeAll:!1,beforeEach:!1,describe:!1,expect:!1,fail:!1,fdescribe:!1,fit:!1,it:!1,jasmine:!1,pending:!1,runs:!1,spyOn:!1,waits:!1,waitsFor:!1,xdescribe:!1,xit:!1},qunit:{asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,"throws":!1},phantomjs:{console:!0,exports:!0,phantom:!0,require:!0,WebPage:!0},couch:{emit:!1,exports:!1,getRow:!1,log:!1,module:!1,provides:!1,require:!1,respond:!1,send:!1,start:!1,sum:!1},rhino:{defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},wsh:{ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WScript:!0,WSH:!0,XDomainRequest:!0},jquery:{$:!1,jQuery:!1},yui:{Y:!1,YUI:!1,YUI_config:!1},shelljs:{cat:!1,cd:!1,chmod:!1,config:!1,cp:!1,dirs:!1,echo:!1,env:!1,error:!1,exec:!1,exit:!1,find:!1,grep:!1,ls:!1,mkdir:!1,mv:!1,popd:!1,pushd:!1,pwd:!1,rm:!1,sed:!1,target:!1,tempdir:!1,test:!1,which:!1},prototypejs:{$:!1,$$:!1,$A:!1,$break:!1,$continue:!1,$F:!1,$H:!1,$R:!1,$w:!1,Abstract:!1,Ajax:!1,Autocompleter:!1,Builder:!1,Class:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Element:!1,Enumerable:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Scriptaculous:!1,Selector:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Template:!1,Toggle:!1,Try:!1},meteor:{$:!1,_:!1,Accounts:!1,App:!1,Assets:!1,Blaze:!1,check:!1,Cordova:!1,DDP:!1,DDPServer:!1,Deps:!1,EJSON:!1,Email:!1,HTTP:!1,Log:!1,Match:!1,Meteor:!1,Mongo:!1,MongoInternals:!1,Npm:!1,Package:!1,Plugin:!1,process:!1,Random:!1,ReactiveDict:!1,ReactiveVar:!1,Router:!1,Session:!1,share:!1,Spacebars:!1,Template:!1,Tinytest:!1,Tracker:!1,UI:!1,Utils:!1,WebApp:!1,WebAppInternals:!1},mongo:{_isWindows:!1,_rand:!1,BulkWriteResult:!1,cat:!1,cd:!1,connect:!1,db:!1,getHostName:!1,getMemInfo:!1,hostname:!1,listFiles:!1,load:!1,ls:!1,md5sumFile:!1,mkdir:!1,Mongo:!1,ObjectId:!1,PlanCache:!1,pwd:!1,quit:!1,removeFile:!1,rs:!1,sh:!1,UUID:!1,version:!1,WriteResult:!1},applescript:{$:!1,Application:!1,Automation:!1,console:!1,delay:!1,Library:!1,ObjC:!1,ObjectSpecifier:!1,Path:!1,Progress:!1,Ref:!1}}},{}],302:[function(e,t){t.exports=e("./globals.json")},{"./globals.json":301}],303:[function(e,t){var n=e("is-nan"),r=e("is-finite");t.exports=Number.isInteger||function(e){return"number"==typeof e&&!n(e)&&r(e)&&parseInt(e,10)===e}},{"is-finite":304,"is-nan":305}],304:[function(e,t){"use strict";t.exports=Number.isFinite||function(e){return"number"!=typeof e||e!==e||1/0===e||e===-1/0?!1:!0}},{}],305:[function(e,t){"use strict";t.exports=function(e){return e!==e}},{}],306:[function(e,t){t.exports=/((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|((?:0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?))|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]{1,6}\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-*\/%&|^]|<{1,2}|>{1,3}|!=?|={1,2})=?|[?:~]|[;,.[\](){}])|(\s+)|(^$|[\s\S])/g,t.exports.matchToToken=function(e){return token={type:"invalid",value:e[0]},e[1]?(token.type="string",token.closed=!(!e[3]&&!e[4])):e[5]?token.type="comment":e[6]?(token.type="comment",token.closed=!!e[7]):e[8]?token.type="regex":e[9]?token.type="number":e[10]?token.type="name":e[11]?token.type="punctuator":e[12]&&(token.type="whitespace"),token}},{}],307:[function(e,t){var n=[],r=[];t.exports=function(e,t){if(e===t)return 0;var l=e.length,i=t.length;if(0===l)return i;if(0===i)return l;for(var s,a,o,u,p=0,c=0;l>p;)r[p]=e.charCodeAt(p),n[p]=++p;for(;i>c;)for(s=t.charCodeAt(c),o=c++,a=c,p=0;l>p;p++)u=s===r[p]?o:o+1,o=n[p],a=n[p]=o>a?u>a?a+1:u:u>o?o+1:u;return a}},{}],308:[function(e,t){function n(e,t,n){return t in e?e[t]:n}function r(e,t){var r=n.bind(null,t||{}),i=r("transform",Function.prototype),s=r("padding"," "),a=r("before"," "),o=r("after"," | "),u=r("start",1),p=Array.isArray(e),c=p?e:e.split("\n"),d=u+c.length-1,f=String(d).length,h=c.map(function(e,t){var n=u+t,r={before:a,number:n,width:f,after:o,line:e};return i(r),r.before+l(r.number,f,s)+r.after+r.line});return p?h:h.join("\n")}var l=e("left-pad");t.exports=r},{"left-pad":309}],309:[function(e,t){function n(e,t,n){e=String(e);var r=-1;for(n||(n=" "),t-=e.length;++r<t;)e=n+e;return e}t.exports=n},{}],310:[function(e,t){function n(e){for(var t=-1,n=e?e.length:0,r=-1,l=[];++t<n;){var i=e[t];i&&(l[++r]=i)}return l}t.exports=n},{}],311:[function(e,t){function n(e,t,n){var i=e?e.length:0;return n&&l(e,t,n)&&(t=!1),i?r(e,t):[]}var r=e("../internal/baseFlatten"),l=e("../internal/isIterateeCall");t.exports=n},{"../internal/baseFlatten":339,"../internal/isIterateeCall":382}],312:[function(e,t){function n(e){var t=e?e.length:0;return t?e[t-1]:void 0}t.exports=n},{}],313:[function(e,t){function n(){var e=arguments,t=e[0];if(!t||!t.length)return t;for(var n=0,l=r,s=e.length;++n<s;)for(var a=0,o=e[n];(a=l(t,o,a))>-1;)i.call(t,a,1);return t}var r=e("../internal/baseIndexOf"),l=Array.prototype,i=l.splice;t.exports=n},{"../internal/baseIndexOf":345}],314:[function(e,t){function n(e,t,n,a){var o=e?e.length:0;return o?(null!=t&&"boolean"!=typeof t&&(a=n,n=i(e,t,a)?null:t,t=!1),n=null==n?n:r(n,a,3),t?s(e,n):l(e,n)):[]}var r=e("../internal/baseCallback"),l=e("../internal/baseUniq"),i=e("../internal/isIterateeCall"),s=e("../internal/sortedUniq");t.exports=n},{"../internal/baseCallback":333,"../internal/baseUniq":360,"../internal/isIterateeCall":382,"../internal/sortedUniq":388}],315:[function(e,t){t.exports=e("./includes")},{"./includes":319}],316:[function(e,t){t.exports=e("./forEach")},{"./forEach":317}],317:[function(e,t){var n=e("../internal/arrayEach"),r=e("../internal/baseEach"),l=e("../internal/createForEach"),i=l(n,r);t.exports=i},{"../internal/arrayEach":327,"../internal/baseEach":337,"../internal/createForEach":372}],318:[function(e,t){var n=e("../internal/createAggregator"),r=Object.prototype,l=r.hasOwnProperty,i=n(function(e,t,n){l.call(e,n)?e[n].push(t):e[n]=[t]});t.exports=i},{"../internal/createAggregator":367}],319:[function(e,t){function n(e,t,n,p){var c=e?e.length:0;return s(c)||(e=o(e),c=e.length),c?(n="number"!=typeof n||p&&i(t,n,p)?0:0>n?u(c+n,0):n||0,"string"==typeof e||!l(e)&&a(e)?c>n&&e.indexOf(t,n)>-1:r(e,t,n)>-1):!1}var r=e("../internal/baseIndexOf"),l=e("../lang/isArray"),i=e("../internal/isIterateeCall"),s=e("../internal/isLength"),a=e("../lang/isString"),o=e("../object/values"),u=Math.max;
t.exports=n},{"../internal/baseIndexOf":345,"../internal/isIterateeCall":382,"../internal/isLength":383,"../lang/isArray":392,"../lang/isString":401,"../object/values":411}],320:[function(e,t){function n(e,t,n){var a=s(e)?r:i;return t=l(t,n,3),a(e,t)}var r=e("../internal/arrayMap"),l=e("../internal/baseCallback"),i=e("../internal/baseMap"),s=e("../lang/isArray");t.exports=n},{"../internal/arrayMap":328,"../internal/baseCallback":333,"../internal/baseMap":350,"../lang/isArray":392}],321:[function(e,t){var n=e("../internal/arrayReduceRight"),r=e("../internal/baseEachRight"),l=e("../internal/createReduce"),i=l(n,r);t.exports=i},{"../internal/arrayReduceRight":329,"../internal/baseEachRight":338,"../internal/createReduce":373}],322:[function(e,t){function n(e,t,n){var o=s(e)?r:i;return n&&a(e,t,n)&&(t=null),("function"!=typeof t||"undefined"!=typeof n)&&(t=l(t,n,3)),o(e,t)}var r=e("../internal/arraySome"),l=e("../internal/baseCallback"),i=e("../internal/baseSome"),s=e("../lang/isArray"),a=e("../internal/isIterateeCall");t.exports=n},{"../internal/arraySome":330,"../internal/baseCallback":333,"../internal/baseSome":357,"../internal/isIterateeCall":382,"../lang/isArray":392}],323:[function(e,t){function n(e,t,n){if(null==e)return[];var u=-1,p=e.length,c=o(p)?Array(p):[];return n&&a(e,t,n)&&(t=null),t=r(t,n,3),l(e,function(e,n,r){c[++u]={criteria:t(e,n,r),index:u,value:e}}),i(c,s)}var r=e("../internal/baseCallback"),l=e("../internal/baseEach"),i=e("../internal/baseSortBy"),s=e("../internal/compareAscending"),a=e("../internal/isIterateeCall"),o=e("../internal/isLength");t.exports=n},{"../internal/baseCallback":333,"../internal/baseEach":337,"../internal/baseSortBy":358,"../internal/compareAscending":366,"../internal/isIterateeCall":382,"../internal/isLength":383}],324:[function(e,t){function n(e,t){if("function"!=typeof e)throw new TypeError(r);return t=l("undefined"==typeof t?e.length-1:+t||0,0),function(){for(var n=arguments,r=-1,i=l(n.length-t,0),s=Array(i);++r<i;)s[r]=n[t+r];switch(t){case 0:return e.call(this,s);case 1:return e.call(this,n[0],s);case 2:return e.call(this,n[0],n[1],s)}var a=Array(t+1);for(r=-1;++r<t;)a[r]=n[r];return a[t]=s,e.apply(this,a)}}var r="Expected a function",l=Math.max;t.exports=n},{}],325:[function(e,t){(function(n){function r(e){var t=e?e.length:0;for(this.data={hash:a(null),set:new s};t--;)this.push(e[t])}var l=e("./cachePush"),i=e("../lang/isNative"),s=i(s=n.Set)&&s,a=i(a=Object.create)&&a;r.prototype.push=l,t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":396,"./cachePush":365}],326:[function(e,t){function n(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}t.exports=n},{}],327:[function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}t.exports=n},{}],328:[function(e,t){function n(e,t){for(var n=-1,r=e.length,l=Array(r);++n<r;)l[n]=t(e[n],n,e);return l}t.exports=n},{}],329:[function(e,t){function n(e,t,n,r){var l=e.length;for(r&&l&&(n=e[--l]);l--;)n=t(n,e[l],l,e);return n}t.exports=n},{}],330:[function(e,t){function n(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}t.exports=n},{}],331:[function(e,t){function n(e,t){return"undefined"==typeof e?t:e}t.exports=n},{}],332:[function(e,t){function n(e,t,n){var i=l(t);if(!n)return r(t,e,i);for(var s=-1,a=i.length;++s<a;){var o=i[s],u=e[o],p=n(u,t[o],o,e,t);(p===p?p===u:u!==u)&&("undefined"!=typeof u||o in e)||(e[o]=p)}return e}var r=e("./baseCopy"),l=e("../object/keys");t.exports=n},{"../object/keys":408,"./baseCopy":336}],333:[function(e,t){function n(e,t,n){var o=typeof e;return"function"==o?"undefined"==typeof t?e:s(e,t,n):null==e?a:"object"==o?r(e):"undefined"==typeof t?i(e+""):l(e+"",t)}var r=e("./baseMatches"),l=e("./baseMatchesProperty"),i=e("./baseProperty"),s=e("./bindCallback"),a=e("../utility/identity");t.exports=n},{"../utility/identity":415,"./baseMatches":351,"./baseMatchesProperty":352,"./baseProperty":355,"./bindCallback":362}],334:[function(e,t){function n(e,t,h,m,g,y,v){var x;if(h&&(x=g?h(e,m,g):h(e)),"undefined"!=typeof x)return x;if(!c(e))return e;var _=p(e);if(_){if(x=a(e),!t)return r(e,x)}else{var S=F.call(e),I=S==b;if(S!=E&&S!=f&&(!I||g))return R[S]?o(e,S,t):g?e:{};if(x=u(I?{}:e),!t)return i(e,x,d(e))}y||(y=[]),v||(v=[]);for(var w=y.length;w--;)if(y[w]==e)return v[w];return y.push(e),v.push(x),(_?l:s)(e,function(r,l){x[l]=n(r,t,h,l,e,y,v)}),x}var r=e("./arrayCopy"),l=e("./arrayEach"),i=e("./baseCopy"),s=e("./baseForOwn"),a=e("./initCloneArray"),o=e("./initCloneByTag"),u=e("./initCloneObject"),p=e("../lang/isArray"),c=e("../lang/isObject"),d=e("../object/keys"),f="[object Arguments]",h="[object Array]",m="[object Boolean]",g="[object Date]",y="[object Error]",b="[object Function]",v="[object Map]",x="[object Number]",E="[object Object]",_="[object RegExp]",S="[object Set]",I="[object String]",w="[object WeakMap]",k="[object ArrayBuffer]",A="[object Float32Array]",C="[object Float64Array]",T="[object Int8Array]",j="[object Int16Array]",M="[object Int32Array]",P="[object Uint8Array]",L="[object Uint8ClampedArray]",O="[object Uint16Array]",D="[object Uint32Array]",R={};R[f]=R[h]=R[k]=R[m]=R[g]=R[A]=R[C]=R[T]=R[j]=R[M]=R[x]=R[E]=R[_]=R[I]=R[P]=R[L]=R[O]=R[D]=!0,R[y]=R[b]=R[v]=R[S]=R[w]=!1;var N=Object.prototype,F=N.toString;t.exports=n},{"../lang/isArray":392,"../lang/isObject":398,"../object/keys":408,"./arrayCopy":326,"./arrayEach":327,"./baseCopy":336,"./baseForOwn":342,"./initCloneArray":378,"./initCloneByTag":379,"./initCloneObject":380}],335:[function(e,t){function n(e,t){if(e!==t){var n=e===e,r=t===t;if(e>t||!n||"undefined"==typeof e&&r)return 1;if(t>e||!r||"undefined"==typeof t&&n)return-1}return 0}t.exports=n},{}],336:[function(e,t){function n(e,t,n){n||(n=t,t={});for(var r=-1,l=n.length;++r<l;){var i=n[r];t[i]=e[i]}return t}t.exports=n},{}],337:[function(e,t){var n=e("./baseForOwn"),r=e("./createBaseEach"),l=r(n);t.exports=l},{"./baseForOwn":342,"./createBaseEach":369}],338:[function(e,t){var n=e("./baseForOwnRight"),r=e("./createBaseEach"),l=r(n,!0);t.exports=l},{"./baseForOwnRight":343,"./createBaseEach":369}],339:[function(e,t){function n(e,t,a){for(var o=-1,u=e.length,p=-1,c=[];++o<u;){var d=e[o];if(s(d)&&i(d.length)&&(l(d)||r(d))){t&&(d=n(d,t,a));var f=-1,h=d.length;for(c.length+=h;++f<h;)c[++p]=d[f]}else a||(c[++p]=d)}return c}var r=e("../lang/isArguments"),l=e("../lang/isArray"),i=e("./isLength"),s=e("./isObjectLike");t.exports=n},{"../lang/isArguments":391,"../lang/isArray":392,"./isLength":383,"./isObjectLike":384}],340:[function(e,t){var n=e("./createBaseFor"),r=n();t.exports=r},{"./createBaseFor":370}],341:[function(e,t){function n(e,t){return r(e,t,l)}var r=e("./baseFor"),l=e("../object/keysIn");t.exports=n},{"../object/keysIn":409,"./baseFor":340}],342:[function(e,t){function n(e,t){return r(e,t,l)}var r=e("./baseFor"),l=e("../object/keys");t.exports=n},{"../object/keys":408,"./baseFor":340}],343:[function(e,t){function n(e,t){return r(e,t,l)}var r=e("./baseForRight"),l=e("../object/keys");t.exports=n},{"../object/keys":408,"./baseForRight":344}],344:[function(e,t){var n=e("./createBaseFor"),r=n(!0);t.exports=r},{"./createBaseFor":370}],345:[function(e,t){function n(e,t,n){if(t!==t)return r(e,n);for(var l=n-1,i=e.length;++l<i;)if(e[l]===t)return l;return-1}var r=e("./indexOfNaN");t.exports=n},{"./indexOfNaN":377}],346:[function(e,t){function n(e,t,l,i,s,a){if(e===t)return 0!==e||1/e==1/t;var o=typeof e,u=typeof t;return"function"!=o&&"object"!=o&&"function"!=u&&"object"!=u||null==e||null==t?e!==e&&t!==t:r(e,t,n,l,i,s,a)}var r=e("./baseIsEqualDeep");t.exports=n},{"./baseIsEqualDeep":347}],347:[function(e,t){function n(e,t,n,d,m,g,y){var b=s(e),v=s(t),x=u,E=u;b||(x=h.call(e),x==o?x=c:x!=c&&(b=a(e))),v||(E=h.call(t),E==o?E=c:E!=c&&(v=a(t)));var _=x==c||m&&x==p,S=E==c||m&&E==p,I=x==E;if(I&&!b&&!_)return l(e,t,x);if(m){if(!(I||_&&S))return!1}else{var w=_&&f.call(e,"__wrapped__"),k=S&&f.call(t,"__wrapped__");if(w||k)return n(w?e.value():e,k?t.value():t,d,m,g,y);if(!I)return!1}g||(g=[]),y||(y=[]);for(var A=g.length;A--;)if(g[A]==e)return y[A]==t;g.push(e),y.push(t);var C=(b?r:i)(e,t,n,d,m,g,y);return g.pop(),y.pop(),C}var r=e("./equalArrays"),l=e("./equalByTag"),i=e("./equalObjects"),s=e("../lang/isArray"),a=e("../lang/isTypedArray"),o="[object Arguments]",u="[object Array]",p="[object Function]",c="[object Object]",d=Object.prototype,f=d.hasOwnProperty,h=d.toString;t.exports=n},{"../lang/isArray":392,"../lang/isTypedArray":402,"./equalArrays":374,"./equalByTag":375,"./equalObjects":376}],348:[function(e,t){function n(e){return"function"==typeof e||!1}t.exports=n},{}],349:[function(e,t){function n(e,t,n,l,i){for(var s=-1,a=t.length,o=!i;++s<a;)if(o&&l[s]?n[s]!==e[t[s]]:!(t[s]in e))return!1;for(s=-1;++s<a;){var u=t[s],p=e[u],c=n[s];if(o&&l[s])var d="undefined"!=typeof p||u in e;else d=i?i(p,c,u):void 0,"undefined"==typeof d&&(d=r(c,p,i,!0));if(!d)return!1}return!0}var r=e("./baseIsEqual");t.exports=n},{"./baseIsEqual":346}],350:[function(e,t){function n(e,t){var n=[];return r(e,function(e,r,l){n.push(t(e,r,l))}),n}var r=e("./baseEach");t.exports=n},{"./baseEach":337}],351:[function(e,t){function n(e){var t=s(e),n=t.length;if(!n)return l(!0);if(1==n){var o=t[0],u=e[o];if(i(u))return function(e){return null!=e&&e[o]===u&&("undefined"!=typeof u||o in a(e))}}for(var p=Array(n),c=Array(n);n--;)u=e[t[n]],p[n]=u,c[n]=i(u);return function(e){return null!=e&&r(a(e),t,p,c)}}var r=e("./baseIsMatch"),l=e("../utility/constant"),i=e("./isStrictComparable"),s=e("../object/keys"),a=e("./toObject");t.exports=n},{"../object/keys":408,"../utility/constant":414,"./baseIsMatch":349,"./isStrictComparable":385,"./toObject":389}],352:[function(e,t){function n(e,t){return l(t)?function(n){return null!=n&&n[e]===t&&("undefined"!=typeof t||e in i(n))}:function(n){return null!=n&&r(t,n[e],null,!0)}}var r=e("./baseIsEqual"),l=e("./isStrictComparable"),i=e("./toObject");t.exports=n},{"./baseIsEqual":346,"./isStrictComparable":385,"./toObject":389}],353:[function(e,t){function n(e,t,c,d,f){if(!o(e))return e;var h=a(t.length)&&(s(t)||p(t));return(h?r:l)(t,function(t,r,l){if(u(t))return d||(d=[]),f||(f=[]),i(e,l,r,n,c,d,f);var s=e[r],a=c?c(s,t,r,e,l):void 0,o="undefined"==typeof a;o&&(a=t),!h&&"undefined"==typeof a||!o&&(a===a?a===s:s!==s)||(e[r]=a)}),e}var r=e("./arrayEach"),l=e("./baseForOwn"),i=e("./baseMergeDeep"),s=e("../lang/isArray"),a=e("./isLength"),o=e("../lang/isObject"),u=e("./isObjectLike"),p=e("../lang/isTypedArray");t.exports=n},{"../lang/isArray":392,"../lang/isObject":398,"../lang/isTypedArray":402,"./arrayEach":327,"./baseForOwn":342,"./baseMergeDeep":354,"./isLength":383,"./isObjectLike":384}],354:[function(e,t){function n(e,t,n,p,c,d,f){for(var h=d.length,m=t[n];h--;)if(d[h]==m)return void(e[n]=f[h]);var g=e[n],y=c?c(g,m,n,e,t):void 0,b="undefined"==typeof y;b&&(y=m,s(m.length)&&(i(m)||o(m))?y=i(g)?g:g&&g.length?r(g):[]:a(m)||l(m)?y=l(g)?u(g):a(g)?g:{}:b=!1),d.push(m),f.push(y),b?e[n]=p(y,m,c,d,f):(y===y?y!==g:g===g)&&(e[n]=y)}var r=e("./arrayCopy"),l=e("../lang/isArguments"),i=e("../lang/isArray"),s=e("./isLength"),a=e("../lang/isPlainObject"),o=e("../lang/isTypedArray"),u=e("../lang/toPlainObject");t.exports=n},{"../lang/isArguments":391,"../lang/isArray":392,"../lang/isPlainObject":399,"../lang/isTypedArray":402,"../lang/toPlainObject":403,"./arrayCopy":326,"./isLength":383}],355:[function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}t.exports=n},{}],356:[function(e,t){function n(e,t,n,r,l){return l(e,function(e,l,i){n=r?(r=!1,e):t(n,e,l,i)}),n}t.exports=n},{}],357:[function(e,t){function n(e,t){var n;return r(e,function(e,r,l){return n=t(e,r,l),!n}),!!n}var r=e("./baseEach");t.exports=n},{"./baseEach":337}],358:[function(e,t){function n(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}t.exports=n},{}],359:[function(e,t){function n(e){return"string"==typeof e?e:null==e?"":e+""}t.exports=n},{}],360:[function(e,t){function n(e,t){var n=-1,s=r,a=e.length,o=!0,u=o&&a>=200,p=u?i():null,c=[];p?(s=l,o=!1):(u=!1,p=t?[]:c);e:for(;++n<a;){var d=e[n],f=t?t(d,n,e):d;if(o&&d===d){for(var h=p.length;h--;)if(p[h]===f)continue e;t&&p.push(f),c.push(d)}else s(p,f,0)<0&&((t||u)&&p.push(f),c.push(d))}return c}var r=e("./baseIndexOf"),l=e("./cacheIndexOf"),i=e("./createCache");t.exports=n},{"./baseIndexOf":345,"./cacheIndexOf":364,"./createCache":371}],361:[function(e,t){function n(e,t){for(var n=-1,r=t.length,l=Array(r);++n<r;)l[n]=e[t[n]];return l}t.exports=n},{}],362:[function(e,t){function n(e,t,n){if("function"!=typeof e)return r;if("undefined"==typeof t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,l){return e.call(t,n,r,l)};case 4:return function(n,r,l,i){return e.call(t,n,r,l,i)};case 5:return function(n,r,l,i,s){return e.call(t,n,r,l,i,s)}}return function(){return e.apply(t,arguments)}}var r=e("../utility/identity");t.exports=n},{"../utility/identity":415}],363:[function(e,t){(function(n){function r(e){return a.call(e,0)}var l=e("../utility/constant"),i=e("../lang/isNative"),s=i(s=n.ArrayBuffer)&&s,a=i(a=s&&new s(0).slice)&&a,o=Math.floor,u=i(u=n.Uint8Array)&&u,p=function(){try{var e=i(e=n.Float64Array)&&e,t=new e(new s(10),0,1)&&e}catch(r){}return t}(),c=p?p.BYTES_PER_ELEMENT:0;a||(r=s&&u?function(e){var t=e.byteLength,n=p?o(t/c):0,r=n*c,l=new s(t);if(n){var i=new p(l,0,n);i.set(new p(e,0,n))}return t!=r&&(i=new u(l,r),i.set(new u(e,r))),l}:l(null)),t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":396,"../utility/constant":414}],364:[function(e,t){function n(e,t){var n=e.data,l="string"==typeof t||r(t)?n.set.has(t):n.hash[t];return l?0:-1}var r=e("../lang/isObject");t.exports=n},{"../lang/isObject":398}],365:[function(e,t){function n(e){var t=this.data;"string"==typeof e||r(e)?t.set.add(e):t.hash[e]=!0}var r=e("../lang/isObject");t.exports=n},{"../lang/isObject":398}],366:[function(e,t){function n(e,t){return r(e.criteria,t.criteria)||e.index-t.index}var r=e("./baseCompareAscending");t.exports=n},{"./baseCompareAscending":335}],367:[function(e,t){function n(e,t){return function(n,s,a){var o=t?t():{};if(s=r(s,a,3),i(n))for(var u=-1,p=n.length;++u<p;){var c=n[u];e(o,c,s(c,u,n),n)}else l(n,function(t,n,r){e(o,t,s(t,n,r),r)});return o}}var r=e("./baseCallback"),l=e("./baseEach"),i=e("../lang/isArray");t.exports=n},{"../lang/isArray":392,"./baseCallback":333,"./baseEach":337}],368:[function(e,t){function n(e){return function(){var t=arguments,n=t.length,i=t[0];if(2>n||null==i)return i;var s=t[n-2],a=t[n-1],o=t[3];n>3&&"function"==typeof s?(s=r(s,a,5),n-=2):(s=n>2&&"function"==typeof a?a:null,n-=s?1:0),o&&l(t[1],t[2],o)&&(s=3==n?null:s,n=2);for(var u=0;++u<n;){var p=t[u];p&&e(i,p,s)}return i}}var r=e("./bindCallback"),l=e("./isIterateeCall");t.exports=n},{"./bindCallback":362,"./isIterateeCall":382}],369:[function(e,t){function n(e,t){return function(n,i){var s=n?n.length:0;if(!r(s))return e(n,i);for(var a=t?s:-1,o=l(n);(t?a--:++a<s)&&i(o[a],a,o)!==!1;);return n}}var r=e("./isLength"),l=e("./toObject");t.exports=n},{"./isLength":383,"./toObject":389}],370:[function(e,t){function n(e){return function(t,n,l){for(var i=r(t),s=l(t),a=s.length,o=e?a:-1;e?o--:++o<a;){var u=s[o];if(n(i[u],u,i)===!1)break}return t}}var r=e("./toObject");t.exports=n},{"./toObject":389}],371:[function(e,t){(function(n){var r=e("./SetCache"),l=e("../utility/constant"),i=e("../lang/isNative"),s=i(s=n.Set)&&s,a=i(a=Object.create)&&a,o=a&&s?function(e){return new r(e)}:l(null);t.exports=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../lang/isNative":396,"../utility/constant":414,"./SetCache":325}],372:[function(e,t){function n(e,t){return function(n,i,s){return"function"==typeof i&&"undefined"==typeof s&&l(n)?e(n,i):t(n,r(i,s,3))}}var r=e("./bindCallback"),l=e("../lang/isArray");t.exports=n},{"../lang/isArray":392,"./bindCallback":362}],373:[function(e,t){function n(e,t){return function(n,s,a,o){var u=arguments.length<3;return"function"==typeof s&&"undefined"==typeof o&&i(n)?e(n,s,a,u):l(n,r(s,o,4),a,u,t)}}var r=e("./baseCallback"),l=e("./baseReduce"),i=e("../lang/isArray");t.exports=n},{"../lang/isArray":392,"./baseCallback":333,"./baseReduce":356}],374:[function(e,t){function n(e,t,n,r,l,i,s){var a=-1,o=e.length,u=t.length,p=!0;if(o!=u&&!(l&&u>o))return!1;for(;p&&++a<o;){var c=e[a],d=t[a];if(p=void 0,r&&(p=l?r(d,c,a):r(c,d,a)),"undefined"==typeof p)if(l)for(var f=u;f--&&(d=t[f],!(p=c&&c===d||n(c,d,r,l,i,s))););else p=c&&c===d||n(c,d,r,l,i,s)}return!!p}t.exports=n},{}],375:[function(e,t){function n(e,t,n){switch(n){case r:case l:return+e==+t;case i:return e.name==t.name&&e.message==t.message;case s:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case a:case o:return e==t+""}return!1}var r="[object Boolean]",l="[object Date]",i="[object Error]",s="[object Number]",a="[object RegExp]",o="[object String]";t.exports=n},{}],376:[function(e,t){function n(e,t,n,l,s,a,o){var u=r(e),p=u.length,c=r(t),d=c.length;if(p!=d&&!s)return!1;for(var f=s,h=-1;++h<p;){var m=u[h],g=s?m in t:i.call(t,m);if(g){var y=e[m],b=t[m];g=void 0,l&&(g=s?l(b,y,m):l(y,b,m)),"undefined"==typeof g&&(g=y&&y===b||n(y,b,l,s,a,o))}if(!g)return!1;f||(f="constructor"==m)}if(!f){var v=e.constructor,x=t.constructor;if(v!=x&&"constructor"in e&&"constructor"in t&&!("function"==typeof v&&v instanceof v&&"function"==typeof x&&x instanceof x))return!1}return!0}var r=e("../object/keys"),l=Object.prototype,i=l.hasOwnProperty;t.exports=n},{"../object/keys":408}],377:[function(e,t){function n(e,t,n){for(var r=e.length,l=t+(n?0:-1);n?l--:++l<r;){var i=e[l];if(i!==i)return l}return-1}t.exports=n},{}],378:[function(e,t){function n(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&l.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var r=Object.prototype,l=r.hasOwnProperty;t.exports=n},{}],379:[function(e,t){function n(e,t,n){var x=e.constructor;switch(t){case u:return r(e);case l:case i:return new x(+e);case p:case c:case d:case f:case h:case m:case g:case y:case b:var E=e.buffer;return new x(n?r(E):E,e.byteOffset,e.length);case s:case o:return new x(e);case a:var _=new x(e.source,v.exec(e));_.lastIndex=e.lastIndex}return _}var r=e("./bufferClone"),l="[object Boolean]",i="[object Date]",s="[object Number]",a="[object RegExp]",o="[object String]",u="[object ArrayBuffer]",p="[object Float32Array]",c="[object Float64Array]",d="[object Int8Array]",f="[object Int16Array]",h="[object Int32Array]",m="[object Uint8Array]",g="[object Uint8ClampedArray]",y="[object Uint16Array]",b="[object Uint32Array]",v=/\w*$/;t.exports=n},{"./bufferClone":363}],380:[function(e,t){function n(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}t.exports=n},{}],381:[function(e,t){function n(e,t){return e=+e,t=null==t?r:t,e>-1&&e%1==0&&t>e}var r=Math.pow(2,53)-1;t.exports=n},{}],382:[function(e,t){function n(e,t,n){if(!i(n))return!1;var s=typeof t;if("number"==s)var a=n.length,o=l(a)&&r(t,a);else o="string"==s&&t in n;if(o){var u=n[t];return e===e?e===u:u!==u}return!1}var r=e("./isIndex"),l=e("./isLength"),i=e("../lang/isObject");t.exports=n},{"../lang/isObject":398,"./isIndex":381,"./isLength":383}],383:[function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&r>=e}var r=Math.pow(2,53)-1;t.exports=n},{}],384:[function(e,t){function n(e){return!!e&&"object"==typeof e}t.exports=n},{}],385:[function(e,t){function n(e){return e===e&&(0===e?1/e>0:!r(e))}var r=e("../lang/isObject");t.exports=n},{"../lang/isObject":398}],386:[function(e,t){function n(e){var t;if(!l(e)||o.call(e)!=i||!a.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t)))return!1;var n;return r(e,function(e,t){n=t}),"undefined"==typeof n||a.call(e,n)}var r=e("./baseForIn"),l=e("./isObjectLike"),i="[object Object]",s=Object.prototype,a=s.hasOwnProperty,o=s.toString;t.exports=n},{"./baseForIn":341,"./isObjectLike":384}],387:[function(e,t){function n(e){for(var t=a(e),n=t.length,u=n&&e.length,c=u&&s(u)&&(l(e)||o.nonEnumArgs&&r(e)),d=-1,f=[];++d<n;){var h=t[d];(c&&i(h,u)||p.call(e,h))&&f.push(h)}return f}var r=e("../lang/isArguments"),l=e("../lang/isArray"),i=e("./isIndex"),s=e("./isLength"),a=e("../object/keysIn"),o=e("../support"),u=Object.prototype,p=u.hasOwnProperty;t.exports=n},{"../lang/isArguments":391,"../lang/isArray":392,"../object/keysIn":409,"../support":413,"./isIndex":381,"./isLength":383}],388:[function(e,t){function n(e,t){for(var n,r=-1,l=e.length,i=-1,s=[];++r<l;){var a=e[r],o=t?t(a,r,e):a;r&&n===o||(n=o,s[++i]=a)}return s}t.exports=n},{}],389:[function(e,t){function n(e){return r(e)?e:Object(e)}var r=e("../lang/isObject");t.exports=n},{"../lang/isObject":398}],390:[function(e,t){function n(e,t,n){return t="function"==typeof t&&l(t,n,1),r(e,!0,t)}var r=e("../internal/baseClone"),l=e("../internal/bindCallback");t.exports=n},{"../internal/baseClone":334,"../internal/bindCallback":362}],391:[function(e,t){function n(e){var t=l(e)?e.length:void 0;return r(t)&&a.call(e)==i}var r=e("../internal/isLength"),l=e("../internal/isObjectLike"),i="[object Arguments]",s=Object.prototype,a=s.toString;t.exports=n},{"../internal/isLength":383,"../internal/isObjectLike":384}],392:[function(e,t){var n=e("../internal/isLength"),r=e("./isNative"),l=e("../internal/isObjectLike"),i="[object Array]",s=Object.prototype,a=s.toString,o=r(o=Array.isArray)&&o,u=o||function(e){return l(e)&&n(e.length)&&a.call(e)==i};t.exports=u},{"../internal/isLength":383,"../internal/isObjectLike":384,"./isNative":396}],393:[function(e,t){function n(e){return e===!0||e===!1||r(e)&&s.call(e)==l}var r=e("../internal/isObjectLike"),l="[object Boolean]",i=Object.prototype,s=i.toString;t.exports=n},{"../internal/isObjectLike":384}],394:[function(e,t){function n(e){if(null==e)return!0;var t=e.length;return s(t)&&(l(e)||o(e)||r(e)||a(e)&&i(e.splice))?!t:!u(e).length}var r=e("./isArguments"),l=e("./isArray"),i=e("./isFunction"),s=e("../internal/isLength"),a=e("../internal/isObjectLike"),o=e("./isString"),u=e("../object/keys");t.exports=n},{"../internal/isLength":383,"../internal/isObjectLike":384,"../object/keys":408,"./isArguments":391,"./isArray":392,"./isFunction":395,"./isString":401}],395:[function(e,t){(function(n){var r=e("../internal/baseIsFunction"),l=e("./isNative"),i="[object Function]",s=Object.prototype,a=s.toString,o=l(o=n.Uint8Array)&&o,u=r(/x/)||o&&!r(o)?function(e){return a.call(e)==i}:r;t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../internal/baseIsFunction":348,"./isNative":396}],396:[function(e,t){function n(e){return null==e?!1:u.call(e)==i?p.test(o.call(e)):l(e)&&s.test(e)}var r=e("../string/escapeRegExp"),l=e("../internal/isObjectLike"),i="[object Function]",s=/^\[object .+?Constructor\]$/,a=Object.prototype,o=Function.prototype.toString,u=a.toString,p=RegExp("^"+r(u).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=n},{"../internal/isObjectLike":384,"../string/escapeRegExp":412}],397:[function(e,t){function n(e){return"number"==typeof e||r(e)&&s.call(e)==l}var r=e("../internal/isObjectLike"),l="[object Number]",i=Object.prototype,s=i.toString;t.exports=n},{"../internal/isObjectLike":384}],398:[function(e,t){function n(e){var t=typeof e;return"function"==t||!!e&&"object"==t}t.exports=n},{}],399:[function(e,t){var n=e("./isNative"),r=e("../internal/shimIsPlainObject"),l="[object Object]",i=Object.prototype,s=i.toString,a=n(a=Object.getPrototypeOf)&&a,o=a?function(e){if(!e||s.call(e)!=l)return!1;var t=e.valueOf,i=n(t)&&(i=a(t))&&a(i);return i?e==i||a(e)==i:r(e)}:r;t.exports=o},{"../internal/shimIsPlainObject":386,"./isNative":396}],400:[function(e,t){function n(e){return r(e)&&s.call(e)==l||!1}var r=e("../internal/isObjectLike"),l="[object RegExp]",i=Object.prototype,s=i.toString;t.exports=n},{"../internal/isObjectLike":384}],401:[function(e,t){function n(e){return"string"==typeof e||r(e)&&s.call(e)==l}var r=e("../internal/isObjectLike"),l="[object String]",i=Object.prototype,s=i.toString;t.exports=n},{"../internal/isObjectLike":384}],402:[function(e,t){function n(e){return l(e)&&r(e.length)&&!!C[j.call(e)]}var r=e("../internal/isLength"),l=e("../internal/isObjectLike"),i="[object Arguments]",s="[object Array]",a="[object Boolean]",o="[object Date]",u="[object Error]",p="[object Function]",c="[object Map]",d="[object Number]",f="[object Object]",h="[object RegExp]",m="[object Set]",g="[object String]",y="[object WeakMap]",b="[object ArrayBuffer]",v="[object Float32Array]",x="[object Float64Array]",E="[object Int8Array]",_="[object Int16Array]",S="[object Int32Array]",I="[object Uint8Array]",w="[object Uint8ClampedArray]",k="[object Uint16Array]",A="[object Uint32Array]",C={};C[v]=C[x]=C[E]=C[_]=C[S]=C[I]=C[w]=C[k]=C[A]=!0,C[i]=C[s]=C[b]=C[a]=C[o]=C[u]=C[p]=C[c]=C[d]=C[f]=C[h]=C[m]=C[g]=C[y]=!1;var T=Object.prototype,j=T.toString;t.exports=n},{"../internal/isLength":383,"../internal/isObjectLike":384}],403:[function(e,t){function n(e){return r(e,l(e))}var r=e("../internal/baseCopy"),l=e("../object/keysIn");t.exports=n},{"../internal/baseCopy":336,"../object/keysIn":409}],404:[function(e,t){var n=e("../internal/baseAssign"),r=e("../internal/createAssigner"),l=r(n);t.exports=l},{"../internal/baseAssign":332,"../internal/createAssigner":368}],405:[function(e,t){var n=e("./assign"),r=e("../internal/assignDefaults"),l=e("../function/restParam"),i=l(function(e){var t=e[0];return null==t?t:(e.push(r),n.apply(void 0,e))});t.exports=i},{"../function/restParam":324,"../internal/assignDefaults":331,"./assign":404}],406:[function(e,t){t.exports=e("./assign")},{"./assign":404}],407:[function(e,t){function n(e,t){return e?l.call(e,t):!1}var r=Object.prototype,l=r.hasOwnProperty;t.exports=n},{}],408:[function(e,t){var n=e("../internal/isLength"),r=e("../lang/isNative"),l=e("../lang/isObject"),i=e("../internal/shimKeys"),s=r(s=Object.keys)&&s,a=s?function(e){if(e)var t=e.constructor,r=e.length;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&r&&n(r)?i(e):l(e)?s(e):[]}:i;t.exports=a},{"../internal/isLength":383,"../internal/shimKeys":387,"../lang/isNative":396,"../lang/isObject":398}],409:[function(e,t){function n(e){if(null==e)return[];a(e)||(e=Object(e));var t=e.length;t=t&&s(t)&&(l(e)||o.nonEnumArgs&&r(e))&&t||0;for(var n=e.constructor,u=-1,c="function"==typeof n&&n.prototype===e,d=Array(t),f=t>0;++u<t;)d[u]=u+"";for(var h in e)f&&i(h,t)||"constructor"==h&&(c||!p.call(e,h))||d.push(h);return d}var r=e("../lang/isArguments"),l=e("../lang/isArray"),i=e("../internal/isIndex"),s=e("../internal/isLength"),a=e("../lang/isObject"),o=e("../support"),u=Object.prototype,p=u.hasOwnProperty;t.exports=n},{"../internal/isIndex":381,"../internal/isLength":383,"../lang/isArguments":391,"../lang/isArray":392,"../lang/isObject":398,"../support":413}],410:[function(e,t){var n=e("../internal/baseMerge"),r=e("../internal/createAssigner"),l=r(n);t.exports=l},{"../internal/baseMerge":353,"../internal/createAssigner":368}],411:[function(e,t){function n(e){return r(e,l(e))}var r=e("../internal/baseValues"),l=e("./keys");t.exports=n},{"../internal/baseValues":361,"./keys":408}],412:[function(e,t){function n(e){return e=r(e),e&&i.test(e)?e.replace(l,"\\$&"):e}var r=e("../internal/baseToString"),l=/[.*+?^${}()|[\]\/\\]/g,i=RegExp(l.source);t.exports=n},{"../internal/baseToString":359}],413:[function(e,t){(function(e){var n=Object.prototype,r=(r=e.window)&&r.document,l=n.propertyIsEnumerable,i={};!function(){i.funcDecomp=/\bthis\b/.test(function(){return this}),i.funcNames="string"==typeof Function.name;try{i.dom=11===r.createDocumentFragment().nodeType}catch(e){i.dom=!1}try{i.nonEnumArgs=!l.call(arguments,1)}catch(e){i.nonEnumArgs=!0}}(0,0),t.exports=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],414:[function(e,t){function n(e){return function(){return e}}t.exports=n},{}],415:[function(e,t){function n(e){return e}t.exports=n},{}],416:[function(e,t){(function(n){function r(e){return e.split("").reduce(function(e,t){return e[t]=!0,e},{})}function l(e,t){return t=t||{},function(n){return s(n,e,t)}}function i(e,t){e=e||{},t=t||{};var n={};return Object.keys(t).forEach(function(e){n[e]=t[e]}),Object.keys(e).forEach(function(t){n[t]=e[t]}),n}function s(e,t,n){if("string"!=typeof t)throw new TypeError("glob pattern string required");return n||(n={}),n.nocomment||"#"!==t.charAt(0)?""===t.trim()?""===e:new a(t,n).match(e):!1}function a(e,t){if(!(this instanceof a))return new a(e,t);if("string"!=typeof e)throw new TypeError("glob pattern string required");t||(t={}),e=e.trim(),g&&(e=e.split("\\").join("/")),this.options=t,this.set=[],this.pattern=e,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}function o(){if(!this._made){var e=this.pattern,t=this.options;if(!t.nocomment&&"#"===e.charAt(0))return void(this.comment=!0);if(!e)return void(this.empty=!0);this.parseNegate();var n=this.globSet=this.braceExpand();t.debug&&(this.debug=console.error),this.debug(this.pattern,n),n=this.globParts=n.map(function(e){return e.split(I)}),this.debug(this.pattern,n),n=n.map(function(e){return e.map(this.parse,this)},this),this.debug(this.pattern,n),n=n.filter(function(e){return-1===e.indexOf(!1)}),this.debug(this.pattern,n),this.set=n}}function u(){var e=this.pattern,t=!1,n=this.options,r=0;if(!n.nonegate){for(var l=0,i=e.length;i>l&&"!"===e.charAt(l);l++)t=!t,r++;r&&(this.pattern=e.substr(r)),this.negate=t}}function p(e,t){if(t||(t=this instanceof a?this.options:{}),e="undefined"==typeof e?this.pattern:e,"undefined"==typeof e)throw new Error("undefined pattern");return t.nobrace||!e.match(/\{.*\}/)?[e]:b(e)}function c(e,t){function n(){if(i){switch(i){case"*":a+=x,o=!0;break;case"?":a+=v,o=!0;break;default:a+="\\"+i}g.debug("clearStateChar %j %j",i,a),i=!1}}var r=this.options;if(!r.noglobstar&&"**"===e)return y;if(""===e)return"";for(var l,i,s,a="",o=!!r.nocase,u=!1,p=[],c=!1,d=-1,f=-1,m="."===e.charAt(0)?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",g=this,b=0,E=e.length;E>b&&(s=e.charAt(b));b++)if(this.debug("%s %s %s %j",e,b,a,s),u&&S[s])a+="\\"+s,u=!1;else switch(s){case"/":return!1;case"\\":n(),u=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",e,b,a,s),c){this.debug(" in class"),"!"===s&&b===f+1&&(s="^"),a+=s;continue}g.debug("call clearStateChar %j",i),n(),i=s,r.noext&&n();continue;case"(":if(c){a+="(";continue}if(!i){a+="\\(";continue}l=i,p.push({type:l,start:b-1,reStart:a.length}),a+="!"===i?"(?:(?!":"(?:",this.debug("plType %j %j",i,a),i=!1;continue;case")":if(c||!p.length){a+="\\)";continue}switch(n(),o=!0,a+=")",l=p.pop().type){case"!":a+="[^/]*?)";break;case"?":case"+":case"*":a+=l;case"@":}continue;case"|":if(c||!p.length||u){a+="\\|",u=!1;continue}n(),a+="|";continue;case"[":if(n(),c){a+="\\"+s;continue}c=!0,f=b,d=a.length,a+=s;continue;case"]":if(b===f+1||!c){a+="\\"+s,u=!1;continue}if(c){var _=e.substring(f+1,b);try{new RegExp("["+_+"]")}catch(I){var k=this.parse(_,w);a=a.substr(0,d)+"\\["+k[0]+"\\]",o=o||k[1],c=!1;continue}}o=!0,c=!1,a+=s;continue;default:n(),u?u=!1:!S[s]||"^"===s&&c||(a+="\\"),a+=s}if(c){var _=e.substr(f+1),k=this.parse(_,w);a=a.substr(0,d)+"\\["+k[0],o=o||k[1]}for(var A;A=p.pop();){var C=a.slice(A.reStart+3);C=C.replace(/((?:\\{2})*)(\\?)\|/g,function(e,t,n){return n||(n="\\"),t+t+n+"|"}),this.debug("tail=%j\n %s",C,C);var T="*"===A.type?x:"?"===A.type?v:"\\"+A.type;o=!0,a=a.slice(0,A.reStart)+T+"\\("+C}n(),u&&(a+="\\\\");var j=!1;switch(a.charAt(0)){case".":case"[":case"(":j=!0}if(""!==a&&o&&(a="(?=.)"+a),j&&(a=m+a),t===w)return[a,o];if(!o)return h(e);var M=r.nocase?"i":"",P=new RegExp("^"+a+"$",M);return P._glob=e,P._src=a,P
}function d(){if(this.regexp||this.regexp===!1)return this.regexp;var e=this.set;if(!e.length)return this.regexp=!1;var t=this.options,n=t.noglobstar?x:t.dot?E:_,r=t.nocase?"i":"",l=e.map(function(e){return e.map(function(e){return e===y?n:"string"==typeof e?m(e):e._src}).join("\\/")}).join("|");l="^(?:"+l+")$",this.negate&&(l="^(?!"+l+").*$");try{return this.regexp=new RegExp(l,r)}catch(i){return this.regexp=!1}}function f(e,t){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return""===e;if("/"===e&&t)return!0;var n=this.options;g&&(e=e.split("\\").join("/")),e=e.split(I),this.debug(this.pattern,"split",e);var r=this.set;this.debug(this.pattern,"set",r);for(var l,i=e.length-1;i>=0&&!(l=e[i]);i--);for(var i=0,s=r.length;s>i;i++){var a=r[i],o=e;n.matchBase&&1===a.length&&(o=[l]);var u=this.matchOne(o,a,t);if(u)return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}function h(e){return e.replace(/\\(.)/g,"$1")}function m(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}t.exports=s,s.Minimatch=a;var g=!1;"undefined"!=typeof n&&"win32"===n.platform&&(g=!0);var y=s.GLOBSTAR=a.GLOBSTAR={},b=e("brace-expansion"),v="[^/]",x=v+"*?",E="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_="(?:(?!(?:\\/|^)\\.).)*?",S=r("().*{}+?[]^$\\!"),I=/\/+/;s.filter=l,s.defaults=function(e){if(!e||!Object.keys(e).length)return s;var t=s,n=function(n,r,l){return t.minimatch(n,r,i(e,l))};return n.Minimatch=function(n,r){return new t.Minimatch(n,i(e,r))},n},a.defaults=function(e){return e&&Object.keys(e).length?s.defaults(e).Minimatch:a},a.prototype.debug=function(){},a.prototype.make=o,a.prototype.parseNegate=u,s.braceExpand=function(e,t){return p(e,t)},a.prototype.braceExpand=p,a.prototype.parse=c;var w={};s.makeRe=function(e,t){return new a(e,t||{}).makeRe()},a.prototype.makeRe=d,s.match=function(e,t,n){n=n||{};var r=new a(t,n);return e=e.filter(function(e){return r.match(e)}),r.options.nonull&&!e.length&&e.push(t),e},a.prototype.match=f,a.prototype.matchOne=function(e,t,n){var r=this.options;this.debug("matchOne",{"this":this,file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var l=0,i=0,s=e.length,a=t.length;s>l&&a>i;l++,i++){this.debug("matchOne loop");var o=t[i],u=e[l];if(this.debug(t,o,u),o===!1)return!1;if(o===y){this.debug("GLOBSTAR",[t,o,u]);var p=l,c=i+1;if(c===a){for(this.debug("** at the end");s>l;l++)if("."===e[l]||".."===e[l]||!r.dot&&"."===e[l].charAt(0))return!1;return!0}e:for(;s>p;){var d=e[p];if(this.debug("\nglobstar while",e,p,t,c,d),this.matchOne(e.slice(p),t.slice(c),n))return this.debug("globstar found match!",p,s,d),!0;if("."===d||".."===d||!r.dot&&"."===d.charAt(0)){this.debug("dot detected!",e,p,t,c);break e}this.debug("globstar swallow a segment, and continue"),p++}return n&&(this.debug("\n>>> no match, partial?",e,p,t,c),p===s)?!0:!1}var f;if("string"==typeof o?(f=r.nocase?u.toLowerCase()===o.toLowerCase():u===o,this.debug("string match",o,u,f)):(f=u.match(o),this.debug("pattern match",o,u,f)),!f)return!1}if(l===s&&i===a)return!0;if(l===s)return n;if(i===a){var h=l===s-1&&""===e[l];return h}throw new Error("wtf?")}}).call(this,e("_process"))},{_process:183,"brace-expansion":417}],417:[function(e,t){function n(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function r(e){return e.split("\\\\").join(h).split("\\{").join(m).split("\\}").join(g).split("\\,").join(y).split("\\.").join(b)}function l(e){return e.split(h).join("\\").split(m).join("{").split(g).join("}").split(y).join(",").split(b).join(".")}function i(e){if(!e)return[""];var t=[],n=f("{","}",e);if(!n)return e.split(",");var r=n.pre,l=n.body,s=n.post,a=r.split(",");a[a.length-1]+="{"+l+"}";var o=i(s);return s.length&&(a[a.length-1]+=o.shift(),a.push.apply(a,o)),t.push.apply(t,a),t}function s(e){return e?c(r(e),!0).map(l):[]}function a(e){return"{"+e+"}"}function o(e){return/^-?0\d/.test(e)}function u(e,t){return t>=e}function p(e,t){return e>=t}function c(e,t){var r=[],l=f("{","}",e);if(!l||/\$$/.test(l.pre))return[e];var s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(l.body),h=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(l.body),m=s||h,y=/^(.*,)+(.+)?$/.test(l.body);if(!m&&!y)return l.post.match(/,.*}/)?(e=l.pre+"{"+l.body+g+l.post,c(e)):[e];var b;if(m)b=l.body.split(/\.\./);else if(b=i(l.body),1===b.length&&(b=c(b[0],!1).map(a),1===b.length)){var v=l.post.length?c(l.post,!1):[""];return v.map(function(e){return l.pre+b[0]+e})}var x,E=l.pre,v=l.post.length?c(l.post,!1):[""];if(m){var _=n(b[0]),S=n(b[1]),I=Math.max(b[0].length,b[1].length),w=3==b.length?Math.abs(n(b[2])):1,k=u,A=_>S;A&&(w*=-1,k=p);var C=b.some(o);x=[];for(var T=_;k(T,S);T+=w){var j;if(h)j=String.fromCharCode(T),"\\"===j&&(j="");else if(j=String(T),C){var M=I-j.length;if(M>0){var P=new Array(M+1).join("0");j=0>T?"-"+P+j.slice(1):P+j}}x.push(j)}}else x=d(b,function(e){return c(e,!1)});for(var L=0;L<x.length;L++)for(var O=0;O<v.length;O++){var D=E+x[L]+v[O];(!t||m||D)&&r.push(D)}return r}var d=e("concat-map"),f=e("balanced-match");t.exports=s;var h="\x00SLASH"+Math.random()+"\x00",m="\x00OPEN"+Math.random()+"\x00",g="\x00CLOSE"+Math.random()+"\x00",y="\x00COMMA"+Math.random()+"\x00",b="\x00PERIOD"+Math.random()+"\x00"},{"balanced-match":418,"concat-map":419}],418:[function(e,t){function n(e,t,r){for(var l=0,i={},s=!1,a=0;a<r.length;a++)if(e==r.substr(a,e.length))"start"in i||(i.start=a),l++;else if(t==r.substr(a,t.length)&&"start"in i&&(s=!0,l--,!l))return i.end=a,i.pre=r.substr(0,i.start),i.body=i.end-i.start>1?r.substring(i.start+e.length,i.end):"",i.post=r.slice(i.end+t.length),i;if(l&&s){var o=i.start+e.length;return i=n(e,t,r.substr(o)),i&&(i.start+=o,i.end+=o,i.pre=r.slice(0,o)+i.pre),i}}t.exports=n},{}],419:[function(e,t){t.exports=function(e,t){for(var r=[],l=0;l<e.length;l++){var i=t(e[l],l);n(i)?r.push.apply(r,i):r.push(i)}return r};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],420:[function(e,t){(function(e){"use strict";function n(e){return"/"===e.charAt(0)}function r(e){var t=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,n=t.exec(e),r=n[1]||"",l=!!r&&":"!==r.charAt(1);return!!n[2]||l}t.exports="win32"===e.platform?r:n,t.exports.posix=n,t.exports.win32=r}).call(this,e("_process"))},{_process:183}],421:[function(e,t,n){"use strict";function r(e,t,n){if(c)try{c.call(p,e,t,{value:n})}catch(r){e[t]=n}else e[t]=n}function l(e){return e&&(r(e,"call",e.call),r(e,"apply",e.apply)),e}function i(e){return d?d.call(p,e):(g.prototype=e||null,new g)}function s(){do var e=a(m.call(h.call(y(),36),2));while(f.call(b,e));return b[e]=e}function a(e){var t={};return t[e]=!0,Object.keys(t)[0]}function o(){return i(null)}function u(e){function t(t){function n(n,r){return n===a?r?i=null:i||(i=e(t)):void 0}var i;r(t,l,n)}function n(e){return f.call(e,l)||t(e),e[l](a)}var l=s(),a=i(null);return e=e||o,n.forget=function(e){f.call(e,l)&&e[l](a,!0)},n}var p=Object,c=Object.defineProperty,d=Object.create;l(c),l(d);var f=l(Object.prototype.hasOwnProperty),h=l(Number.prototype.toString),m=l(String.prototype.slice),g=function(){},y=Math.random,b=i(null);r(n,"makeUniqueKey",s);var v=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function(e){for(var t=v(e),n=0,r=0,l=t.length;l>n;++n)f.call(b,t[n])||(n>r&&(t[r]=t[n]),++r);return t.length=r,t},r(n,"makeAccessor",u)},{}],422:[function(e,t,n){function r(e){o.ok(this instanceof r),c.Identifier.assert(e),Object.defineProperties(this,{contextId:{value:e},listing:{value:[]},marked:{value:[!0]},finalLoc:{value:l()},tryEntries:{value:[]}}),Object.defineProperties(this,{leapManager:{value:new d.LeapManager(this)}})}function l(){return p.literal(-1)}function i(e){return c.BreakStatement.check(e)||c.ContinueStatement.check(e)||c.ReturnStatement.check(e)||c.ThrowStatement.check(e)}function s(e){return new Error("all declarations should have been transformed into assignments before the Exploder began its work: "+JSON.stringify(e))}function a(e){var t=e.type;return"normal"===t?!m.call(e,"target"):"break"===t||"continue"===t?!m.call(e,"value")&&c.Literal.check(e.target):"return"===t||"throw"===t?m.call(e,"value")&&!m.call(e,"target"):!1}var o=e("assert"),u=e("ast-types"),p=(u.builtInTypes.array,u.builders),c=u.namedTypes,d=e("./leap"),f=e("./meta"),h=e("./util"),m=Object.prototype.hasOwnProperty,g=r.prototype;n.Emitter=r,g.mark=function(e){c.Literal.assert(e);var t=this.listing.length;return-1===e.value?e.value=t:o.strictEqual(e.value,t),this.marked[t]=!0,e},g.emit=function(e){c.Expression.check(e)&&(e=p.expressionStatement(e)),c.Statement.assert(e),this.listing.push(e)},g.emitAssign=function(e,t){return this.emit(this.assign(e,t)),e},g.assign=function(e,t){return p.expressionStatement(p.assignmentExpression("=",e,t))},g.contextProperty=function(e,t){return p.memberExpression(this.contextId,t?p.literal(e):p.identifier(e),!!t)};var y={prev:!0,next:!0,sent:!0,rval:!0};g.isVolatileContextProperty=function(e){if(c.MemberExpression.check(e)){if(e.computed)return!0;if(c.Identifier.check(e.object)&&c.Identifier.check(e.property)&&e.object.name===this.contextId.name&&m.call(y,e.property.name))return!0}return!1},g.stop=function(e){e&&this.setReturnValue(e),this.jump(this.finalLoc)},g.setReturnValue=function(e){c.Expression.assert(e.value),this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))},g.clearPendingException=function(e,t){c.Literal.assert(e);var n=p.callExpression(this.contextProperty("catch",!0),[e]);t?this.emitAssign(t,n):this.emit(n)},g.jump=function(e){this.emitAssign(this.contextProperty("next"),e),this.emit(p.breakStatement())},g.jumpIf=function(e,t){c.Expression.assert(e),c.Literal.assert(t),this.emit(p.ifStatement(e,p.blockStatement([this.assign(this.contextProperty("next"),t),p.breakStatement()])))},g.jumpIfNot=function(e,t){c.Expression.assert(e),c.Literal.assert(t);var n;n=c.UnaryExpression.check(e)&&"!"===e.operator?e.argument:p.unaryExpression("!",e),this.emit(p.ifStatement(n,p.blockStatement([this.assign(this.contextProperty("next"),t),p.breakStatement()])))};var b=0;g.makeTempVar=function(){return this.contextProperty("t"+b++)},g.getContextFunction=function(e){var t=p.functionExpression(e||null,[this.contextId],p.blockStatement([this.getDispatchLoop()]),!1,!1);return t._aliasFunction=!0,t},g.getDispatchLoop=function(){var e,t=this,n=[],r=!1;return t.listing.forEach(function(l,s){t.marked.hasOwnProperty(s)&&(n.push(p.switchCase(p.literal(s),e=[])),r=!1),r||(e.push(l),i(l)&&(r=!0))}),this.finalLoc.value=this.listing.length,n.push(p.switchCase(this.finalLoc,[]),p.switchCase(p.literal("end"),[p.returnStatement(p.callExpression(this.contextProperty("stop"),[]))])),p.whileStatement(p.literal(1),p.switchStatement(p.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),n))},g.getTryLocsList=function(){if(0===this.tryEntries.length)return null;var e=0;return p.arrayExpression(this.tryEntries.map(function(t){var n=t.firstLoc.value;o.ok(n>=e,"try entries out of order"),e=n;var r=t.catchEntry,l=t.finallyEntry,i=[t.firstLoc,r?r.firstLoc:null];return l&&(i[2]=l.firstLoc,i[3]=l.afterLoc),p.arrayExpression(i)}))},g.explode=function(e,t){o.ok(e instanceof u.NodePath);var n=e.value,r=this;if(c.Node.assert(n),c.Statement.check(n))return r.explodeStatement(e);if(c.Expression.check(n))return r.explodeExpression(e,t);if(c.Declaration.check(n))throw s(n);switch(n.type){case"Program":return e.get("body").map(r.explodeStatement,r);case"VariableDeclarator":throw s(n);case"Property":case"SwitchCase":case"CatchClause":throw new Error(n.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(n.type))}},g.explodeStatement=function(e,t){o.ok(e instanceof u.NodePath);var n=e.value,r=this;if(c.Statement.assert(n),t?c.Identifier.assert(t):t=null,c.BlockStatement.check(n))return e.get("body").each(r.explodeStatement,r);if(!f.containsLeap(n))return void r.emit(n);switch(n.type){case"ExpressionStatement":r.explodeExpression(e.get("expression"),!0);break;case"LabeledStatement":var i=l();r.leapManager.withEntry(new d.LabeledEntry(i,n.label),function(){r.explodeStatement(e.get("body"),n.label)}),r.mark(i);break;case"WhileStatement":var s=l(),i=l();r.mark(s),r.jumpIfNot(r.explodeExpression(e.get("test")),i),r.leapManager.withEntry(new d.LoopEntry(i,s,t),function(){r.explodeStatement(e.get("body"))}),r.jump(s),r.mark(i);break;case"DoWhileStatement":var a=l(),m=l(),i=l();r.mark(a),r.leapManager.withEntry(new d.LoopEntry(i,m,t),function(){r.explode(e.get("body"))}),r.mark(m),r.jumpIf(r.explodeExpression(e.get("test")),a),r.mark(i);break;case"ForStatement":var g=l(),y=l(),i=l();n.init&&r.explode(e.get("init"),!0),r.mark(g),n.test&&r.jumpIfNot(r.explodeExpression(e.get("test")),i),r.leapManager.withEntry(new d.LoopEntry(i,y,t),function(){r.explodeStatement(e.get("body"))}),r.mark(y),n.update&&r.explode(e.get("update"),!0),r.jump(g),r.mark(i);break;case"ForInStatement":c.Identifier.assert(n.left);var g=l(),i=l(),b=r.makeTempVar();r.emitAssign(b,p.callExpression(h.runtimeProperty("keys"),[r.explodeExpression(e.get("right"))])),r.mark(g);var v=r.makeTempVar();r.jumpIf(p.memberExpression(p.assignmentExpression("=",v,p.callExpression(b,[])),p.identifier("done"),!1),i),r.emitAssign(n.left,p.memberExpression(v,p.identifier("value"),!1)),r.leapManager.withEntry(new d.LoopEntry(i,g,t),function(){r.explodeStatement(e.get("body"))}),r.jump(g),r.mark(i);break;case"BreakStatement":r.emitAbruptCompletion({type:"break",target:r.leapManager.getBreakLoc(n.label)});break;case"ContinueStatement":r.emitAbruptCompletion({type:"continue",target:r.leapManager.getContinueLoc(n.label)});break;case"SwitchStatement":for(var x=r.emitAssign(r.makeTempVar(),r.explodeExpression(e.get("discriminant"))),i=l(),E=l(),_=E,S=[],I=n.cases||[],w=I.length-1;w>=0;--w){var k=I[w];c.SwitchCase.assert(k),k.test?_=p.conditionalExpression(p.binaryExpression("===",x,k.test),S[w]=l(),_):S[w]=E}r.jump(r.explodeExpression(new u.NodePath(_,e,"discriminant"))),r.leapManager.withEntry(new d.SwitchEntry(i),function(){e.get("cases").each(function(e){var t=(e.value,e.name);r.mark(S[t]),e.get("consequent").each(r.explodeStatement,r)})}),r.mark(i),-1===E.value&&(r.mark(E),o.strictEqual(i.value,E.value));break;case"IfStatement":var A=n.alternate&&l(),i=l();r.jumpIfNot(r.explodeExpression(e.get("test")),A||i),r.explodeStatement(e.get("consequent")),A&&(r.jump(i),r.mark(A),r.explodeStatement(e.get("alternate"))),r.mark(i);break;case"ReturnStatement":r.emitAbruptCompletion({type:"return",value:r.explodeExpression(e.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var i=l(),C=n.handler;!C&&n.handlers&&(C=n.handlers[0]||null);var T=C&&l(),j=T&&new d.CatchEntry(T,C.param),M=n.finalizer&&l(),P=M&&new d.FinallyEntry(M,i),L=new d.TryEntry(r.getUnmarkedCurrentLoc(),j,P);r.tryEntries.push(L),r.updateContextPrevLoc(L.firstLoc),r.leapManager.withEntry(L,function(){if(r.explodeStatement(e.get("block")),T){r.jump(M?M:i),r.updateContextPrevLoc(r.mark(T));var t=e.get("handler","body"),n=r.makeTempVar();r.clearPendingException(L.firstLoc,n);var l=t.scope,s=C.param.name;c.CatchClause.assert(l.node),o.strictEqual(l.lookup(s),l),u.visit(t,{visitIdentifier:function(e){return h.isReference(e,s)&&e.scope.lookup(s)===l?n:void this.traverse(e)},visitFunction:function(e){return e.scope.declares(s)?!1:void this.traverse(e)}}),r.leapManager.withEntry(j,function(){r.explodeStatement(t)})}M&&(r.updateContextPrevLoc(r.mark(M)),r.leapManager.withEntry(P,function(){r.explodeStatement(e.get("finalizer"))}),r.emit(p.returnStatement(p.callExpression(r.contextProperty("finish"),[P.firstLoc]))))}),r.mark(i);break;case"ThrowStatement":r.emit(p.throwStatement(r.explodeExpression(e.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(n.type))}},g.emitAbruptCompletion=function(e){a(e)||o.ok(!1,"invalid completion record: "+JSON.stringify(e)),o.notStrictEqual(e.type,"normal","normal completions are not abrupt");var t=[p.literal(e.type)];"break"===e.type||"continue"===e.type?(c.Literal.assert(e.target),t[1]=e.target):("return"===e.type||"throw"===e.type)&&e.value&&(c.Expression.assert(e.value),t[1]=e.value),this.emit(p.returnStatement(p.callExpression(this.contextProperty("abrupt"),t)))},g.getUnmarkedCurrentLoc=function(){return p.literal(this.listing.length)},g.updateContextPrevLoc=function(e){e?(c.Literal.assert(e),-1===e.value?e.value=this.listing.length:o.strictEqual(e.value,this.listing.length)):e=this.getUnmarkedCurrentLoc(),this.emitAssign(this.contextProperty("prev"),e)},g.explodeExpression=function(e,t){function n(e){return c.Expression.assert(e),t?void a.emit(e):e}function r(e,t,n){o.ok(t instanceof u.NodePath),o.ok(!n||!e,"Ignoring the result of a child expression but forcing it to be assigned to a temporary variable?");var r=a.explodeExpression(t,n);return n||(e||d&&(a.isVolatileContextProperty(r)||f.hasSideEffects(r)))&&(r=a.emitAssign(e||a.makeTempVar(),r)),r}o.ok(e instanceof u.NodePath);var i=e.value;if(!i)return i;c.Expression.assert(i);var s,a=this;if(!f.containsLeap(i))return n(i);var d=f.containsLeap.onlyChildren(i);switch(i.type){case"MemberExpression":return n(p.memberExpression(a.explodeExpression(e.get("object")),i.computed?r(null,e.get("property")):i.property,i.computed));case"CallExpression":var h=e.get("callee"),m=a.explodeExpression(h);return!c.MemberExpression.check(h.node)&&c.MemberExpression.check(m)&&(m=p.sequenceExpression([p.literal(0),m])),n(p.callExpression(m,e.get("arguments").map(function(e){return r(null,e)})));case"NewExpression":return n(p.newExpression(r(null,e.get("callee")),e.get("arguments").map(function(e){return r(null,e)})));case"ObjectExpression":return n(p.objectExpression(e.get("properties").map(function(e){return p.property(e.value.kind,e.value.key,r(null,e.get("value")))})));case"ArrayExpression":return n(p.arrayExpression(e.get("elements").map(function(e){return r(null,e)})));case"SequenceExpression":var g=i.expressions.length-1;return e.get("expressions").each(function(e){e.name===g?s=a.explodeExpression(e,t):a.explodeExpression(e,!0)}),s;case"LogicalExpression":var y=l();t||(s=a.makeTempVar());var b=r(s,e.get("left"));return"&&"===i.operator?a.jumpIfNot(b,y):(o.strictEqual(i.operator,"||"),a.jumpIf(b,y)),r(s,e.get("right"),t),a.mark(y),s;case"ConditionalExpression":var v=l(),y=l(),x=a.explodeExpression(e.get("test"));return a.jumpIfNot(x,v),t||(s=a.makeTempVar()),r(s,e.get("consequent"),t),a.jump(y),a.mark(v),r(s,e.get("alternate"),t),a.mark(y),s;case"UnaryExpression":return n(p.unaryExpression(i.operator,a.explodeExpression(e.get("argument")),!!i.prefix));case"BinaryExpression":return n(p.binaryExpression(i.operator,r(null,e.get("left")),r(null,e.get("right"))));case"AssignmentExpression":return n(p.assignmentExpression(i.operator,a.explodeExpression(e.get("left")),a.explodeExpression(e.get("right"))));case"UpdateExpression":return n(p.updateExpression(i.operator,a.explodeExpression(e.get("argument")),i.prefix));case"YieldExpression":var y=l(),E=i.argument&&a.explodeExpression(e.get("argument"));if(E&&i.delegate){var s=a.makeTempVar();return a.emit(p.returnStatement(p.callExpression(a.contextProperty("delegateYield"),[E,p.literal(s.property.name),y]))),a.mark(y),s}return a.emitAssign(a.contextProperty("next"),y),a.emit(p.returnStatement(E||null)),a.mark(y),a.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(i.type))}}},{"./leap":424,"./meta":425,"./util":426,assert:173,"ast-types":171}],423:[function(e,t,n){var r=e("assert"),l=e("ast-types"),i=l.namedTypes,s=l.builders,a=Object.prototype.hasOwnProperty;n.hoist=function(e){function t(e,t){i.VariableDeclaration.assert(e);var r=[];return e.declarations.forEach(function(e){n[e.id.name]=e.id,e.init?r.push(s.assignmentExpression("=",e.id,e.init)):t&&r.push(e.id)}),0===r.length?null:1===r.length?r[0]:s.sequenceExpression(r)}r.ok(e instanceof l.NodePath),i.Function.assert(e.value);var n={};l.visit(e.get("body"),{visitVariableDeclaration:function(e){var n=t(e.value,!1);return null!==n?s.expressionStatement(n):(e.replace(),!1)},visitForStatement:function(e){var n=e.value.init;i.VariableDeclaration.check(n)&&e.get("init").replace(t(n,!1)),this.traverse(e)},visitForInStatement:function(e){var n=e.value.left;i.VariableDeclaration.check(n)&&e.get("left").replace(t(n,!0)),this.traverse(e)},visitFunctionDeclaration:function(e){var t=e.value;n[t.id.name]=t.id;var r=(e.parent.node,s.expressionStatement(s.assignmentExpression("=",t.id,s.functionExpression(t.id,t.params,t.body,t.generator,t.expression))));return i.BlockStatement.check(e.parent.node)?(e.parent.get("body").unshift(r),e.replace()):e.replace(r),!1},visitFunctionExpression:function(){return!1}});var o={};e.get("params").each(function(e){var t=e.value;i.Identifier.check(t)&&(o[t.name]=t)});var u=[];return Object.keys(n).forEach(function(e){a.call(o,e)||u.push(s.variableDeclarator(n[e],null))}),0===u.length?null:s.variableDeclaration("var",u)}},{assert:173,"ast-types":171}],424:[function(e,t,n){function r(){d.ok(this instanceof r)}function l(e){r.call(this),h.Literal.assert(e),this.returnLoc=e}function i(e,t,n){r.call(this),h.Literal.assert(e),h.Literal.assert(t),n?h.Identifier.assert(n):n=null,this.breakLoc=e,this.continueLoc=t,this.label=n}function s(e){r.call(this),h.Literal.assert(e),this.breakLoc=e}function a(e,t,n){r.call(this),h.Literal.assert(e),t?d.ok(t instanceof o):t=null,n?d.ok(n instanceof u):n=null,d.ok(t||n),this.firstLoc=e,this.catchEntry=t,this.finallyEntry=n}function o(e,t){r.call(this),h.Literal.assert(e),h.Identifier.assert(t),this.firstLoc=e,this.paramId=t}function u(e,t){r.call(this),h.Literal.assert(e),h.Literal.assert(t),this.firstLoc=e,this.afterLoc=t}function p(e,t){r.call(this),h.Literal.assert(e),h.Identifier.assert(t),this.breakLoc=e,this.label=t}function c(t){d.ok(this instanceof c);var n=e("./emit").Emitter;d.ok(t instanceof n),this.emitter=t,this.entryStack=[new l(t.finalLoc)]}{var d=e("assert"),f=e("ast-types"),h=f.namedTypes,m=(f.builders,e("util").inherits);Object.prototype.hasOwnProperty}m(l,r),n.FunctionEntry=l,m(i,r),n.LoopEntry=i,m(s,r),n.SwitchEntry=s,m(a,r),n.TryEntry=a,m(o,r),n.CatchEntry=o,m(u,r),n.FinallyEntry=u,m(p,r),n.LabeledEntry=p;var g=c.prototype;n.LeapManager=c,g.withEntry=function(e,t){d.ok(e instanceof r),this.entryStack.push(e);try{t.call(this.emitter)}finally{var n=this.entryStack.pop();d.strictEqual(n,e)}},g._findLeapLocation=function(e,t){for(var n=this.entryStack.length-1;n>=0;--n){var r=this.entryStack[n],l=r[e];if(l)if(t){if(r.label&&r.label.name===t.name)return l}else if(!(r instanceof p))return l}return null},g.getBreakLoc=function(e){return this._findLeapLocation("breakLoc",e)},g.getContinueLoc=function(e){return this._findLeapLocation("continueLoc",e)}},{"./emit":422,assert:173,"ast-types":171,util:199}],425:[function(e,t,n){function r(e,t){function n(e){function t(e){return n||(a.check(e)?e.some(t):o.Node.check(e)&&(l.strictEqual(n,!1),n=r(e))),n}o.Node.assert(e);var n=!1;return s.eachField(e,function(e,n){t(n)}),n}function r(r){o.Node.assert(r);var l=i(r);return u.call(l,e)?l[e]:l[e]=u.call(p,r.type)?!1:u.call(t,r.type)?!0:n(r)}return r.onlyChildren=n,r}var l=e("assert"),i=e("private").makeAccessor(),s=e("ast-types"),a=s.builtInTypes.array,o=s.namedTypes,u=Object.prototype.hasOwnProperty,p={FunctionExpression:!0},c={CallExpression:!0,ForInStatement:!0,UnaryExpression:!0,BinaryExpression:!0,AssignmentExpression:!0,UpdateExpression:!0,NewExpression:!0},d={YieldExpression:!0,BreakStatement:!0,ContinueStatement:!0,ReturnStatement:!0,ThrowStatement:!0};for(var f in d)u.call(d,f)&&(c[f]=d[f]);n.hasSideEffects=r("hasSideEffects",c),n.containsLeap=r("containsLeap",d)},{assert:173,"ast-types":171,"private":421}],426:[function(e,t,n){var r=(e("assert"),e("ast-types")),l=r.namedTypes,i=r.builders,s=Object.prototype.hasOwnProperty;n.defaults=function(e){for(var t,n=arguments.length,r=1;n>r;++r)if(t=arguments[r])for(var l in t)s.call(t,l)&&!s.call(e,l)&&(e[l]=t[l]);return e},n.runtimeProperty=function(e){return i.memberExpression(i.identifier("regeneratorRuntime"),i.identifier(e),!1)},n.isReference=function(e,t){var n=e.value;if(!l.Identifier.check(n))return!1;if(t&&n.name!==t)return!1;var r=e.parent.value;switch(r.type){case"VariableDeclarator":return"init"===e.name;case"MemberExpression":return"object"===e.name||r.computed&&"property"===e.name;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return"id"===e.name?!1:r.params===e.parentPath&&r.params[e.name]===n?!1:!0;case"ClassDeclaration":case"ClassExpression":return"id"!==e.name;case"CatchClause":return"param"!==e.name;case"Property":case"MethodDefinition":return"key"!==e.name;case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return!1;default:return!0}}},{assert:173,"ast-types":171}],427:[function(e,t,n){var r=(e("assert"),e("fs"),e("ast-types")),l=r.namedTypes,i=r.builders,s=(r.builtInTypes.array,r.builtInTypes.object,r.NodePath),a=e("./hoist").hoist,o=e("./emit").Emitter,u=e("./util").runtimeProperty;n.transform=function(e,t){t=t||{};var n=e instanceof s?e:new s(e);return p.visit(n,t),e=n.value,t.madeChanges=p.wasChangeReported(),e};var p=r.PathVisitor.fromMethodsObject({reset:function(e,t){this.options=t},visitFunction:function(e){this.traverse(e);var t=e.value,n=t.async&&!this.options.disableAsync;if(t.generator||n){this.reportChanged(),t.generator=!1,t.expression&&(t.expression=!1,t.body=i.blockStatement([i.returnStatement(t.body)])),n&&c.visit(e.get("body"));var r=t.id||(t.id=e.scope.parent.declareTemporary("callee$")),s=[],p=e.value.body;p.body=p.body.filter(function(e){return e&&null!=e._blockHoist?(s.push(e),!1):!0});var d=i.identifier(t.id.name+"$"),f=e.scope.declareTemporary("context$"),h=a(e),m=new o(f);m.explode(e.get("body")),h&&h.declarations.length>0&&s.push(h);var g=[m.getContextFunction(d),n?i.literal(null):r,i.thisExpression()],y=m.getTryLocsList();y&&g.push(y);var b=i.callExpression(u(n?"async":"wrap"),g);if(s.push(i.returnStatement(b)),t.body=i.blockStatement(s),t.body._declarations=p._declarations,n)return void(t.async=!1);if(!l.FunctionDeclaration.check(t))return l.FunctionExpression.assert(t),i.callExpression(u("mark"),[t]);for(var v=e.parent;v&&!l.BlockStatement.check(v.value)&&!l.Program.check(v.value);)v=v.parent;if(v){e.replace(),t.type="FunctionExpression";var x=i.variableDeclaration("var",[i.variableDeclarator(t.id,i.callExpression(u("mark"),[t]))]);t.comments&&(x.leadingComments=t.leadingComments,x.trailingComments=t.trailingComments,t.leadingComments=null,t.trailingComments=null),x._blockHoist=3;{var E=v.get("body");E.value.length}E.push(x)}}}}),c=r.PathVisitor.fromMethodsObject({visitFunction:function(){return!1},visitAwaitExpression:function(e){var t=e.value.argument;return e.value.all&&(t=i.callExpression(i.memberExpression(i.identifier("Promise"),i.identifier("all"),!1),[t])),i.yieldExpression(t,!1)}})},{"./emit":422,"./hoist":423,"./util":426,assert:173,"ast-types":171,fs:172}],428:[function(e,t){(function(n){function r(e,t){function n(e){l.push(e)}function r(){this.queue(compile(l.join(""),t).code),this.queue(null)}var l=[];return s(n,r)}function l(){e("./runtime")}{var i=(e("assert"),e("path")),s=(e("fs"),e("through")),a=e("./lib/visit").transform;e("./lib/util"),e("ast-types")}t.exports=r,r.runtime=l,l.path=i.join(n,"runtime.js"),r.transform=a}).call(this,"/node_modules/regenerator-babel")},{"./lib/util":426,"./lib/visit":427,"./runtime":430,assert:173,"ast-types":171,fs:172,path:182,through:429}],429:[function(e,t,n){(function(r){function l(e,t,n){function l(){for(;u.length&&!c.paused;){var e=u.shift();if(null===e)return c.emit("end");c.emit("data",e)}}function s(){c.writable=!1,t.call(c),!c.readable&&c.autoDestroy&&c.destroy()}e=e||function(e){this.queue(e)},t=t||function(){this.queue(null)};var a=!1,o=!1,u=[],p=!1,c=new i;return c.readable=c.writable=!0,c.paused=!1,c.autoDestroy=!(n&&n.autoDestroy===!1),c.write=function(t){return e.call(this,t),!c.paused},c.queue=c.push=function(e){return p?c:(null==e&&(p=!0),u.push(e),l(),c)},c.on("end",function(){c.readable=!1,!c.writable&&c.autoDestroy&&r.nextTick(function(){c.destroy()})}),c.end=function(e){return a?void 0:(a=!0,arguments.length&&c.write(e),s(),c)},c.destroy=function(){return o?void 0:(o=!0,a=!0,u.length=0,c.writable=c.readable=!1,c.emit("close"),c)},c.pause=function(){return c.paused?void 0:(c.paused=!0,c)},c.resume=function(){return c.paused&&(c.paused=!1,c.emit("resume")),l(),c.paused||c.emit("drain"),c},c}var i=e("stream");n=t.exports=l,l.through=l}).call(this,e("_process"))},{_process:183,stream:195}],430:[function(e,t){(function(e){!function(e){"use strict";function n(e,t,n,r){return new s(e,t,n||null,r||[])}function r(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(r){return{type:"throw",arg:r}}}function l(){}function i(){}function s(e,t,n,l){function i(t,l){if(o===v)throw new Error("Generator is already running");if(o===x)return c();for(;;){var i=a.delegate;if(i){var s=r(i.iterator[t],i.iterator,l);if("throw"===s.type){a.delegate=null,t="throw",l=s.arg;continue}t="next",l=d;var u=s.arg;if(!u.done)return o=b,u;a[i.resultName]=u.value,a.next=i.nextLoc,a.delegate=null}if("next"===t){if(o===y&&"undefined"!=typeof l)throw new TypeError("attempt to send "+JSON.stringify(l)+" to newborn generator");o===b?a.sent=l:delete a.sent}else if("throw"===t){if(o===y)throw o=x,l;a.dispatchException(l)&&(t="next",l=d)}else"return"===t&&a.abrupt("return",l);o=v;var s=r(e,n,a);if("normal"===s.type){o=a.done?x:b;var u={value:s.arg,done:a.done};if(s.arg!==E)return u;a.delegate&&"next"===t&&(l=d)}else"throw"===s.type&&(o=x,"next"===t?a.dispatchException(s.arg):l=s.arg)}}var s=t?Object.create(t.prototype):this,a=new u(l),o=y;return s.next=i.bind(s,"next"),s["throw"]=i.bind(s,"throw"),s["return"]=i.bind(s,"return"),s}function a(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function o(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function u(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(a,this),this.reset()}function p(e){if(e){var t=e[h];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function l(){for(;++n<e.length;)if(f.call(e,n))return l.value=e[n],l.done=!1,l;return l.value=d,l.done=!0,l};return r.next=r}}return{next:c}}function c(){return{value:d,done:!0}}var d,f=Object.prototype.hasOwnProperty,h="function"==typeof Symbol&&Symbol.iterator||"@@iterator",m="object"==typeof t,g=e.regeneratorRuntime;if(g)return void(m&&(t.exports=g));g=e.regeneratorRuntime=m?t.exports:{},g.wrap=n;var y="suspendedStart",b="suspendedYield",v="executing",x="completed",E={},_=i.prototype=s.prototype;l.prototype=_.constructor=i,i.constructor=l,l.displayName="GeneratorFunction",g.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return t?t===l||"GeneratorFunction"===(t.displayName||t.name):!1},g.mark=function(e){return e.__proto__=i,e.prototype=Object.create(_),e},g.async=function(e,t,l,i){return new Promise(function(s,a){function o(e){var t=r(this,null,e);if("throw"===t.type)return void a(t.arg);var n=t.arg;n.done?s(n.value):Promise.resolve(n.value).then(p,c)}var u=n(e,t,l,i),p=o.bind(u.next),c=o.bind(u["throw"]);p()})},_[h]=function(){return this},_.toString=function(){return"[object Generator]"},g.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function r(){for(;t.length;){var n=t.pop();if(n in e)return r.value=n,r.done=!1,r}return r.done=!0,r}},g.values=p,u.prototype={constructor:u,reset:function(){this.prev=0,this.next=0,this.sent=d,this.done=!1,this.delegate=null,this.tryEntries.forEach(o);for(var e,t=0;f.call(this,e="t"+t)||20>t;++t)this[e]=null},stop:function(){this.done=!0;var e=this.tryEntries[0],t=e.completion;
if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){function t(t,r){return i.type="throw",i.arg=e,n.next=t,!!r}if(this.done)throw e;for(var n=this,r=this.tryEntries.length-1;r>=0;--r){var l=this.tryEntries[r],i=l.completion;if("root"===l.tryLoc)return t("end");if(l.tryLoc<=this.prev){var s=f.call(l,"catchLoc"),a=f.call(l,"finallyLoc");if(s&&a){if(this.prev<l.catchLoc)return t(l.catchLoc,!0);if(this.prev<l.finallyLoc)return t(l.finallyLoc)}else if(s){if(this.prev<l.catchLoc)return t(l.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<l.finallyLoc)return t(l.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&f.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var l=r;break}}l&&("break"===e||"continue"===e)&&l.tryLoc<=t&&t<l.finallyLoc&&(l=null);var i=l?l.completion:{};return i.type=e,i.arg=t,l?this.next=l.finallyLoc:this.complete(i),E},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=e.arg,this.next="end"):"normal"===e.type&&t&&(this.next=t),E},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc)}},"catch":function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var l=r.arg;o(n)}return l}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:p(e),resultName:t,nextLoc:n},E}}}("object"==typeof e?e:"object"==typeof window?window:this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],431:[function(e,t,n){var r=e("regenerate");n.REGULAR={d:r().addRange(48,57),D:r().addRange(0,47).addRange(58,65535),s:r(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:r().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:r(95).addRange(48,57).addRange(65,90).addRange(97,122),W:r(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)},n.UNICODE={d:r().addRange(48,57),D:r().addRange(0,47).addRange(58,1114111),s:r(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:r().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:r(95).addRange(48,57).addRange(65,90).addRange(97,122),W:r(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)},n.UNICODE_IGNORE_CASE={d:r().addRange(48,57),D:r().addRange(0,47).addRange(58,1114111),s:r(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:r().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:r(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:r(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:433}],432:[function(e,t){t.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],433:[function(t,n,r){(function(t){!function(l){var i="object"==typeof r&&r,s="object"==typeof n&&n&&n.exports==i&&n,a="object"==typeof t&&t;(a.global===a||a.window===a)&&(l=a);var o={rangeOrder:"A range’s `stop` value must be greater than or equal to the `start` value.",codePointRange:"Invalid code point value. Code points range from U+000000 to U+10FFFF."},u=55296,p=56319,c=56320,d=57343,f=/\\x00([^0123456789]|$)/g,h={},m=h.hasOwnProperty,g=function(e,t){var n;for(n in t)m.call(t,n)&&(e[n]=t[n]);return e},y=function(e,t){for(var n=-1,r=e.length;++n<r;)t(e[n],n)},b=h.toString,v=function(e){return"[object Array]"==b.call(e)},x=function(e){return"number"==typeof e||"[object Number]"==b.call(e)},E="0000",_=function(e,t){var n=String(e);return n.length<t?(E+n).slice(-t):n},S=function(e){return Number(e).toString(16).toUpperCase()},I=[].slice,w=function(e){for(var t,n=-1,r=e.length,l=r-1,i=[],s=!0,a=0;++n<r;)if(t=e[n],s)i.push(t),a=t,s=!1;else if(t==a+1){if(n!=l){a=t;continue}s=!0,i.push(t+1)}else i.push(a+1,t),a=t;return s||i.push(t+1),i},k=function(e,t){for(var n,r,l=0,i=e.length;i>l;){if(n=e[l],r=e[l+1],t>=n&&r>t)return t==n?r==n+1?(e.splice(l,2),e):(e[l]=t+1,e):t==r-1?(e[l+1]=t,e):(e.splice(l,2,n,t,t+1,r),e);l+=2}return e},A=function(e,t,n){if(t>n)throw Error(o.rangeOrder);for(var r,l,i=0;i<e.length;){if(r=e[i],l=e[i+1]-1,r>n)return e;if(r>=t&&n>=l)e.splice(i,2);else{if(t>=r&&l>n)return t==r?(e[i]=n+1,e[i+1]=l+1,e):(e.splice(i,2,r,t,n+1,l+1),e);if(t>=r&&l>=t)e[i+1]=t;else if(n>=r&&l>=n)return e[i]=n+1,e;i+=2}}return e},C=function(e,t){var n,r,l=0,i=null,s=e.length;if(0>t||t>1114111)throw RangeError(o.codePointRange);for(;s>l;){if(n=e[l],r=e[l+1],t>=n&&r>t)return e;if(t==n-1)return e[l]=t,e;if(n>t)return e.splice(null!=i?i+2:0,0,t,t+1),e;if(t==r)return t+1==e[l+2]?(e.splice(l,4,n,e[l+3]),e):(e[l+1]=t+1,e);i=l,l+=2}return e.push(t,t+1),e},T=function(e,t){for(var n,r,l=0,i=e.slice(),s=t.length;s>l;)n=t[l],r=t[l+1]-1,i=n==r?C(i,n):M(i,n,r),l+=2;return i},j=function(e,t){for(var n,r,l=0,i=e.slice(),s=t.length;s>l;)n=t[l],r=t[l+1]-1,i=n==r?k(i,n):A(i,n,r),l+=2;return i},M=function(e,t,n){if(t>n)throw Error(o.rangeOrder);if(0>t||t>1114111||0>n||n>1114111)throw RangeError(o.codePointRange);for(var r,l,i=0,s=!1,a=e.length;a>i;){if(r=e[i],l=e[i+1],s){if(r==n+1)return e.splice(i-1,2),e;if(r>n)return e;r>=t&&n>=r&&(l>t&&n>=l-1?(e.splice(i,2),i-=2):(e.splice(i-1,2),i-=2))}else{if(r==n+1)return e[i]=t,e;if(r>n)return e.splice(i,0,t,n+1),e;if(t>=r&&l>t&&l>=n+1)return e;t>=r&&l>t||l==t?(e[i+1]=n+1,s=!0):r>=t&&n+1>=l&&(e[i]=t,e[i+1]=n+1,s=!0)}i+=2}return s||e.push(t,n+1),e},P=function(e,t){var n=0,r=e.length,l=e[n],i=e[r-1];if(r>=2&&(l>t||t>i))return!1;for(;r>n;){if(l=e[n],i=e[n+1],t>=l&&i>t)return!0;n+=2}return!1},L=function(e,t){for(var n,r=0,l=t.length,i=[];l>r;)n=t[r],P(e,n)&&i.push(n),++r;return w(i)},O=function(e){return!e.length},D=function(e){return 2==e.length&&e[0]+1==e[1]},R=function(e){for(var t,n,r=0,l=[],i=e.length;i>r;){for(t=e[r],n=e[r+1];n>t;)l.push(t),++t;r+=2}return l},N=Math.floor,F=function(e){return parseInt(N((e-65536)/1024)+u,10)},B=function(e){return parseInt((e-65536)%1024+c,10)},$=String.fromCharCode,V=function(e){var t;return t=9==e?"\\t":10==e?"\\n":12==e?"\\f":13==e?"\\r":92==e?"\\\\":36==e||e>=40&&43>=e||45==e||46==e||63==e||e>=91&&94>=e||e>=123&&125>=e?"\\"+$(e):e>=32&&126>=e?$(e):255>=e?"\\x"+_(S(e),2):"\\u"+_(S(e),4)},U=function(e){var t,n=e.length,r=e.charCodeAt(0);return r>=u&&p>=r&&n>1?(t=e.charCodeAt(1),1024*(r-u)+t-c+65536):r},q=function(e){var t,n,r="",l=0,i=e.length;if(D(e))return V(e[0]);for(;i>l;)t=e[l],n=e[l+1]-1,r+=t==n?V(t):t+1==n?V(t)+V(n):V(t)+"-"+V(n),l+=2;return"["+r+"]"},G=function(e){for(var t,n,r=[],l=[],i=[],s=[],a=0,o=e.length;o>a;)t=e[a],n=e[a+1]-1,u>t?(u>n&&i.push(t,n+1),n>=u&&p>=n&&(i.push(t,u),r.push(u,n+1)),n>=c&&d>=n&&(i.push(t,u),r.push(u,p+1),l.push(c,n+1)),n>d&&(i.push(t,u),r.push(u,p+1),l.push(c,d+1),65535>=n?i.push(d+1,n+1):(i.push(d+1,65536),s.push(65536,n+1)))):t>=u&&p>=t?(n>=u&&p>=n&&r.push(t,n+1),n>=c&&d>=n&&(r.push(t,p+1),l.push(c,n+1)),n>d&&(r.push(t,p+1),l.push(c,d+1),65535>=n?i.push(d+1,n+1):(i.push(d+1,65536),s.push(65536,n+1)))):t>=c&&d>=t?(n>=c&&d>=n&&l.push(t,n+1),n>d&&(l.push(t,d+1),65535>=n?i.push(d+1,n+1):(i.push(d+1,65536),s.push(65536,n+1)))):t>d&&65535>=t?65535>=n?i.push(t,n+1):(i.push(t,65536),s.push(65536,n+1)):s.push(t,n+1),a+=2;return{loneHighSurrogates:r,loneLowSurrogates:l,bmp:i,astral:s}},W=function(e){for(var t,n,r,l,i,s,a=[],o=[],u=!1,p=-1,c=e.length;++p<c;)if(t=e[p],n=e[p+1]){for(r=t[0],l=t[1],i=n[0],s=n[1],o=l;i&&r[0]==i[0]&&r[1]==i[1];)o=D(s)?C(o,s[0]):M(o,s[0],s[1]-1),++p,t=e[p],r=t[0],l=t[1],n=e[p+1],i=n&&n[0],s=n&&n[1],u=!0;a.push([r,u?o:l]),u=!1}else a.push(t);return z(a)},z=function(e){if(1==e.length)return e;for(var t=-1,n=-1;++t<e.length;){var r=e[t],l=r[1],i=l[0],s=l[1];for(n=t;++n<e.length;){var a=e[n],o=a[1],u=o[0],p=o[1];i==u&&s==p&&(r[0]=D(a[0])?C(r[0],a[0][0]):M(r[0],a[0][0],a[0][1]-1),e.splice(n,1),--n)}}return e},H=function(e){if(!e.length)return[];for(var t,n,r,l,i,s,a=0,o=0,u=0,p=[],f=e.length;f>a;){t=e[a],n=e[a+1]-1,r=F(t),l=B(t),i=F(n),s=B(n);var h=l==c,m=s==d,g=!1;r==i||h&&m?(p.push([[r,i+1],[l,s+1]]),g=!0):p.push([[r,r+1],[l,d+1]]),!g&&i>r+1&&(m?(p.push([[r+1,i+1],[c,s+1]]),g=!0):p.push([[r+1,i],[c,d+1]])),g||p.push([[i,i+1],[c,s+1]]),o=r,u=i,a+=2}return W(p)},J=function(e){var t=[];return y(e,function(e){var n=e[0],r=e[1];t.push(q(n)+q(r))}),t.join("|")},X=function(e,t){var n=[],r=G(e),l=r.loneHighSurrogates,i=r.loneLowSurrogates,s=r.bmp,a=r.astral,o=(!O(r.astral),!O(l)),u=!O(i),p=H(a);return t&&(s=T(s,l),o=!1,s=T(s,i),u=!1),O(s)||n.push(q(s)),p.length&&n.push(J(p)),o&&n.push(q(l)+"(?![\\uDC00-\\uDFFF])"),u&&n.push("(?:[^\\uD800-\\uDBFF]|^)"+q(i)),n.join("|")},Y=function(e){return arguments.length>1&&(e=I.call(arguments)),this instanceof Y?(this.data=[],e?this.add(e):this):(new Y).add(e)};Y.version="1.2.0";var K=Y.prototype;g(K,{add:function(e){var t=this;return null==e?t:e instanceof Y?(t.data=T(t.data,e.data),t):(arguments.length>1&&(e=I.call(arguments)),v(e)?(y(e,function(e){t.add(e)}),t):(t.data=C(t.data,x(e)?e:U(e)),t))},remove:function(e){var t=this;return null==e?t:e instanceof Y?(t.data=j(t.data,e.data),t):(arguments.length>1&&(e=I.call(arguments)),v(e)?(y(e,function(e){t.remove(e)}),t):(t.data=k(t.data,x(e)?e:U(e)),t))},addRange:function(e,t){var n=this;return n.data=M(n.data,x(e)?e:U(e),x(t)?t:U(t)),n},removeRange:function(e,t){var n=this,r=x(e)?e:U(e),l=x(t)?t:U(t);return n.data=A(n.data,r,l),n},intersection:function(e){var t=this,n=e instanceof Y?R(e.data):e;return t.data=L(t.data,n),t},contains:function(e){return P(this.data,x(e)?e:U(e))},clone:function(){var e=new Y;return e.data=this.data.slice(0),e},toString:function(e){var t=X(this.data,e?e.bmpOnly:!1);return t.replace(f,"\\0$1")},toRegExp:function(e){return RegExp(this.toString(),e||"")},valueOf:function(){return R(this.data)}}),K.toArray=K.valueOf,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return Y}):i&&!i.nodeType?s?s.exports=Y:i.regenerate=Y:l.regenerate=Y}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],434:[function(t,n,r){(function(t){(function(){"use strict";function l(){var e,t,n=16384,r=[],l=-1,i=arguments.length;if(!i)return"";for(var s="";++l<i;){var a=Number(arguments[l]);if(!isFinite(a)||0>a||a>1114111||A(a)!=a)throw RangeError("Invalid code point: "+a);65535>=a?r.push(a):(a-=65536,e=(a>>10)+55296,t=a%1024+56320,r.push(e,t)),(l+1==i||r.length>n)&&(s+=k.apply(null,r),r.length=0)}return s}function i(e,t){if(-1==t.indexOf("|")){if(e==t)return;throw Error("Invalid node type: "+e)}if(t=i.hasOwnProperty(t)?i[t]:i[t]=RegExp("^(?:"+t+")$"),!t.test(e))throw Error("Invalid node type: "+e)}function s(e){var t=e.type;if(s.hasOwnProperty(t)&&"function"==typeof s[t])return s[t](e);throw Error("Invalid node type: "+t)}function a(e){i(e.type,"alternative");var t=e.body,n=t?t.length:0;if(1==n)return v(t[0]);for(var r=-1,l="";++r<n;)l+=v(t[r]);return l}function o(e){switch(i(e.type,"anchor"),e.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function u(e){return i(e.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value"),s(e)}function p(e){i(e.type,"characterClass");var t=e.body,n=t?t.length:0,r=-1,l="[";for(e.negative&&(l+="^");++r<n;)l+=f(t[r]);return l+="]"}function c(e){return i(e.type,"characterClassEscape"),"\\"+e.value}function d(e){i(e.type,"characterClassRange");var t=e.min,n=e.max;if("characterClassRange"==t.type||"characterClassRange"==n.type)throw Error("Invalid character class range");return f(t)+"-"+f(n)}function f(e){return i(e.type,"anchor|characterClassEscape|characterClassRange|dot|value"),s(e)}function h(e){i(e.type,"disjunction");var t=e.body,n=t?t.length:0;if(0==n)throw Error("No body");if(1==n)return s(t[0]);for(var r=-1,l="";++r<n;)0!=r&&(l+="|"),l+=s(t[r]);return l}function m(e){return i(e.type,"dot"),"."}function g(e){i(e.type,"group");var t="(";switch(e.behavior){case"normal":break;case"ignore":t+="?:";break;case"lookahead":t+="?=";break;case"negativeLookahead":t+="?!";break;default:throw Error("Invalid behaviour: "+e.behaviour)}var n=e.body,r=n?n.length:0;if(1==r)t+=s(n[0]);else for(var l=-1;++l<r;)t+=s(n[l]);return t+=")"}function y(e){i(e.type,"quantifier");var t="",n=e.min,r=e.max;switch(r){case void 0:case null:switch(n){case 0:t="*";break;case 1:t="+";break;default:t="{"+n+",}"}break;default:t=n==r?"{"+n+"}":0==n&&1==r?"?":"{"+n+","+r+"}"}return e.greedy||(t+="?"),u(e.body[0])+t}function b(e){return i(e.type,"reference"),"\\"+e.matchIndex}function v(e){return i(e.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value"),s(e)}function x(e){i(e.type,"value");var t=e.kind,n=e.codePoint;switch(t){case"controlLetter":return"\\c"+l(n+64);case"hexadecimalEscape":return"\\x"+("00"+n.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+l(n);case"null":return"\\"+n;case"octal":return"\\"+n.toString(8);case"singleEscape":switch(n){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+n)}case"symbol":return l(n);case"unicodeEscape":return"\\u"+("0000"+n.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+n.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+t)}}var E={"function":!0,object:!0},_=E[typeof window]&&window||this,S=E[typeof r]&&r,I=E[typeof n]&&n&&!n.nodeType&&n,w=S&&I&&"object"==typeof t&&t;!w||w.global!==w&&w.window!==w&&w.self!==w||(_=w);var k=String.fromCharCode,A=Math.floor;s.alternative=a,s.anchor=o,s.characterClass=p,s.characterClassEscape=c,s.characterClassRange=d,s.disjunction=h,s.dot=m,s.group=g,s.quantifier=y,s.reference=b,s.value=x,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return{generate:s}}):S&&I?S.generate=s:_.regjsgen={generate:s}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],435:[function(e,t){!function(){function e(e,t){function n(t){return t.raw=e.substring(t.range[0],t.range[1]),t}function r(e,t){return e.range[0]=t,n(e)}function l(e,t){return n({type:"anchor",kind:e,range:[Y-t,Y]})}function i(e,t,r,l){return n({type:"value",kind:e,codePoint:t,range:[r,l]})}function s(e,t,n,r){return r=r||0,i(e,t,Y-(n.length+r),Y)}function a(e){var t=e[0],n=t.charCodeAt(0);if(X){var r;if(1===t.length&&n>=55296&&56319>=n&&(r=E().charCodeAt(0),r>=56320&&57343>=r))return Y++,i("symbol",1024*(n-55296)+r-56320+65536,Y-2,Y)}return i("symbol",n,Y-1,Y)}function o(e,t,r){return n({type:"disjunction",body:e,range:[t,r]})}function u(){return n({type:"dot",range:[Y-1,Y]})}function p(e){return n({type:"characterClassEscape",value:e,range:[Y-2,Y]})}function c(e){return n({type:"reference",matchIndex:parseInt(e,10),range:[Y-1-e.length,Y]})}function d(e,t,r,l){return n({type:"group",behavior:e,body:t,range:[r,l]})}function f(e,t,r,l){return null==l&&(r=Y-1,l=Y),n({type:"quantifier",min:e,max:t,greedy:!0,body:null,range:[r,l]})}function h(e,t,r){return n({type:"alternative",body:e,range:[t,r]})}function m(e,t,r,l){return n({type:"characterClass",body:e,negative:t,range:[r,l]})}function g(e,t,r,l){if(e.codePoint>t.codePoint)throw SyntaxError("invalid range in character class");return n({type:"characterClassRange",min:e,max:t,range:[r,l]})}function y(e){return"alternative"===e.type?e.body:[e]}function b(t){t=t||1;var n=e.substring(Y,Y+t);return Y+=t||1,n}function v(e){if(!x(e))throw SyntaxError("character: "+e)}function x(t){return e.indexOf(t,Y)===Y?b(t.length):void 0}function E(){return e[Y]}function _(t){return e.indexOf(t,Y)===Y}function S(t){return e[Y+1]===t}function I(t){var n=e.substring(Y),r=n.match(t);return r&&(r.range=[],r.range[0]=Y,b(r[0].length),r.range[1]=Y),r}function w(){var e=[],t=Y;for(e.push(k());x("|");)e.push(k());return 1===e.length?e[0]:o(e,t,Y)}function k(){for(var e,t=[],n=Y;e=A();)t.push(e);return 1===t.length?t[0]:h(t,n,Y)}function A(){if(Y>=e.length||_("|")||_(")"))return null;var t=T();if(t)return t;var n=M();if(!n)throw SyntaxError("Expected atom");var l=j()||!1;return l?(l.body=y(n),r(l,n.range[0]),l):n}function C(e,t,n,r){var l=null,i=Y;if(x(e))l=t;else{if(!x(n))return!1;l=r}var s=w();if(!s)throw SyntaxError("Expected disjunction");v(")");var a=d(l,y(s),i,Y);return"normal"==l&&J&&H++,a}function T(){return x("^")?l("start",1):x("$")?l("end",1):x("\\b")?l("boundary",2):x("\\B")?l("not-boundary",2):C("(?=","lookahead","(?!","negativeLookahead")}function j(){var e,t,n,r;if(x("*"))t=f(0);else if(x("+"))t=f(1);else if(x("?"))t=f(0,1);else if(e=I(/^\{([0-9]+)\}/))n=parseInt(e[1],10),t=f(n,n,e.range[0],e.range[1]);else if(e=I(/^\{([0-9]+),\}/))n=parseInt(e[1],10),t=f(n,void 0,e.range[0],e.range[1]);else if(e=I(/^\{([0-9]+),([0-9]+)\}/)){if(n=parseInt(e[1],10),r=parseInt(e[2],10),n>r)throw SyntaxError("numbers out of order in {} quantifier");t=f(n,r,e.range[0],e.range[1])}return t&&x("?")&&(t.greedy=!1,t.range[1]+=1),t}function M(){var e;if(e=I(/^[^^$\\.*+?(){[|]/))return a(e);if(x("."))return u();if(x("\\")){if(e=O(),!e)throw SyntaxError("atomEscape");return e}return(e=B())?e:C("(?:","ignore","(","normal")}function P(e){if(X){var t,r;if("unicodeEscape"==e.kind&&(t=e.codePoint)>=55296&&56319>=t&&_("\\")&&S("u")){var l=Y;Y++;var i=L();"unicodeEscape"==i.kind&&(r=i.codePoint)>=56320&&57343>=r?(e.range[1]=i.range[1],e.codePoint=1024*(t-55296)+r-56320+65536,e.type="value",e.kind="unicodeCodePointEscape",n(e)):Y=l}}return e}function L(){return O(!0)}function O(e){var t;if(t=D())return t;if(e){if(x("b"))return s("singleEscape",8,"\\b");if(x("B"))throw SyntaxError("\\B not possible inside of CharacterClass")}return t=R()}function D(){var e,t;if(e=I(/^(?!0)\d+/)){t=e[0];var n=parseInt(e[0],10);return H>=n?c(e[0]):(z.push(n),b(-e[0].length),(e=I(/^[0-7]{1,3}/))?s("octal",parseInt(e[0],8),e[0],1):(e=a(I(/^[89]/)),r(e,e.range[0]-1)))}return(e=I(/^[0-7]{1,3}/))?(t=e[0],/^0{1,3}$/.test(t)?s("null",0,"0",t.length+1):s("octal",parseInt(t,8),t,1)):(e=I(/^[dDsSwW]/))?p(e[0]):!1}function R(){var e;if(e=I(/^[fnrtv]/)){var t=0;switch(e[0]){case"t":t=9;break;case"n":t=10;break;case"v":t=11;break;case"f":t=12;break;case"r":t=13}return s("singleEscape",t,"\\"+e[0])}return(e=I(/^c([a-zA-Z])/))?s("controlLetter",e[1].charCodeAt(0)%32,e[1],2):(e=I(/^x([0-9a-fA-F]{2})/))?s("hexadecimalEscape",parseInt(e[1],16),e[1],2):(e=I(/^u([0-9a-fA-F]{4})/))?P(s("unicodeEscape",parseInt(e[1],16),e[1],2)):X&&(e=I(/^u\{([0-9a-fA-F]+)\}/))?s("unicodeCodePointEscape",parseInt(e[1],16),e[1],4):F()}function N(e){var t=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return 36===e||95===e||e>=65&&90>=e||e>=97&&122>=e||e>=48&&57>=e||92===e||e>=128&&t.test(String.fromCharCode(e))}function F(){var e,t="",n="";return N(E())?x(t)?s("identifier",8204,t):x(n)?s("identifier",8205,n):null:(e=b(),s("identifier",e.charCodeAt(0),e,1))}function B(){var e,t=Y;return(e=I(/^\[\^/))?(e=$(),v("]"),m(e,!0,t,Y)):x("[")?(e=$(),v("]"),m(e,!1,t,Y)):null}function $(){var e;if(_("]"))return[];if(e=U(),!e)throw SyntaxError("nonEmptyClassRanges");return e}function V(e){var t,n,r;if(_("-")&&!S("]")){if(v("-"),r=G(),!r)throw SyntaxError("classAtom");n=Y;var l=$();if(!l)throw SyntaxError("classRanges");return t=e.range[0],"empty"===l.type?[g(e,r,t,n)]:[g(e,r,t,n)].concat(l)}if(r=q(),!r)throw SyntaxError("nonEmptyClassRangesNoDash");return[e].concat(r)}function U(){var e=G();if(!e)throw SyntaxError("classAtom");return _("]")?[e]:V(e)}function q(){var e=G();if(!e)throw SyntaxError("classAtom");return _("]")?e:V(e)}function G(){return x("-")?a("-"):W()}function W(){var e;if(e=I(/^[^\\\]-]/))return a(e[0]);if(x("\\")){if(e=L(),!e)throw SyntaxError("classEscape");return P(e)}}var z=[],H=0,J=!0,X=-1!==(t||"").indexOf("u"),Y=0;e=String(e),""===e&&(e="(?:)");var K=w();if(K.range[1]!==e.length)throw SyntaxError("Could not parse entire input - got stuck: "+e);for(var Q=0;Q<z.length;Q++)if(z[Q]<=H)return Y=0,J=!1,w();return K}var n={parse:e};"undefined"!=typeof t&&t.exports?t.exports=n:window.regjsparser=n}()},{}],436:[function(e,t){function n(e){return _?E?h.UNICODE_IGNORE_CASE[e]:h.UNICODE[e]:h.REGULAR[e]}function r(e,t){return g.call(e,t)}function l(e,t){for(var n in t)e[n]=t[n]}function i(e,t){if(t){var n=c(t,"");switch(n.type){case"characterClass":case"group":case"value":break;default:n=s(n,t)}l(e,n)}}function s(e,t){return{type:"group",behavior:"ignore",body:[e],raw:"(?:"+t+")"}}function a(e){return r(f,e)?f[e]:!1}function o(e){{var t=d();e.body.forEach(function(e){switch(e.type){case"value":if(t.add(e.codePoint),E&&_){var r=a(e.codePoint);r&&t.add(r)}break;case"characterClassRange":var l=e.min.codePoint,i=e.max.codePoint;t.addRange(l,i),E&&_&&t.iuAddRange(l,i);break;case"characterClassEscape":t.add(n(e.value));break;default:throw Error("Unknown term type: "+e.type)}})}return e.negative&&(t=(_?y:b).clone().remove(t)),i(e,t.toString()),e}function u(e){switch(e.type){case"dot":i(e,(_?v:x).toString());break;case"characterClass":e=o(e);break;case"characterClassEscape":i(e,n(e.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":e.body=e.body.map(u);break;case"value":var t=e.codePoint,r=d(t);if(E&&_){var l=a(t);l&&r.add(l)}i(e,r.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+e.type)}return e}var p=e("regjsgen").generate,c=e("regjsparser").parse,d=e("regenerate"),f=e("./data/iu-mappings.json"),h=e("./data/character-class-escape-sets.js"),m={},g=m.hasOwnProperty,y=d().addRange(0,1114111),b=d().addRange(0,65535),v=y.clone().remove(10,13,8232,8233),x=v.clone().intersection(b);d.prototype.iuAddRange=function(e,t){var n=this;do{var r=a(e);r&&n.add(r)}while(++e<=t);return n};var E=!1,_=!1;t.exports=function(e,t){var n=c(e,t);return E=t?t.indexOf("i")>-1:!1,_=t?t.indexOf("u")>-1:!1,l(n,u(n)),p(n)}},{"./data/character-class-escape-sets.js":431,"./data/iu-mappings.json":432,regenerate:433,regjsgen:434,regjsparser:435}],437:[function(e,t){"use strict";var n=e("is-finite");t.exports=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string as the first argument");if(0>t||!n(t))throw new TypeError("Expected a finite positive number");var r="";do 1&t&&(r+=e),e+=e;while(t>>=1);return r}},{"is-finite":438}],438:[function(e,t,n){arguments[4][304][0].apply(n,arguments)},{dup:304}],439:[function(e,t){"use strict";t.exports=/^#!.*/},{}],440:[function(e,t){"use strict";t.exports=function(e){var t=/^\\\\\?\\/.test(e),n=/[^\x00-\x80]+/.test(e);return t||n?e:e.replace(/\\/g,"/")}},{}],441:[function(e,t,n){n.SourceMapGenerator=e("./source-map/source-map-generator").SourceMapGenerator,n.SourceMapConsumer=e("./source-map/source-map-consumer").SourceMapConsumer,n.SourceNode=e("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":447,"./source-map/source-map-generator":448,"./source-map/source-node":449}],442:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(){this._array=[],this._set={}}var r=e("./util");n.fromArray=function(e,t){for(var r=new n,l=0,i=e.length;i>l;l++)r.add(e[l],t);return r},n.prototype.add=function(e,t){var n=this.has(e),l=this._array.length;(!n||t)&&this._array.push(e),n||(this._set[r.toSetString(e)]=l)},n.prototype.has=function(e){return Object.prototype.hasOwnProperty.call(this._set,r.toSetString(e))},n.prototype.indexOf=function(e){if(this.has(e))return this._set[r.toSetString(e)];throw new Error('"'+e+'" is not in the set.')},n.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)},n.prototype.toArray=function(){return this._array.slice()},t.ArraySet=n})},{"./util":450,amdefine:451}],443:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e){return 0>e?(-e<<1)+1:(e<<1)+0}function r(e){var t=1===(1&e),n=e>>1;return t?-n:n}var l=e("./base64"),i=5,s=1<<i,a=s-1,o=s;t.encode=function(e){var t,r="",s=n(e);do t=s&a,s>>>=i,s>0&&(t|=o),r+=l.encode(t);while(s>0);return r},t.decode=function(e,t,n){var s,u,p=e.length,c=0,d=0;do{if(t>=p)throw new Error("Expected more digits in base 64 VLQ value.");u=l.decode(e.charAt(t++)),s=!!(u&o),u&=a,c+=u<<d,d+=i}while(s);n.value=r(c),n.rest=t}})},{"./base64":444,amdefine:451}],444:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){var n={},r={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(e,t){n[e]=t,r[t]=e}),t.encode=function(e){if(e in r)return r[e];throw new TypeError("Must be between 0 and 63: "+e)},t.decode=function(e){if(e in n)return n[e];throw new TypeError("Not a valid base 64 digit: "+e)}})},{amdefine:451}],445:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e,r,l,i,s,a){var o=Math.floor((r-e)/2)+e,u=s(l,i[o],!0);return 0===u?o:u>0?r-o>1?n(o,r,l,i,s,a):a==t.LEAST_UPPER_BOUND?r<i.length?r:-1:o:o-e>1?n(e,o,l,i,s,a):a==t.LEAST_UPPER_BOUND?o:0>e?-1:e}t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2,t.search=function(e,r,l,i){if(0===r.length)return-1;var s=n(-1,r.length,e,r,l,i||t.GREATEST_LOWER_BOUND);if(0>s)return-1;for(;s-1>=0&&0===l(r[s],r[s-1],!0);)--s;return s}})},{amdefine:451}],446:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e,t){var n=e.generatedLine,r=t.generatedLine,i=e.generatedColumn,s=t.generatedColumn;return r>n||r==n&&s>=i||l.compareByGeneratedPositions(e,t)<=0}function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var l=e("./util");r.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},r.prototype.add=function(e){n(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},r.prototype.toArray=function(){return this._sorted||(this._array.sort(l.compareByGeneratedPositions),this._sorted=!0),this._array},t.MappingList=r})},{"./util":450,amdefine:451}],447:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e){var t=e;return"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=t.sections?new l(t):new r(t)}function r(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var n=i.getArg(t,"version"),r=i.getArg(t,"sources"),l=i.getArg(t,"names",[]),s=i.getArg(t,"sourceRoot",null),o=i.getArg(t,"sourcesContent",null),u=i.getArg(t,"mappings"),p=i.getArg(t,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);r=r.map(i.normalize),this._names=a.fromArray(l,!0),this._sources=a.fromArray(r,!0),this.sourceRoot=s,this.sourcesContent=o,this._mappings=u,this.file=p}function l(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=i.getArg(t,"version"),l=i.getArg(t,"sections");if(r!=this._version)throw new Error("Unsupported version: "+r);var s={line:-1,column:0};this._sections=l.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var t=i.getArg(e,"offset"),r=i.getArg(t,"line"),l=i.getArg(t,"column");if(r<s.line||r===s.line&&l<s.column)throw new Error("Section offsets must be ordered and non-overlapping.");return s=t,{generatedOffset:{generatedLine:r+1,generatedColumn:l+1},consumer:new n(i.getArg(e,"map"))}})}var i=e("./util"),s=e("./binary-search"),a=e("./array-set").ArraySet,o=e("./base64-vlq");n.fromSourceMap=function(e){return r.fromSourceMap(e)},n.prototype._version=3,n.prototype.__generatedMappings=null,Object.defineProperty(n.prototype,"_generatedMappings",{get:function(){return this.__generatedMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__generatedMappings}}),n.prototype.__originalMappings=null,Object.defineProperty(n.prototype,"_originalMappings",{get:function(){return this.__originalMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__originalMappings
}}),n.prototype._nextCharIsMappingSeparator=function(e,t){var n=e.charAt(t);return";"===n||","===n},n.prototype._parseMappings=function(){throw new Error("Subclasses must implement _parseMappings")},n.GENERATED_ORDER=1,n.ORIGINAL_ORDER=2,n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.prototype.eachMapping=function(e,t,r){var l,s=t||null,a=r||n.GENERATED_ORDER;switch(a){case n.GENERATED_ORDER:l=this._generatedMappings;break;case n.ORIGINAL_ORDER:l=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var o=this.sourceRoot;l.map(function(e){var t=e.source;return null!=t&&null!=o&&(t=i.join(o,t)),{source:t,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name}}).forEach(e,s)},n.prototype.allGeneratedPositionsFor=function(e){var t={source:i.getArg(e,"source"),originalLine:i.getArg(e,"line"),originalColumn:i.getArg(e,"column",0)};null!=this.sourceRoot&&(t.source=i.relative(this.sourceRoot,t.source));var n=[],r=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",i.compareByOriginalPositions,s.LEAST_UPPER_BOUND);if(r>=0)for(var l=this._originalMappings[r],a=l.originalLine,o=l.originalColumn;l&&l.originalLine===a&&(void 0===e.column||l.originalColumn===o);)n.push({line:i.getArg(l,"generatedLine",null),column:i.getArg(l,"generatedColumn",null),lastColumn:i.getArg(l,"lastGeneratedColumn",null)}),l=this._originalMappings[++r];return n},t.SourceMapConsumer=n,r.prototype=Object.create(n.prototype),r.prototype.consumer=n,r.fromSourceMap=function(e){var t=Object.create(r.prototype);return t._names=a.fromArray(e._names.toArray(),!0),t._sources=a.fromArray(e._sources.toArray(),!0),t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file,t.__generatedMappings=e._mappings.toArray().slice(),t.__originalMappings=e._mappings.toArray().slice().sort(i.compareByOriginalPositions),t},r.prototype._version=3,Object.defineProperty(r.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?i.join(this.sourceRoot,e):e},this)}}),r.prototype._parseMappings=function(e){for(var t,n,r,l,s,a=1,u=0,p=0,c=0,d=0,f=0,h=e.length,m=0,g={},y={};h>m;)if(";"===e.charAt(m))a++,++m,u=0;else if(","===e.charAt(m))++m;else{for(t={},t.generatedLine=a,l=m;h>l&&!this._nextCharIsMappingSeparator(e,l);++l);if(n=e.slice(m,l),r=g[n])m+=n.length;else{for(r=[];l>m;)o.decode(e,m,y),s=y.value,m=y.rest,r.push(s);g[n]=r}if(t.generatedColumn=u+r[0],u=t.generatedColumn,r.length>1){if(t.source=this._sources.at(d+r[1]),d+=r[1],2===r.length)throw new Error("Found a source, but no line and column");if(t.originalLine=p+r[2],p=t.originalLine,t.originalLine+=1,3===r.length)throw new Error("Found a source and line, but no column");t.originalColumn=c+r[3],c=t.originalColumn,r.length>4&&(t.name=this._names.at(f+r[4]),f+=r[4])}this.__generatedMappings.push(t),"number"==typeof t.originalLine&&this.__originalMappings.push(t)}this.__generatedMappings.sort(i.compareByGeneratedPositions),this.__originalMappings.sort(i.compareByOriginalPositions)},r.prototype._findMapping=function(e,t,n,r,l,i){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[r]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[r]);return s.search(e,t,l,i)},r.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var t=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(t.generatedLine===n.generatedLine){t.lastGeneratedColumn=n.generatedColumn-1;continue}}t.lastGeneratedColumn=1/0}},r.prototype.originalPositionFor=function(e){var t={generatedLine:i.getArg(e,"line"),generatedColumn:i.getArg(e,"column")},r=this._findMapping(t,this._generatedMappings,"generatedLine","generatedColumn",i.compareByGeneratedPositions,i.getArg(e,"bias",n.GREATEST_LOWER_BOUND));if(r>=0){var l=this._generatedMappings[r];if(l.generatedLine===t.generatedLine){var s=i.getArg(l,"source",null);return null!=s&&null!=this.sourceRoot&&(s=i.join(this.sourceRoot,s)),{source:s,line:i.getArg(l,"originalLine",null),column:i.getArg(l,"originalColumn",null),name:i.getArg(l,"name",null)}}}return{source:null,line:null,column:null,name:null}},r.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=i.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var n;if(null!=this.sourceRoot&&(n=i.urlParse(this.sourceRoot))){var r=e.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(r))return this.sourcesContent[this._sources.indexOf(r)];if((!n.path||"/"==n.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},r.prototype.generatedPositionFor=function(e){var t={source:i.getArg(e,"source"),originalLine:i.getArg(e,"line"),originalColumn:i.getArg(e,"column")};null!=this.sourceRoot&&(t.source=i.relative(this.sourceRoot,t.source));var r=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",i.compareByOriginalPositions,i.getArg(e,"bias",n.GREATEST_LOWER_BOUND));if(r>=0){var l=this._originalMappings[r];if(l.source===t.source)return{line:i.getArg(l,"generatedLine",null),column:i.getArg(l,"generatedColumn",null),lastColumn:i.getArg(l,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},t.BasicSourceMapConsumer=r,l.prototype=Object.create(n.prototype),l.prototype.constructor=n,l.prototype._version=3,Object.defineProperty(l.prototype,"sources",{get:function(){for(var e=[],t=0;t<this._sections.length;t++)for(var n=0;n<this._sections[t].consumer.sources.length;n++)e.push(this._sections[t].consumer.sources[n]);return e}}),l.prototype.originalPositionFor=function(e){var t={generatedLine:i.getArg(e,"line"),generatedColumn:i.getArg(e,"column")},n=s.search(t,this._sections,function(e,t){var n=e.generatedLine-t.generatedOffset.generatedLine;return n?n:e.generatedColumn-t.generatedOffset.generatedColumn}),r=this._sections[n];return r?r.consumer.originalPositionFor({line:t.generatedLine-(r.generatedOffset.generatedLine-1),column:t.generatedColumn-(r.generatedOffset.generatedLine===t.generatedLine?r.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}},l.prototype.sourceContentFor=function(e,t){for(var n=0;n<this._sections.length;n++){var r=this._sections[n],l=r.consumer.sourceContentFor(e,!0);if(l)return l}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},l.prototype.generatedPositionFor=function(e){for(var t=0;t<this._sections.length;t++){var n=this._sections[t];if(-1!==n.consumer.sources.indexOf(i.getArg(e,"source"))){var r=n.consumer.generatedPositionFor(e);if(r){var l={line:r.line+(n.generatedOffset.generatedLine-1),column:r.column+(n.generatedOffset.generatedLine===r.line?n.generatedOffset.generatedColumn-1:0)};return l}}}return{line:null,column:null}},l.prototype._parseMappings=function(){this.__generatedMappings=[],this.__originalMappings=[];for(var e=0;e<this._sections.length;e++)for(var t=this._sections[e],n=t.consumer._generatedMappings,r=0;r<n.length;r++){var l=n[e],s=l.source,a=t.consumer.sourceRoot;null!=s&&null!=a&&(s=i.join(a,s));var o={source:s,generatedLine:l.generatedLine+(t.generatedOffset.generatedLine-1),generatedColumn:l.column+(t.generatedOffset.generatedLine===l.generatedLine)?t.generatedOffset.generatedColumn-1:0,originalLine:l.originalLine,originalColumn:l.originalColumn,name:l.name};this.__generatedMappings.push(o),"number"==typeof o.originalLine&&this.__originalMappings.push(o)}this.__generatedMappings.sort(i.compareByGeneratedPositions),this.__originalMappings.sort(i.compareByOriginalPositions)},t.IndexedSourceMapConsumer=l})},{"./array-set":442,"./base64-vlq":443,"./binary-search":445,"./util":450,amdefine:451}],448:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e){e||(e={}),this._file=l.getArg(e,"file",null),this._sourceRoot=l.getArg(e,"sourceRoot",null),this._skipValidation=l.getArg(e,"skipValidation",!1),this._sources=new i,this._names=new i,this._mappings=new s,this._sourcesContents=null}var r=e("./base64-vlq"),l=e("./util"),i=e("./array-set").ArraySet,s=e("./mapping-list").MappingList;n.prototype._version=3,n.fromSourceMap=function(e){var t=e.sourceRoot,r=new n({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var n={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(n.source=e.source,null!=t&&(n.source=l.relative(t,n.source)),n.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(n.name=e.name)),r.addMapping(n)}),e.sources.forEach(function(t){var n=e.sourceContentFor(t);null!=n&&r.setSourceContent(t,n)}),r},n.prototype.addMapping=function(e){var t=l.getArg(e,"generated"),n=l.getArg(e,"original",null),r=l.getArg(e,"source",null),i=l.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,r,i),null==r||this._sources.has(r)||this._sources.add(r),null==i||this._names.has(i)||this._names.add(i),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:r,name:i})},n.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=l.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents={}),this._sourcesContents[l.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[l.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},n.prototype.applySourceMap=function(e,t,n){var r=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');r=e.file}var s=this._sourceRoot;null!=s&&(r=l.relative(s,r));var a=new i,o=new i;this._mappings.unsortedForEach(function(t){if(t.source===r&&null!=t.originalLine){var i=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=i.source&&(t.source=i.source,null!=n&&(t.source=l.join(n,t.source)),null!=s&&(t.source=l.relative(s,t.source)),t.originalLine=i.line,t.originalColumn=i.column,null!=i.name&&(t.name=i.name))}var u=t.source;null==u||a.has(u)||a.add(u);var p=t.name;null==p||o.has(p)||o.add(p)},this),this._sources=a,this._names=o,e.sources.forEach(function(t){var r=e.sourceContentFor(t);null!=r&&(null!=n&&(t=l.join(n,t)),null!=s&&(t=l.relative(s,t)),this.setSourceContent(t,r))},this)},n.prototype._validateMapping=function(e,t,n,r){if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!t&&!n&&!r||e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:r}))},n.prototype._serializeMappings=function(){for(var e,t=0,n=1,i=0,s=0,a=0,o=0,u="",p=this._mappings.toArray(),c=0,d=p.length;d>c;c++){if(e=p[c],e.generatedLine!==n)for(t=0;e.generatedLine!==n;)u+=";",n++;else if(c>0){if(!l.compareByGeneratedPositions(e,p[c-1]))continue;u+=","}u+=r.encode(e.generatedColumn-t),t=e.generatedColumn,null!=e.source&&(u+=r.encode(this._sources.indexOf(e.source)-o),o=this._sources.indexOf(e.source),u+=r.encode(e.originalLine-1-s),s=e.originalLine-1,u+=r.encode(e.originalColumn-i),i=e.originalColumn,null!=e.name&&(u+=r.encode(this._names.indexOf(e.name)-a),a=this._names.indexOf(e.name)))}return u},n.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=l.relative(t,e));var n=l.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},n.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},n.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=n})},{"./array-set":442,"./base64-vlq":443,"./mapping-list":446,"./util":450,amdefine:451}],449:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e,t,n,r,l){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==n?null:n,this.name=null==l?null:l,this[a]=!0,null!=r&&this.add(r)}var r=e("./source-map-generator").SourceMapGenerator,l=e("./util"),i=/(\r?\n)/,s=10,a="$$$isSourceNode$$$";n.fromStringWithSourceMap=function(e,t,r){function s(e,t){if(null===e||void 0===e.source)a.add(t);else{var i=r?l.join(r,e.source):e.source;a.add(new n(e.originalLine,e.originalColumn,i,t,e.name))}}var a=new n,o=e.split(i),u=function(){var e=o.shift(),t=o.shift()||"";return e+t},p=1,c=0,d=null;return t.eachMapping(function(e){if(null!==d){if(!(p<e.generatedLine)){var t=o[0],n=t.substr(0,e.generatedColumn-c);return o[0]=t.substr(e.generatedColumn-c),c=e.generatedColumn,s(d,n),void(d=e)}var n="";s(d,u()),p++,c=0}for(;p<e.generatedLine;)a.add(u()),p++;if(c<e.generatedColumn){var t=o[0];a.add(t.substr(0,e.generatedColumn)),o[0]=t.substr(e.generatedColumn),c=e.generatedColumn}d=e},this),o.length>0&&(d&&s(d,u()),a.add(o.join(""))),t.sources.forEach(function(e){var n=t.sourceContentFor(e);null!=n&&(null!=r&&(e=l.join(r,e)),a.setSourceContent(e,n))}),a},n.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[a]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},n.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else{if(!e[a]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},n.prototype.walk=function(e){for(var t,n=0,r=this.children.length;r>n;n++)t=this.children[n],t[a]?t.walk(e):""!==t&&e(t,{source:this.source,line:this.line,column:this.column,name:this.name})},n.prototype.join=function(e){var t,n,r=this.children.length;if(r>0){for(t=[],n=0;r-1>n;n++)t.push(this.children[n]),t.push(e);t.push(this.children[n]),this.children=t}return this},n.prototype.replaceRight=function(e,t){var n=this.children[this.children.length-1];return n[a]?n.replaceRight(e,t):"string"==typeof n?this.children[this.children.length-1]=n.replace(e,t):this.children.push("".replace(e,t)),this},n.prototype.setSourceContent=function(e,t){this.sourceContents[l.toSetString(e)]=t},n.prototype.walkSourceContents=function(e){for(var t=0,n=this.children.length;n>t;t++)this.children[t][a]&&this.children[t].walkSourceContents(e);for(var r=Object.keys(this.sourceContents),t=0,n=r.length;n>t;t++)e(l.fromSetString(r[t]),this.sourceContents[r[t]])},n.prototype.toString=function(){var e="";return this.walk(function(t){e+=t}),e},n.prototype.toStringWithSourceMap=function(e){var t={code:"",line:1,column:0},n=new r(e),l=!1,i=null,a=null,o=null,u=null;return this.walk(function(e,r){t.code+=e,null!==r.source&&null!==r.line&&null!==r.column?((i!==r.source||a!==r.line||o!==r.column||u!==r.name)&&n.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:t.line,column:t.column},name:r.name}),i=r.source,a=r.line,o=r.column,u=r.name,l=!0):l&&(n.addMapping({generated:{line:t.line,column:t.column}}),i=null,l=!1);for(var p=0,c=e.length;c>p;p++)e.charCodeAt(p)===s?(t.line++,t.column=0,p+1===c?(i=null,l=!1):l&&n.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:t.line,column:t.column},name:r.name})):t.column++}),this.walkSourceContents(function(e,t){n.setSourceContent(e,t)}),{code:t.code,map:n}},t.SourceNode=n})},{"./source-map-generator":448,"./util":450,amdefine:451}],450:[function(e,t){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t){function n(e,t,n){if(t in e)return e[t];if(3===arguments.length)return n;throw new Error('"'+t+'" is a required argument.')}function r(e){var t=e.match(f);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function l(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function i(e){var t=e,n=r(e);if(n){if(!n.path)return e;t=n.path}for(var i,s="/"===t.charAt(0),a=t.split(/\/+/),o=0,u=a.length-1;u>=0;u--)i=a[u],"."===i?a.splice(u,1):".."===i?o++:o>0&&(""===i?(a.splice(u+1,o),o=0):(a.splice(u,2),o--));return t=a.join("/"),""===t&&(t=s?"/":"."),n?(n.path=t,l(n)):t}function s(e,t){""===e&&(e="."),""===t&&(t=".");var n=r(t),s=r(e);if(s&&(e=s.path||"/"),n&&!n.scheme)return s&&(n.scheme=s.scheme),l(n);if(n||t.match(h))return t;if(s&&!s.host&&!s.path)return s.host=t,l(s);var a="/"===t.charAt(0)?t:i(e.replace(/\/+$/,"")+"/"+t);return s?(s.path=a,l(s)):a}function a(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");var n=r(e);return"/"==t.charAt(0)&&n&&"/"==n.path?t.slice(1):0===t.indexOf(e+"/")?t.substr(e.length+1):t}function o(e){return"$"+e}function u(e){return e.substr(1)}function p(e,t){var n=e||"",r=t||"";return(n>r)-(r>n)}function c(e,t,n){var r;return(r=p(e.source,t.source))?r:(r=e.originalLine-t.originalLine)?r:(r=e.originalColumn-t.originalColumn,r||n?r:(r=e.generatedColumn-t.generatedColumn)?r:(r=e.generatedLine-t.generatedLine,r?r:p(e.name,t.name)))}function d(e,t,n){var r;return(r=e.generatedLine-t.generatedLine)?r:(r=e.generatedColumn-t.generatedColumn,r||n?r:(r=p(e.source,t.source))?r:(r=e.originalLine-t.originalLine)?r:(r=e.originalColumn-t.originalColumn,r?r:p(e.name,t.name)))}t.getArg=n;var f=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,h=/^data:.+\,.+$/;t.urlParse=r,t.urlGenerate=l,t.normalize=i,t.join=s,t.relative=a,t.toSetString=o,t.fromSetString=u,t.compareByOriginalPositions=c,t.compareByGeneratedPositions=d})},{amdefine:451}],451:[function(e,t){(function(n,r){"use strict";function l(t,l){function i(e){var t,n;for(t=0;e[t];t+=1)if(n=e[t],"."===n)e.splice(t,1),t-=1;else if(".."===n){if(1===t&&(".."===e[2]||".."===e[0]))break;t>0&&(e.splice(t-1,2),t-=2)}}function s(e,t){var n;return e&&"."===e.charAt(0)&&t&&(n=t.split("/"),n=n.slice(0,n.length-1),n=n.concat(e.split("/")),i(n),e=n.join("/")),e}function a(e){return function(t){return s(t,e)}}function o(e){function t(t){h[e]=t}return t.fromText=function(){throw new Error("amdefine does not implement load.fromText")},t}function u(e,n,i){var s,a,o,u;if(e)a=h[e]={},o={id:e,uri:r,exports:a},s=c(l,a,o,e);else{if(m)throw new Error("amdefine with no module ID cannot be called more than once per file.");m=!0,a=t.exports,o=t,s=c(l,a,o,t.id)}n&&(n=n.map(function(e){return s(e)})),u="function"==typeof i?i.apply(o.exports,n):i,void 0!==u&&(o.exports=u,e&&(h[e]=o.exports))}function p(e,t,n){Array.isArray(e)?(n=t,t=e,e=void 0):"string"!=typeof e&&(n=e,e=t=void 0),t&&!Array.isArray(t)&&(n=t,t=void 0),t||(t=["require","exports","module"]),e?f[e]=[e,t,n]:u(e,t,n)}var c,d,f={},h={},m=!1,g=e("path");return c=function(e,t,r,l){function i(i,s){return"string"==typeof i?d(e,t,r,i,l):(i=i.map(function(n){return d(e,t,r,n,l)}),void n.nextTick(function(){s.apply(null,i)}))}return i.toUrl=function(e){return 0===e.indexOf(".")?s(e,g.dirname(r.filename)):e},i},l=l||function(){return t.require.apply(t,arguments)},d=function(e,t,n,r,l){var i,p,m=r.indexOf("!"),g=r;if(-1===m){if(r=s(r,l),"require"===r)return c(e,t,n,l);if("exports"===r)return t;if("module"===r)return n;if(h.hasOwnProperty(r))return h[r];if(f[r])return u.apply(null,f[r]),h[r];if(e)return e(g);throw new Error("No module with ID: "+r)}return i=r.substring(0,m),r=r.substring(m+1,r.length),p=d(e,t,n,i,l),r=p.normalize?p.normalize(r,a(l)):s(r,l),h[r]?h[r]:(p.load(r,c(e,t,n,l),o(r),{}),h[r])},p.require=function(e){return h[e]?h[e]:f[e]?(u.apply(null,f[e]),h[e]):void 0},p.amd={},p}t.exports=l}).call(this,e("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:183,path:182}],452:[function(e,t,n){"use strict";t.exports=function r(e){function t(){}t.prototype=e,new t}},{}],453:[function(e,t){"use strict";t.exports=function(e){return e.replace(/[\s\uFEFF\xA0]+$/g,"")}},{}],454:[function(e,t){t.exports={name:"babel-core",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"5.0.10",author:"Sebastian McKenzie <[email protected]>",homepage:"https://babeljs.io/",repository:"babel/babel",main:"lib/babel/api/node.js",browser:{"./lib/babel/api/register/node.js":"./lib/babel/api/register/browser.js"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5","babel"],scripts:{bench:"make bench",test:"make test"},dependencies:{"ast-types":"~0.7.0",chalk:"^1.0.0","convert-source-map":"^0.5.0","core-js":"^0.8.1",debug:"^2.1.1","detect-indent":"^3.0.0",estraverse:"^1.9.1",esutils:"^1.1.6","fs-readdir-recursive":"^0.1.0",globals:"^6.2.0","is-integer":"^1.0.4","js-tokens":"1.0.0",leven:"^1.0.1","line-numbers":"0.2.0",lodash:"^3.2.0",minimatch:"^2.0.3","output-file-sync":"^1.1.0","path-is-absolute":"^1.0.0","private":"^0.1.6","regenerator-babel":"0.8.13-2",regexpu:"^1.1.2",repeating:"^1.1.2","shebang-regex":"^1.0.0",slash:"^1.0.0","source-map":"^0.4.0","source-map-support":"^0.2.9","to-fast-properties":"^1.0.0","trim-right":"^1.0.0"},devDependencies:{babel:"4.7.13",browserify:"^9.0.3",chai:"^2.0.0",eslint:"^0.15.1","babel-eslint":"^1.0.1",esvalid:"^1.1.0",istanbul:"^0.3.5",matcha:"^0.6.0",mocha:"^2.1.0",rimraf:"^2.2.8","uglify-js":"^2.4.16"}}},{}],455:[function(e,t){t.exports={"abstract-expression-call":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"PROPERTY",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"referenceGet",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"abstract-expression-delete":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"PROPERTY",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"referenceDelete",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"abstract-expression-get":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"PROPERTY",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"referenceGet",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"abstract-expression-set":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"PROPERTY",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"referenceSet",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"array-comprehension-container":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},init:{start:null,loc:null,range:null,elements:[],type:"ArrayExpression",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"array-from":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"from",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"array-push":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"push",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"STATEMENT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"call-instance-decorator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,type:"ThisExpression",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"INITIALIZERS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null}],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"call-static-decorator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"CONSTRUCTOR",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"INITIALIZERS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"CONSTRUCTOR",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},call:{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"CONTEXT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"class-decorator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"CLASS_REF",type:"Identifier",end:null},right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"DECORATOR",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"CLASS_REF",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},operator:"||",right:{start:null,loc:null,range:null,name:"CLASS_REF",type:"Identifier",end:null},type:"LogicalExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"class-super-constructor-call-loose":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"SUPER_NAME",type:"Identifier",end:null},operator:"!=",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"SUPER_NAME",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"apply",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null},{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"Program",end:null},"class-super-constructor-call":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"SUPER_NAME",type:"Identifier",end:null},operator:"!=",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"SUPER_NAME",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"apply",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null},{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"Program",end:null},"corejs-is-iterator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"CORE_ID",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isIterable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"corejs-iterator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"CORE_ID",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getIterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"default-parameter":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"VARIABLE_NAME",type:"Identifier",end:null},init:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARGUMENTS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"ARGUMENT_KEY",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,name:"DEFAULT_VALUE",type:"Identifier",end:null},alternate:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARGUMENTS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"ARGUMENT_KEY",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"ConditionalExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"let",type:"VariableDeclaration",end:null}],type:"Program",end:null},"exports-assign":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"exports-default-assign":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"module",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"VALUE",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"exports-from-assign":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"ID",type:"Identifier",end:null},{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"get",type:"Identifier",end:null},value:{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"get",type:"Identifier",end:null},generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"INIT",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"exports-module-declaration-loose":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"__esModule",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"exports-module-declaration":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},{start:null,loc:null,range:null,value:"__esModule",raw:null,type:"Literal",end:null},{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"for-of-array":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARR",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,name:"BODY",type:"Identifier",end:null},type:"ExpressionStatement",end:null,_paths:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"Program",end:null},"for-of-loose":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},init:{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"IS_ARRAY",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isArray",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},init:{loc:null,start:null,range:null,test:{start:null,loc:null,range:null,name:"IS_ARRAY",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},alternate:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ConditionalExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:null,update:null,body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ID",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"IS_ARRAY",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},operator:">=",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"BreakStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ID",type:"Identifier",end:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},property:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"LOOP_OBJECT",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"next",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"done",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"BreakStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ID",type:"Identifier",end:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"INDEX",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"Program",end:null},"for-of":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ITERATOR_COMPLETION",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ITERATOR_HAD_ERROR_KEY",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:!1,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ITERATOR_ERROR_KEY",type:"Identifier",end:null},init:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,block:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ITERATOR_KEY",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"OBJECT",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"STEP_KEY",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ITERATOR_COMPLETION",type:"Identifier",end:null},right:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"STEP_KEY",type:"Identifier",end:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ITERATOR_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"next",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,parenthesizedExpression:!0,_paths:null},property:{start:null,loc:null,range:null,name:"done",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,parenthesizedExpression:!0,_paths:null},type:"UnaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ITERATOR_COMPLETION",type:"Identifier",end:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},handler:{start:null,loc:null,range:null,param:{start:null,loc:null,range:null,name:"err",type:"Identifier",end:null},guard:null,body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ITERATOR_HAD_ERROR_KEY",type:"Identifier",end:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"ITERATOR_ERROR_KEY",type:"Identifier",end:null},right:{start:null,loc:null,range:null,name:"err",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"CatchClause",end:null,_scopeInfo:null,_paths:null},guardedHandlers:[],finalizer:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,block:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{start:null,loc:null,range:null,name:"ITERATOR_COMPLETION",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ITERATOR_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"return",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ITERATOR_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"return",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},handler:null,guardedHandlers:[],finalizer:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"ITERATOR_HAD_ERROR_KEY",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"ITERATOR_ERROR_KEY",type:"Identifier",end:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"TryStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"TryStatement",end:null,_paths:null}],type:"Program",end:null},"helper-async-to-generator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"fn",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"gen",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"fn",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"apply",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null},{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"Promise",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"resolve",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"reject",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"callNext",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"step",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"bind",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},{start:null,loc:null,range:null,value:"next",raw:null,type:"Literal",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"callThrow",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"step",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"bind",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},{start:null,loc:null,range:null,value:"throw",raw:null,type:"Literal",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"step",type:"Identifier",end:null},generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"arg",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,block:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"info",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"gen",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arg",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"info",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null}],type:"BlockStatement",end:null,_scopeInfo:null},handler:{start:null,loc:null,range:null,param:{start:null,loc:null,range:null,name:"error",type:"Identifier",end:null},guard:null,body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"reject",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"error",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:null,type:"ReturnStatement",end:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"CatchClause",end:null,_scopeInfo:null,_paths:null},guardedHandlers:[],finalizer:null,type:"TryStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"info",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"done",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"resolve",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Promise",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"resolve",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"then",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"callNext",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"callThrow",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"callNext",type:"Identifier",end:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null}],type:"NewExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-bind":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Function",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"bind",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-class-call-check":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"instance",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"instance",type:"Identifier",end:null},operator:"instanceof",right:{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},type:"BinaryExpression",end:null,parenthesizedExpression:!0,_paths:null},type:"UnaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,value:"Cannot call a class as a function",raw:null,type:"Literal",end:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-create-class":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"||",right:{start:null,loc:null,range:null,value:!1,raw:null,type:"Literal",end:null},type:"LogicalExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"configurable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"value",raw:null,type:"Literal",end:null},operator:"in",right:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"writable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-create-decorated-class":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"descriptors",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"initializers",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptors",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptors",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,operator:"delete",prefix:!0,argument:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"UnaryExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,leadingComments:null,_paths:null},{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,operator:"delete",prefix:!0,argument:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"UnaryExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"||",right:{start:null,loc:null,range:null,value:!1,raw:null,type:"Literal",end:null},type:"LogicalExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"configurable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"value",raw:null,type:"Literal",end:null},operator:"in",right:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"||",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"initializer",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"writable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"f",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"f",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"f",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"decorator",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"decorators",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"f",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"decorator",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"function",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"decorator",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},operator:"||",right:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},type:"LogicalExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"The decorator for method ",raw:null,type:"Literal",end:null},operator:"+",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},operator:"+",right:{start:null,loc:null,range:null,value:" is of the invalid type ",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"+",right:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"decorator",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"initializers",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"initializers",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"initializer",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"descriptor",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"protoInitializers",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticInitializers",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},{start:null,loc:null,range:null,name:"protoProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"protoInitializers",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"staticInitializers",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"Constructor",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-default-props":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"defaultProps",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"defaultProps",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,left:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"propName",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},right:{start:null,loc:null,range:null,name:"defaultProps",type:"Identifier",end:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"propName",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"undefined",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"propName",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"defaultProps",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"propName",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForInStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"props",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-defaults":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"defaults",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"keys",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getOwnPropertyNames",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"defaults",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"keys",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"keys",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getOwnPropertyDescriptor",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"defaults",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"configurable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-define-property":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},value:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},value:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},operator:"==",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"||",right:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"==",right:{start:null,loc:null,range:null,value:"undefined",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},operator:"||",right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"constructor",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"!==",right:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"configurable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"writable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-extends":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"assign",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"||",right:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:1,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"source",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,left:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},right:{start:null,loc:null,range:null,name:"source",type:"Identifier",end:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"hasOwnProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"source",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"source",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"key",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForInStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-get":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"get",type:"Identifier",end:null},generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getOwnPropertyDescriptor",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},operator:"===",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getPrototypeOf",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},operator:"===",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"get",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"value",raw:null,type:"Literal",end:null},operator:"in",right:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"getter",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"get",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"getter",type:"Identifier",end:null},operator:"===",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"getter",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-has-own":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"hasOwnProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-inherits":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"subClass",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"!==",right:{start:null,loc:null,range:null,value:"function",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},operator:"!==",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,type:"Literal",end:null},operator:"+",right:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"subClass",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"create",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"constructor",type:"Identifier",end:null},value:{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},value:{start:null,loc:null,range:null,name:"subClass",type:"Identifier",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"enumerable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!1,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"writable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"configurable",type:"Identifier",end:null},value:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null}],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"subClass",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"__proto__",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"superClass",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-interop-require-wildcard":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"__esModule",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},alternate:{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,value:"default",raw:null,type:"Literal",end:null},value:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null},type:"ConditionalExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-interop-require":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"__esModule",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"default",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},alternate:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},type:"ConditionalExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-object-destructuring-empty":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},operator:"==",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,value:"Cannot destructure undefined",raw:null,type:"Literal",end:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-object-without-properties":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"keys",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},init:{start:null,loc:null,range:null,properties:[],type:"ObjectExpression",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,left:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},right:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"keys",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"indexOf",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},operator:">=",right:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"ContinueStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"hasOwnProperty",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"UnaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"ContinueStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForInStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"target",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-self-global":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"global",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"undefined",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,name:"self",type:"Identifier",end:null},alternate:{start:null,loc:null,range:null,name:"global",type:"Identifier",end:null},type:"ConditionalExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-set":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"set",type:"Identifier",end:null},generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getOwnPropertyDescriptor",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},operator:"===",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"getPrototypeOf",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"object",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},operator:"!==",right:{start:null,loc:null,range:null,value:null,raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"set",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"parent",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"property",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,value:"value",raw:null,type:"Literal",end:null},operator:"in",right:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"writable",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"setter",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"desc",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"set",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"setter",type:"Identifier",end:null},operator:"!==",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"setter",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"call",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"receiver",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-slice":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"slice",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-sliced-to-array-loose":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isArray",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"in",right:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},init:{start:null,loc:null,range:null,elements:[],type:"ArrayExpression",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_iterator",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_step",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_step",type:"Identifier",end:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_iterator",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"next",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,parenthesizedExpression:!0,_paths:null},property:{start:null,loc:null,range:null,name:"done",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"UnaryExpression",end:null,_paths:null},update:null,body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"push",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_step",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"BreakStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,value:"Invalid attempt to destructure non-iterable instance",raw:null,type:"Literal",end:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-sliced-to-array":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isArray",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"in",right:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},init:{start:null,loc:null,range:null,elements:[],type:"ArrayExpression",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null,leadingComments:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_n",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_d",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:!1,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_e",type:"Identifier",end:null},init:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,block:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_i",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},property:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"iterator",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"_s",type:"Identifier",end:null},init:null,type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_n",type:"Identifier",end:null},right:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_s",type:"Identifier",end:null},right:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_i",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"next",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,parenthesizedExpression:!0,_paths:null},property:{start:null,loc:null,range:null,name:"done",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,parenthesizedExpression:!0,_paths:null},type:"UnaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_n",type:"Identifier",end:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"push",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_s",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,label:null,type:"BreakStatement",end:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},handler:{start:null,loc:null,range:null,param:{start:null,loc:null,range:null,name:"err",type:"Identifier",end:null},guard:null,body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_d",type:"Identifier",end:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{start:null,loc:null,range:null,name:"_e",type:"Identifier",end:null},right:{start:null,loc:null,range:null,name:"err",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"CatchClause",end:null,_scopeInfo:null,_paths:null},guardedHandlers:[],finalizer:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,block:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"!",prefix:!0,argument:{start:null,loc:null,range:null,name:"_n",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_i",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"return",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"_i",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"return",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},handler:null,guardedHandlers:[],finalizer:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"_d",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"_e",type:"Identifier",end:null},type:"ThrowStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"TryStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"TryStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"_arr",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"TypeError",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,value:"Invalid attempt to destructure non-iterable instance",raw:null,type:"Literal",end:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-tagged-template-literal-loose":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"strings",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"strings",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"strings",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-tagged-template-literal":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"strings",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"freeze",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"defineProperties",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"strings",type:"Identifier",end:null},{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null},value:{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"value",type:"Identifier",end:null},value:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"freeze",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"raw",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null}],type:"CallExpression",end:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-temporal-assert-defined":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"val",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"name",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"undef",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"val",type:"Identifier",end:null},operator:"===",right:{start:null,loc:null,range:null,name:"undef",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,callee:{start:null,loc:null,range:null,name:"ReferenceError",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"name",type:"Identifier",end:null},operator:"+",right:{start:null,loc:null,range:null,value:" is not defined - temporal dead zone",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null}],type:"NewExpression",end:null,_paths:null},type:"ThrowStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:null,type:"IfStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-temporal-undefined":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,properties:[],type:"ObjectExpression",end:null,parenthesizedExpression:!0},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-to-array":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isArray",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},alternate:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"from",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ConditionalExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-to-consumable-array":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"isArray",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"arr2",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},operator:"<",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr2",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"i",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"arr2",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"from",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"arr",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"helper-typeof":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},operator:"&&",right:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"constructor",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,name:"Symbol",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,value:"symbol",raw:null,type:"Literal",end:null},alternate:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"obj",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},type:"ConditionalExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"let-scoping-return":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"RETURN",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"object",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"RETURN",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"v",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null},alternate:null,type:"IfStatement",end:null,_paths:null}],type:"Program",end:null},"ludicrous-in":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"Object",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"RIGHT",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"LEFT",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},operator:"!==",right:{start:null,loc:null,range:null,name:"undefined",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"named-function":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"GET_OUTER_ID",type:"Identifier",end:null},generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"FUNCTION",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"property-method-assignment-wrapper-generator":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"FUNCTION_KEY",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},generator:!0,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,delegate:!0,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"apply",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null},{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"YieldExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"toString",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"toString",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"FUNCTION",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"property-method-assignment-wrapper":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"FUNCTION_KEY",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"apply",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,type:"ThisExpression",end:null},{start:null,loc:null,range:null,name:"arguments",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionDeclaration",end:null,_scopeInfo:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"toString",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"FUNCTION_KEY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"toString",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[],type:"CallExpression",end:null,_paths:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"FUNCTION",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"prototype-identifier":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"CLASS_NAME",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"prototype",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"require-assign-key":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"VARIABLE_NAME",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"require",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"MODULE_NAME",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null}],type:"Program",end:null},require:{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"require",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"MODULE_NAME",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},rest:{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,init:{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"LEN",type:"Identifier",end:null},init:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARGUMENTS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"length",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"ARRAY",type:"Identifier",end:null},init:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"Array",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"ARRAY_LEN",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"VariableDeclarator",end:null,_paths:null},{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},init:{start:null,loc:null,range:null,name:"START",type:"Identifier",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},operator:"<",right:{start:null,loc:null,range:null,name:"LEN",type:"Identifier",end:null},type:"BinaryExpression",end:null,_paths:null},update:{loc:null,start:null,range:null,operator:"++",prefix:!1,argument:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},type:"UpdateExpression",end:null,_paths:null},body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARRAY",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"ARRAY_KEY",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"ARGUMENTS",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"KEY",type:"Identifier",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"ForStatement",end:null,_scopeInfo:null,_paths:null}],type:"Program",end:null},"self-contained-helpers-head":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},property:{start:null,loc:null,range:null,value:"default",raw:null,type:"Literal",end:null},computed:!0,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,name:"HELPER",type:"Identifier",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"__esModule",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},system:{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"System",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"register",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"MODULE_NAME",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",type:"Identifier",end:null},{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,argument:{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"setters",type:"Identifier",end:null},value:{start:null,loc:null,range:null,name:"SETTERS",type:"Identifier",end:null},kind:"init",type:"Property",end:null,_paths:null},{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"execute",type:"Identifier",end:null},value:{start:null,loc:null,range:null,name:"EXECUTE",type:"Identifier",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null},type:"ReturnStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"tail-call-body":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"AGAIN_ID",type:"Identifier",end:null},init:{start:null,loc:null,range:null,value:!0,raw:null,type:"Literal",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,body:{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"AGAIN_ID",type:"Identifier",end:null},body:{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,name:"BLOCK",type:"Identifier",end:null},type:"ExpressionStatement",end:null,_paths:null},type:"WhileStatement",end:null,_scopeInfo:null,_paths:null},label:{start:null,loc:null,range:null,name:"FUNCTION_ID",type:"Identifier",end:null},type:"LabeledStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null}],type:"Program",end:null},"test-exports":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"!==",right:{start:null,loc:null,range:null,value:"undefined",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"test-module":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"module",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"!==",right:{start:null,loc:null,range:null,value:"undefined",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"umd-commonjs-strict":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"root",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"function",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"amd",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"AMD_ARGUMENTS",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"object",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"COMMON_ARGUMENTS",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"BROWSER_ARGUMENTS",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},arguments:[{start:null,loc:null,range:null,name:"UMD_ROOT",type:"Identifier",end:null},{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"FACTORY_PARAMETERS",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,name:"FACTORY_BODY",type:"Identifier",end:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,_scopeInfo:null,_paths:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null},"umd-runner-body":{loc:null,start:null,range:null,body:[{start:null,loc:null,range:null,expression:{start:null,loc:null,range:null,id:null,generator:!1,expression:!1,params:[{start:null,loc:null,range:null,name:"global",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null}],body:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,test:{loc:null,start:null,range:null,left:{loc:null,start:null,range:null,left:{start:null,loc:null,range:null,operator:"typeof",prefix:!0,argument:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},type:"UnaryExpression",end:null,_paths:null},operator:"===",right:{start:null,loc:null,range:null,value:"function",raw:null,type:"Literal",end:null},type:"BinaryExpression",end:null,_paths:null},operator:"&&",right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"amd",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"LogicalExpression",end:null,_paths:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"define",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"AMD_ARGUMENTS",type:"Identifier",end:null},{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,test:{start:null,loc:null,range:null,name:"COMMON_TEST",type:"Identifier",end:null},consequent:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null},arguments:[{start:null,loc:null,range:null,name:"COMMON_ARGUMENTS",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},alternate:{start:null,loc:null,range:null,body:[{start:null,loc:null,range:null,declarations:[{start:null,loc:null,range:null,id:{start:null,loc:null,range:null,name:"mod",type:"Identifier",end:null},init:{start:null,loc:null,range:null,properties:[{start:null,loc:null,range:null,method:!1,shorthand:!1,computed:!1,key:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},value:{start:null,loc:null,range:null,properties:[],type:"ObjectExpression",end:null},kind:"init",type:"Property",end:null,_paths:null}],type:"ObjectExpression",end:null},type:"VariableDeclarator",end:null,_paths:null}],kind:"var",type:"VariableDeclaration",end:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,callee:{start:null,loc:null,range:null,name:"factory",type:"Identifier",end:null},arguments:[{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"mod",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},{start:null,loc:null,range:null,name:"BROWSER_ARGUMENTS",type:"Identifier",end:null}],type:"CallExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null},{start:null,loc:null,range:null,expression:{loc:null,start:null,range:null,operator:"=",left:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"global",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"GLOBAL_ARG",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},right:{loc:null,start:null,range:null,object:{start:null,loc:null,range:null,name:"mod",type:"Identifier",end:null},property:{start:null,loc:null,range:null,name:"exports",type:"Identifier",end:null},computed:!1,type:"MemberExpression",end:null,_paths:null},type:"AssignmentExpression",end:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"BlockStatement",end:null,_scopeInfo:null},type:"IfStatement",end:null,_paths:null},type:"IfStatement",end:null,_paths:null}],type:"BlockStatement",end:null},type:"FunctionExpression",end:null,parenthesizedExpression:!0,_scopeInfo:null,_paths:null},type:"ExpressionStatement",end:null,_paths:null}],type:"Program",end:null}}
},{}]},{},[19])(19)}); |
src/assets/js/edit-page.js | happeninghq/happening | /**
* This is a single-page application for editing
* a "page" - adding/moving/editing/deleting
* components.
*/
import reqwest from 'reqwest'
import _ from 'lodash'
import React from 'react'
import { render } from 'react-dom'
import { Provider, connect } from 'react-redux'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { DjangoCSRFToken } from './react/django'
import { v4 } from 'node-uuid'
const { PropTypes } = React;
export const init = () => {
_.each(document.getElementsByClassName("edit-page"), (elem) => {
// Initial configuration
const blocktypes = JSON.parse(elem.dataset['blocktypes']);
const valid_blocktypes = blocktypes.map(({type}) => type);
const UnfilteredContent = JSON.parse(elem.dataset['content']);
const getBlock = (blocks, id) => blocks.filter((b) => b.id == id)[0];
const content = {
blocks: UnfilteredContent.blocks.filter(
(block) => valid_blocktypes.indexOf(block.type) > -1
),
blockLists: UnfilteredContent.blockLists.map((l) =>
l.filter((blockId) => valid_blocktypes.indexOf(getBlock(UnfilteredContent.blocks, blockId).type) > -1)
),
};
// ACTIONS
const ADD_BLOCK = 'ADD_BLOCK';
const DELETE_BLOCK = 'DELETE_BLOCK';
const CHANGE_BLOCK_TYPE = 'CHANGE_BLOCK_TYPE';
const EDIT_BLOCK = 'EDIT_BLOCK';
const PREVIEW_BLOCK = 'PREVIEW_BLOCK';
const RENDER = 'RENDER';
const SET_FORM_VALUE = 'SET_FORM_VALUE';
const INIT_UI = 'INIT_UI';
// MODES
const SELECT_TYPE = 'SELECT_TYPE';
const EDIT = 'EDIT';
const PREVIEW = 'PREVIEW';
// ACTION CREATORS
const AddBlock = (location) => {
return {
type: ADD_BLOCK,
id: v4(),
location
}
}
const InitUI = (block) => {
return dispatch => {
reqwest({
url: "/admin/pages/block",
data: block,
type: "json"
}).then(resp => {
dispatch({
type: RENDER,
html: resp.html,
id: block.id
});
})
dispatch({
type: INIT_UI,
id: block.id
});
}
}
const DeleteBlock = (id) => {
return {
type: DELETE_BLOCK,
id
}
}
const StartEditBlock = (id) => {
return {
type: EDIT_BLOCK,
id
}
}
const SetFormValue = (id, fieldName, value) => {
return {
type: SET_FORM_VALUE,
id,
fieldName,
value
}
}
const StartPreviewBlock = (block) => {
return dispatch => {
reqwest({
url: "/admin/pages/block",
data: block,
type: "json"
}).then(resp => {
dispatch({
type: RENDER,
html: resp.html,
id: block.id
});
})
dispatch({
type: PREVIEW_BLOCK,
id: block.id
});
}
}
const ChangeBlockType = (id, blockType) => {
return {
type: CHANGE_BLOCK_TYPE,
id,
blockType
}
}
// Presentation
const SelectTypeBlock = ({ block, blockTypes, onSelectBlockType }) => (
<div>
<ul>
{blockTypes.map((i) =>
<li key={i.type} onClick={e => onSelectBlockType(block.id, i.type)}>
{i.type}
</li>)}
</ul>
</div>
)
SelectTypeBlock.propTypes = {
block: PropTypes.object.isRequired
}
const InputField = ({ field, value, onFieldChange }) => {
let input;
return <div className="form__field">
<div className="form__field__label">
<label>{field.name}</label>
</div>
<input defaultValue={value} type="text" ref={node => {
input = node
}} onKeyUp={e => onFieldChange(input.value)}></input>
</div>
}
const EditBlock = ({ block, blockType, onFieldChange }) => {
const formelements = blockType.fields.map((f) => (
<InputField key={f.name} field={f} value={block[f.name]} onFieldChange={(value) =>
onFieldChange(f.name, value)
}></InputField>
));
return <div>
{formelements}
</div>
}
const PreviewBlock = ({ block, blockUI }) => {
if ( blockUI.renderedHTML != null) {
return <div dangerouslySetInnerHTML={{__html: blockUI.renderedHTML}}></div>
}
return <div>
Loading...
</div>
}
const Block = ({ block, onDelete, onEdit, onPreview, mode }) => {
let content = null;
let extraLink = null
if (mode == SELECT_TYPE) {
content = <SelectTypeBlockContainer block={block}></SelectTypeBlockContainer>
extraLink = <div>
<a className="block__header-extra-link" href="#">
<i className="fa fa-trash" title="Delete" onClick={e => {
e.preventDefault()
onDelete()
}}></i>
</a>
</div>
} else if (mode == EDIT) {
content = <EditBlockContainer block={block}></EditBlockContainer>
extraLink = <div>
<a className="block__header-extra-link" href="#">
<i className="fa fa-trash" title="Delete" onClick={e => {
e.preventDefault()
onDelete()
}}></i>
</a>
<a className="block__header-extra-link" href="#">
<i className="fa fa-play" title="Delete" onClick={e => {
e.preventDefault()
onPreview()
}}></i>
</a>
</div>
} else {
content = <PreviewBlockContainer block={block}></PreviewBlockContainer>
extraLink = <div>
<a className="block__header-extra-link" href="#">
<i className="fa fa-trash" title="Delete" onClick={e => {
e.preventDefault()
onDelete()
}}></i>
</a>
<a className="block__header-extra-link" href="#">
<i className="fa fa-pause" title="Delete" onClick={e => {
e.preventDefault()
onEdit()
}}></i>
</a>
</div>
}
return (
<div className="block block-list__item">
<header className="block__header valign-together">
<h2 className="block__header-text block__header-text--small">{block.title}</h2>
{ extraLink }
</header>
{content}
</div>
)}
Block.propTypes = {
block: PropTypes.shape({
}).isRequired,
onDelete: PropTypes.func.isRequired
}
const BlockList = ({ list, className, onAddBlock, additionalBlock }) => (
<div className={className}>
{list.map(i =>
<BlockContainer key={i.id} block={i} />
)}
<div className="block block-list__item">
<a href="#" onClick={e => {
e.preventDefault()
onAddBlock()
}}>Add Block</a>
</div>
{ additionalBlock }
</div>
)
BlockList.propTypes = {
list: PropTypes.arrayOf(PropTypes.shape({
}).isRequired).isRequired,
className: PropTypes.string.isRequired,
onAddBlock: PropTypes.func.isRequired
}
const EditPage = ( { blockLists, onAddBlock, value } ) => {
const submitBlock = <div className="block-list__item block">
<header className="block__header valign-together">
<h2 className="block__header-text block__header-text--small">Edit Page</h2>
</header>
<input type="hidden" name="content" value={value}></input>
<button type="submit">Save</button>
</div>
return <form method="POST">
<DjangoCSRFToken />
<BlockList list={blockLists[0]} className="l-primary-content block-list" onAddBlock={() =>
onAddBlock(0)
} />
<BlockList list={blockLists[1]} className="l-secondary-content block-list" additionalBlock={submitBlock} onAddBlock={() =>
onAddBlock(1)
} />
</form>}
// Container
const App = connect(
(state) => ({
blockLists: state.blockLists.map((l) =>
l.map((id) => state.blocks.filter((i) => i.id == id)[0])),
value: JSON.stringify({blocks: state.blocks, blockLists: state.blockLists})
}),
{ onAddBlock: AddBlock }
)(EditPage)
const SelectTypeBlockContainer = connect(
(state) => ({
blockTypes: state.blockTypes
}),
{ onSelectBlockType: ChangeBlockType }
)(SelectTypeBlock)
const EditBlockContainer = connect(
(state, { block }) => {
return {
blockType: state.blockTypes.filter((i) => i.type == block.type)[0]
}},
(dispatch, { block }) => ({
onFieldChange: (fieldName, value) => {
dispatch(SetFormValue(block.id, fieldName, value));
}
}))(EditBlock)
const PreviewBlockContainer = connect(
(state, { block }) => ({
blockUI: state.blockUIs.filter((i) => i.id == block.id)[0]
}),
{})(PreviewBlock)
const BlockContainer = connect(
(state, { block }) => ({
mode: state.blockUIs.filter((b) => b.id == block.id)[0].mode
}),
(dispatch, { block }) => ({
onDelete: () => {
dispatch(DeleteBlock(block.id))
},
onEdit: () => {
dispatch(StartEditBlock(block.id))
},
onPreview: () => {
dispatch(StartPreviewBlock(block))
},
onSelectBlockType: (id, type) => {
dispatch(ChangeBlockType(id, type))
}
}))(Block)
// Reducers
const block = (state, action) => {
switch (action.type) {
case ADD_BLOCK:
return {
id: action.id,
type: null
};
case CHANGE_BLOCK_TYPE:
if (state.id == action.id) {
return Object.assign({}, state, {type: action.blockType});
}
return state;
case SET_FORM_VALUE:
if (state.id == action.id) {
let x = {}
x[action.fieldName] = action.value;
return Object.assign({}, state, x);
}
return state;
default:
return state
}
};
const blocks = (state = content.blocks, action) => {
switch (action.type) {
case ADD_BLOCK:
return [...state, block(undefined, action)];
case DELETE_BLOCK:
return state.filter((b) => b.id != action.id);
case CHANGE_BLOCK_TYPE:
return state.map((l) => block(l, action));
case SET_FORM_VALUE:
return state.map((l) => block(l, action));
default:
return state;
}
}
const blockUI = (state, action) => {
switch (action.type) {
case ADD_BLOCK:
return {
id: action.id,
mode: SELECT_TYPE,
renderedHTML: null
};
case INIT_UI:
return {
id: action.id,
mode: PREVIEW,
renderedHTML: null
};
case CHANGE_BLOCK_TYPE:
if (state.id == action.id && state.mode == SELECT_TYPE) {
return Object.assign({}, state, {mode: EDIT});
}
return state;
case EDIT_BLOCK:
if (state.id == action.id) {
return Object.assign({}, state, {mode: EDIT});
}
return state;
case PREVIEW_BLOCK:
if (state.id == action.id) {
return Object.assign({}, state, {mode: PREVIEW, renderedHTML: null});
}
return state;
case RENDER:
if (state.id == action.id) {
return Object.assign({}, state, {renderedHTML: action.html});
}
return state;
default:
return state
}
};
const blockUIs = (state = [], action) => {
switch (action.type) {
case ADD_BLOCK:
case INIT_UI:
return [...state, blockUI(undefined, action)];
case DELETE_BLOCK:
return state.filter((b) => b.id != action.id);
case CHANGE_BLOCK_TYPE:
return state.map((l) => blockUI(l, action));
case EDIT_BLOCK:
return state.map((l) => blockUI(l, action));
case PREVIEW_BLOCK:
return state.map((l) => blockUI(l, action));
case RENDER:
return state.map((l) => blockUI(l, action));
default:
return state;
}
}
const blockLists = (state = content.blockLists, action) => {
switch (action.type) {
case ADD_BLOCK:
return state.map((l, i) => {
if (i == action.location) {
return [...l, action.id];
}
return l;
});
case DELETE_BLOCK:
return state.map((l) => l.filter((b) => b != action.id));
default:
return state
}
}
const blockTypes = (state = blocktypes, action) => {
switch (action.type) {
default:
return state;
}
}
const editPage = combineReducers({
blockLists,
blockTypes,
blocks,
blockUIs
});
const store = createStore(editPage, applyMiddleware(thunk));
// We need to initialise the UI
_.each(content.blocks, (block) => {
store.dispatch(InitUI(block));
});
render(
<Provider store={store}>
<App />
</Provider>,
elem
);
});
} |
blueocean-material-icons/src/js/components/svg-icons/av/library-books.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvLibraryBooks = (props) => (
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"/>
</SvgIcon>
);
AvLibraryBooks.displayName = 'AvLibraryBooks';
AvLibraryBooks.muiName = 'SvgIcon';
export default AvLibraryBooks;
|
techCurriculum/ui/solutions/4.2/src/components/Message.js | AnxChow/EngineeringEssentials-group | /**
* Copyright 2017 Goldman Sachs.
* 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.
**/
import React from 'react';
function Message(props) {
return (
<div className='message-text'>
<p>{props.text}</p>
</div>
);
}
export default Message;
|
internals/templates/containers/LanguageProvider/index.js | MaleSharker/Qingyan | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
ajax/libs/react-router/2.0.0-rc5/ReactRouter.js | rlugojr/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReactRouter"] = factory(require("react"));
else
root["ReactRouter"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* components */
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _Router2 = __webpack_require__(37);
var _Router3 = _interopRequireDefault(_Router2);
exports.Router = _Router3['default'];
var _Link2 = __webpack_require__(18);
var _Link3 = _interopRequireDefault(_Link2);
exports.Link = _Link3['default'];
var _IndexLink2 = __webpack_require__(31);
var _IndexLink3 = _interopRequireDefault(_IndexLink2);
exports.IndexLink = _IndexLink3['default'];
/* components (configuration) */
var _IndexRedirect2 = __webpack_require__(32);
var _IndexRedirect3 = _interopRequireDefault(_IndexRedirect2);
exports.IndexRedirect = _IndexRedirect3['default'];
var _IndexRoute2 = __webpack_require__(33);
var _IndexRoute3 = _interopRequireDefault(_IndexRoute2);
exports.IndexRoute = _IndexRoute3['default'];
var _Redirect2 = __webpack_require__(19);
var _Redirect3 = _interopRequireDefault(_Redirect2);
exports.Redirect = _Redirect3['default'];
var _Route2 = __webpack_require__(35);
var _Route3 = _interopRequireDefault(_Route2);
exports.Route = _Route3['default'];
/* mixins */
var _History2 = __webpack_require__(30);
var _History3 = _interopRequireDefault(_History2);
exports.History = _History3['default'];
var _Lifecycle2 = __webpack_require__(34);
var _Lifecycle3 = _interopRequireDefault(_Lifecycle2);
exports.Lifecycle = _Lifecycle3['default'];
var _RouteContext2 = __webpack_require__(36);
var _RouteContext3 = _interopRequireDefault(_RouteContext2);
exports.RouteContext = _RouteContext3['default'];
/* utils */
var _useRoutes2 = __webpack_require__(48);
var _useRoutes3 = _interopRequireDefault(_useRoutes2);
exports.useRoutes = _useRoutes3['default'];
var _RouteUtils = __webpack_require__(5);
exports.createRoutes = _RouteUtils.createRoutes;
var _RouterContext2 = __webpack_require__(13);
var _RouterContext3 = _interopRequireDefault(_RouterContext2);
exports.RouterContext = _RouterContext3['default'];
var _RoutingContext2 = __webpack_require__(38);
var _RoutingContext3 = _interopRequireDefault(_RoutingContext2);
exports.RoutingContext = _RoutingContext3['default'];
var _PropTypes2 = __webpack_require__(6);
var _PropTypes3 = _interopRequireDefault(_PropTypes2);
exports.PropTypes = _PropTypes3['default'];
var _match2 = __webpack_require__(46);
var _match3 = _interopRequireDefault(_match2);
exports.match = _match3['default'];
var _useRouterHistory2 = __webpack_require__(24);
var _useRouterHistory3 = _interopRequireDefault(_useRouterHistory2);
exports.useRouterHistory = _useRouterHistory3['default'];
var _PatternUtils = __webpack_require__(8);
exports.formatPattern = _PatternUtils.formatPattern;
/* histories */
var _browserHistory2 = __webpack_require__(40);
var _browserHistory3 = _interopRequireDefault(_browserHistory2);
exports.browserHistory = _browserHistory3['default'];
var _hashHistory2 = __webpack_require__(44);
var _hashHistory3 = _interopRequireDefault(_hashHistory2);
exports.hashHistory = _hashHistory3['default'];
var _createMemoryHistory2 = __webpack_require__(21);
var _createMemoryHistory3 = _interopRequireDefault(_createMemoryHistory2);
exports.createMemoryHistory = _createMemoryHistory3['default'];
var _Router4 = _interopRequireDefault(_Router2);
exports['default'] = _Router4['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = routerWarning;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
function routerWarning(falseToWarn, message) {
message = '[react-router] ' + message;
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
false ? _warning2['default'].apply(undefined, [falseToWarn, message].concat(args)) : undefined;
}
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (false) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-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';
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = function() {};
if (false) {
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || (/^[s\W]*$/).test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChildren = isReactChildren;
exports.createRouteFromReactElement = createRouteFromReactElement;
exports.createRoutesFromReactChildren = createRoutesFromReactChildren;
exports.createRoutes = createRoutes;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
function isValidChild(object) {
return object == null || _react2['default'].isValidElement(object);
}
function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent';
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, componentName);
/* istanbul ignore if: error logging */
if (error instanceof Error) false ? _warning2['default'](false, error.message) : undefined;
}
}
}
function createRoute(defaultProps, props) {
return _extends({}, defaultProps, props);
}
function createRouteFromReactElement(element) {
var type = element.type;
var route = createRoute(type.defaultProps, element.props);
if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route);
if (route.children) {
var childRoutes = createRoutesFromReactChildren(route.children, route);
if (childRoutes.length) route.childRoutes = childRoutes;
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
function createRoutesFromReactChildren(children, parentRoute) {
var routes = [];
_react2['default'].Children.forEach(children, function (element) {
if (_react2['default'].isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
var route = element.type.createRouteFromReactElement(element, parentRoute);
if (route) routes.push(route);
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (routes && !Array.isArray(routes)) {
routes = [routes];
}
return routes;
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.falsy = falsy;
var _react = __webpack_require__(2);
var func = _react.PropTypes.func;
var object = _react.PropTypes.object;
var arrayOf = _react.PropTypes.arrayOf;
var oneOfType = _react.PropTypes.oneOfType;
var element = _react.PropTypes.element;
var shape = _react.PropTypes.shape;
var string = _react.PropTypes.string;
function falsy(props, propName, componentName) {
if (props[propName]) return new Error('<' + componentName + '> should not have a "' + propName + '" prop');
}
var history = shape({
listen: func.isRequired,
pushState: func.isRequired,
replaceState: func.isRequired,
go: func.isRequired
});
exports.history = history;
var location = shape({
pathname: string.isRequired,
search: string.isRequired,
state: object,
action: string.isRequired,
key: string
});
exports.location = location;
var component = oneOfType([func, string]);
exports.component = component;
var components = oneOfType([component, object]);
exports.components = components;
var route = oneOfType([object, element]);
exports.route = route;
var routes = oneOfType([route, arrayOf(route)]);
exports.routes = routes;
exports['default'] = {
falsy: falsy,
history: history,
location: location,
component: component,
components: components,
route: route
};
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _extractPath = __webpack_require__(29);
var _extractPath2 = _interopRequireDefault(_extractPath);
function parsePath(path) {
var pathname = _extractPath2['default'](path);
var search = '';
var hash = '';
false ? _warning2['default'](path === pathname, 'A path must be pathname + search + hash only, not a fully qualified URL like "%s"', path) : undefined;
var hashIndex = pathname.indexOf('#');
if (hashIndex !== -1) {
hash = pathname.substring(hashIndex);
pathname = pathname.substring(0, hashIndex);
}
var searchIndex = pathname.indexOf('?');
if (searchIndex !== -1) {
search = pathname.substring(searchIndex);
pathname = pathname.substring(0, searchIndex);
}
if (pathname === '') pathname = '/';
return {
pathname: pathname,
search: search,
hash: hash
};
}
exports['default'] = parsePath;
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.compilePattern = compilePattern;
exports.matchPattern = matchPattern;
exports.getParamNames = getParamNames;
exports.getParams = getParams;
exports.formatPattern = formatPattern;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function escapeSource(string) {
return escapeRegExp(string).replace(/\/+/g, '/+');
}
function _compilePattern(pattern) {
var regexpSource = '';
var paramNames = [];
var tokens = [];
var match = undefined,
lastIndex = 0,
matcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|\*\*|\*|\(|\)/g;
while (match = matcher.exec(pattern)) {
if (match.index !== lastIndex) {
tokens.push(pattern.slice(lastIndex, match.index));
regexpSource += escapeSource(pattern.slice(lastIndex, match.index));
}
if (match[1]) {
regexpSource += '([^/?#]+)';
paramNames.push(match[1]);
} else if (match[0] === '**') {
regexpSource += '([\\s\\S]*)';
paramNames.push('splat');
} else if (match[0] === '*') {
regexpSource += '([\\s\\S]*?)';
paramNames.push('splat');
} else if (match[0] === '(') {
regexpSource += '(?:';
} else if (match[0] === ')') {
regexpSource += ')?';
}
tokens.push(match[0]);
lastIndex = matcher.lastIndex;
}
if (lastIndex !== pattern.length) {
tokens.push(pattern.slice(lastIndex, pattern.length));
regexpSource += escapeSource(pattern.slice(lastIndex, pattern.length));
}
return {
pattern: pattern,
regexpSource: regexpSource,
paramNames: paramNames,
tokens: tokens
};
}
var CompiledPatternsCache = {};
function compilePattern(pattern) {
if (!(pattern in CompiledPatternsCache)) CompiledPatternsCache[pattern] = _compilePattern(pattern);
return CompiledPatternsCache[pattern];
}
/**
* Attempts to match a pattern on the given pathname. Patterns may use
* the following special characters:
*
* - :paramName Matches a URL segment up to the next /, ?, or #. The
* captured string is considered a "param"
* - () Wraps a segment of the URL that is optional
* - * Consumes (non-greedy) all characters up to the next
* character in the pattern, or to the end of the URL if
* there is none
* - ** Consumes (greedy) all characters up to the next character
* in the pattern, or to the end of the URL if there is none
*
* The return value is an object with the following properties:
*
* - remainingPathname
* - paramNames
* - paramValues
*/
function matchPattern(pattern, pathname) {
// Make leading slashes consistent between pattern and pathname.
if (pattern.charAt(0) !== '/') {
pattern = '/' + pattern;
}
if (pathname.charAt(0) !== '/') {
pathname = '/' + pathname;
}
var _compilePattern2 = compilePattern(pattern);
var regexpSource = _compilePattern2.regexpSource;
var paramNames = _compilePattern2.paramNames;
var tokens = _compilePattern2.tokens;
regexpSource += '/*'; // Capture path separators
// Special-case patterns like '*' for catch-all routes.
var captureRemaining = tokens[tokens.length - 1] !== '*';
if (captureRemaining) {
// This will match newlines in the remaining path.
regexpSource += '([\\s\\S]*?)';
}
var match = pathname.match(new RegExp('^' + regexpSource + '$', 'i'));
var remainingPathname = undefined,
paramValues = undefined;
if (match != null) {
if (captureRemaining) {
remainingPathname = match.pop();
var matchedPath = match[0].substr(0, match[0].length - remainingPathname.length);
// If we didn't match the entire pathname, then make sure that the match
// we did get ends at a path separator (potentially the one we added
// above at the beginning of the path, if the actual match was empty).
if (remainingPathname && matchedPath.charAt(matchedPath.length - 1) !== '/') {
return {
remainingPathname: null,
paramNames: paramNames,
paramValues: null
};
}
} else {
// If this matched at all, then the match was the entire pathname.
remainingPathname = '';
}
paramValues = match.slice(1).map(function (v) {
return v != null ? decodeURIComponent(v) : v;
});
} else {
remainingPathname = paramValues = null;
}
return {
remainingPathname: remainingPathname,
paramNames: paramNames,
paramValues: paramValues
};
}
function getParamNames(pattern) {
return compilePattern(pattern).paramNames;
}
function getParams(pattern, pathname) {
var _matchPattern = matchPattern(pattern, pathname);
var paramNames = _matchPattern.paramNames;
var paramValues = _matchPattern.paramValues;
if (paramValues != null) {
return paramNames.reduce(function (memo, paramName, index) {
memo[paramName] = paramValues[index];
return memo;
}, {});
}
return null;
}
/**
* Returns a version of the given pattern with params interpolated. Throws
* if there is a dynamic segment of the pattern for which there is no param.
*/
function formatPattern(pattern, params) {
params = params || {};
var _compilePattern3 = compilePattern(pattern);
var tokens = _compilePattern3.tokens;
var parenCount = 0,
pathname = '',
splatIndex = 0;
var token = undefined,
paramName = undefined,
paramValue = undefined;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
if (token === '*' || token === '**') {
paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat;
!(paramValue != null || parenCount > 0) ? false ? _invariant2['default'](false, 'Missing splat #%s for path "%s"', splatIndex, pattern) : _invariant2['default'](false) : undefined;
if (paramValue != null) pathname += encodeURI(paramValue);
} else if (token === '(') {
parenCount += 1;
} else if (token === ')') {
parenCount -= 1;
} else if (token.charAt(0) === ':') {
paramName = token.substring(1);
paramValue = params[paramName];
!(paramValue != null || parenCount > 0) ? false ? _invariant2['default'](false, 'Missing "%s" parameter for path "%s"', paramName, pattern) : _invariant2['default'](false) : undefined;
if (paramValue != null) pathname += encodeURIComponent(paramValue);
} else {
pathname += token;
}
}
return pathname.replace(/\/+/g, '/');
}
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* Indicates that navigation was caused by a call to history.push.
*/
'use strict';
exports.__esModule = true;
var PUSH = 'PUSH';
exports.PUSH = PUSH;
/**
* Indicates that navigation was caused by a call to history.replace.
*/
var REPLACE = 'REPLACE';
exports.REPLACE = REPLACE;
/**
* Indicates that navigation was caused by some other action such
* as using a browser's back/forward buttons and/or manually manipulating
* the URL in a browser's location bar. This is the default.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
* for more information.
*/
var POP = 'POP';
exports.POP = POP;
exports['default'] = {
PUSH: PUSH,
REPLACE: REPLACE,
POP: POP
};
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
exports.canUseDOM = canUseDOM;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _queryString = __webpack_require__(57);
var _runTransitionHook = __webpack_require__(17);
var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
var _deprecate = __webpack_require__(16);
var _deprecate2 = _interopRequireDefault(_deprecate);
var SEARCH_BASE_KEY = '$searchBase';
function defaultStringifyQuery(query) {
return _queryString.stringify(query).replace(/%20/g, '+');
}
var defaultParseQueryString = _queryString.parse;
function isNestedObject(object) {
for (var p in object) {
if (object.hasOwnProperty(p) && typeof object[p] === 'object' && !Array.isArray(object[p]) && object[p] !== null) return true;
}return false;
}
/**
* Returns a new createHistory function that may be used to create
* history objects that know how to handle URL queries.
*/
function useQueries(createHistory) {
return function () {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var stringifyQuery = options.stringifyQuery;
var parseQueryString = options.parseQueryString;
var historyOptions = _objectWithoutProperties(options, ['stringifyQuery', 'parseQueryString']);
var history = createHistory(historyOptions);
if (typeof stringifyQuery !== 'function') stringifyQuery = defaultStringifyQuery;
if (typeof parseQueryString !== 'function') parseQueryString = defaultParseQueryString;
function addQuery(location) {
if (location.query == null) {
var search = location.search;
location.query = parseQueryString(search.substring(1));
location[SEARCH_BASE_KEY] = { search: search, searchBase: '' };
}
// TODO: Instead of all the book-keeping here, this should just strip the
// stringified query from the search.
return location;
}
function appendQuery(location, query) {
var _extends2;
var queryString = undefined;
if (!query || (queryString = stringifyQuery(query)) === '') return location;
false ? _warning2['default'](stringifyQuery !== defaultStringifyQuery || !isNestedObject(query), 'useQueries does not stringify nested query objects by default; ' + 'use a custom stringifyQuery function') : undefined;
if (typeof location === 'string') location = _parsePath2['default'](location);
var searchBaseSpec = location[SEARCH_BASE_KEY];
var searchBase = undefined;
if (searchBaseSpec && location.search === searchBaseSpec.search) {
searchBase = searchBaseSpec.searchBase;
} else {
searchBase = location.search || '';
}
var search = searchBase + (searchBase ? '&' : '?') + queryString;
return _extends({}, location, (_extends2 = {
search: search
}, _extends2[SEARCH_BASE_KEY] = { search: search, searchBase: searchBase }, _extends2));
}
// Override all read methods with query-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
_runTransitionHook2['default'](hook, addQuery(location), callback);
});
}
function listen(listener) {
return history.listen(function (location) {
listener(addQuery(location));
});
}
// Override all write methods with query-aware versions.
function push(location) {
history.push(appendQuery(location, location.query));
}
function replace(location) {
history.replace(appendQuery(location, location.query));
}
function createPath(location, query) {
false ? _warning2['default'](!query, 'the query argument to createPath is deprecated; use a location descriptor instead') : undefined;
return history.createPath(appendQuery(location, query || location.query));
}
function createHref(location, query) {
false ? _warning2['default'](!query, 'the query argument to createHref is deprecated; use a location descriptor instead') : undefined;
return history.createHref(appendQuery(location, query || location.query));
}
function createLocation() {
return addQuery(history.createLocation.apply(history, arguments));
}
// deprecated
function pushState(state, path, query) {
if (typeof path === 'string') path = _parsePath2['default'](path);
push(_extends({ state: state }, path, { query: query }));
}
// deprecated
function replaceState(state, path, query) {
if (typeof path === 'string') path = _parsePath2['default'](path);
replace(_extends({ state: state }, path, { query: query }));
}
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen,
push: push,
replace: replace,
createPath: createPath,
createHref: createHref,
createLocation: createLocation,
pushState: _deprecate2['default'](pushState, 'pushState is deprecated; use push instead'),
replaceState: _deprecate2['default'](replaceState, 'replaceState is deprecated; use replace instead')
});
};
}
exports['default'] = useQueries;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports.loopAsync = loopAsync;
exports.mapAsync = mapAsync;
function loopAsync(turns, work, callback) {
var currentTurn = 0,
isDone = false;
function done() {
isDone = true;
callback.apply(this, arguments);
}
function next() {
if (isDone) return;
if (currentTurn < turns) {
work.call(this, currentTurn++, next, done);
} else {
done.apply(this, arguments);
}
}
next();
}
function mapAsync(array, work, callback) {
var length = array.length;
var values = [];
if (length === 0) return callback(null, values);
var isDone = false,
doneCount = 0;
function done(index, error, value) {
if (isDone) return;
if (error) {
isDone = true;
callback(error);
} else {
values[index] = value;
isDone = ++doneCount === length;
if (isDone) callback(null, values);
}
}
array.forEach(function (item, index) {
work(item, index, function (error, value) {
done(index, error, value);
});
});
}
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _deprecateObjectProperties = __webpack_require__(23);
var _deprecateObjectProperties2 = _interopRequireDefault(_deprecateObjectProperties);
var _getRouteParams = __webpack_require__(43);
var _getRouteParams2 = _interopRequireDefault(_getRouteParams);
var _RouteUtils = __webpack_require__(5);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _React$PropTypes = _react2['default'].PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = _react2['default'].createClass({
displayName: 'RouterContext',
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: _react2['default'].createElement
};
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext: function getChildContext() {
var _props = this.props;
var router = _props.router;
var history = _props.history;
var location = _props.location;
if (!router) {
false ? _warning2['default'](false, '`<RouterContext>` expects a `router` rather than a `history`') : undefined;
router = _extends({}, history, {
setRouteLeaveHook: history.listenBeforeLeavingRoute
});
delete router.listenBeforeLeavingRoute;
}
if (false) {
location = _deprecateObjectProperties2['default'](location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation');
}
return { history: history, location: location, router: router };
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = _getRouteParams2['default'](route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (_RouteUtils.isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (element.hasOwnProperty(prop)) props[prop] = element[prop];
}
}
if (typeof components === 'object') {
var elements = {};
for (var key in components) {
if (components.hasOwnProperty(key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || _react2['default'].isValidElement(element)) ? false ? _invariant2['default'](false, 'The root route must render a single element') : _invariant2['default'](false) : undefined;
return element;
}
});
exports['default'] = RouterContext;
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = createTransitionManager;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _historyLibActions = __webpack_require__(9);
var _computeChangedRoutes2 = __webpack_require__(41);
var _computeChangedRoutes3 = _interopRequireDefault(_computeChangedRoutes2);
var _TransitionUtils = __webpack_require__(39);
var _isActive2 = __webpack_require__(45);
var _isActive3 = _interopRequireDefault(_isActive2);
var _getComponents = __webpack_require__(42);
var _getComponents2 = _interopRequireDefault(_getComponents);
var _matchRoutes = __webpack_require__(47);
var _matchRoutes2 = _interopRequireDefault(_matchRoutes);
function hasAnyProperties(object) {
for (var p in object) {
if (object.hasOwnProperty(p)) return true;
}return false;
}
function createTransitionManager(history, routes) {
var state = {};
// Signature should be (location, indexOnly), but needs to support (path,
// query, indexOnly)
function isActive(location) {
var indexOnlyOrDeprecatedQuery = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var deprecatedIndexOnly = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
var indexOnly = undefined;
if (indexOnlyOrDeprecatedQuery && indexOnlyOrDeprecatedQuery !== true || deprecatedIndexOnly !== null) {
false ? _warning2['default'](false, '`isActive(pathname, query, indexOnly) is deprecated; use `isActive(location, indexOnly)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated') : undefined;
location = { pathname: location, query: indexOnlyOrDeprecatedQuery };
indexOnly = deprecatedIndexOnly || false;
} else {
if (typeof location === 'string') {
location = { pathname: location };
}
indexOnly = indexOnlyOrDeprecatedQuery;
}
return _isActive3['default'](location, indexOnly, state.location, state.routes, state.params);
}
function createLocationFromRedirectInfo(location) {
return history.createLocation(location, _historyLibActions.REPLACE);
}
var partialNextState = undefined;
function match(location, callback) {
if (partialNextState && partialNextState.location === location) {
// Continue from where we left off.
finishMatch(partialNextState, callback);
} else {
_matchRoutes2['default'](routes, location, function (error, nextState) {
if (error) {
callback(error);
} else if (nextState) {
finishMatch(_extends({}, nextState, { location: location }), callback);
} else {
callback();
}
});
}
}
function finishMatch(nextState, callback) {
var _computeChangedRoutes = _computeChangedRoutes3['default'](state, nextState);
var leaveRoutes = _computeChangedRoutes.leaveRoutes;
var enterRoutes = _computeChangedRoutes.enterRoutes;
_TransitionUtils.runLeaveHooks(leaveRoutes);
// Tear down confirmation hooks for left routes
leaveRoutes.forEach(removeListenBeforeHooksForRoute);
_TransitionUtils.runEnterHooks(enterRoutes, nextState, function (error, redirectInfo) {
if (error) {
callback(error);
} else if (redirectInfo) {
callback(null, createLocationFromRedirectInfo(redirectInfo));
} else {
// TODO: Fetch components after state is updated.
_getComponents2['default'](nextState, function (error, components) {
if (error) {
callback(error);
} else {
// TODO: Make match a pure function and have some other API
// for "match and update state".
callback(null, null, state = _extends({}, nextState, { components: components }));
}
});
}
});
}
var RouteGuid = 1;
function getRouteID(route) {
var create = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
return route.__id__ || create && (route.__id__ = RouteGuid++);
}
var RouteHooks = {};
function getRouteHooksForRoutes(routes) {
return routes.reduce(function (hooks, route) {
hooks.push.apply(hooks, RouteHooks[getRouteID(route)]);
return hooks;
}, []);
}
function transitionHook(location, callback) {
_matchRoutes2['default'](routes, location, function (error, nextState) {
if (nextState == null) {
// TODO: We didn't actually match anything, but hang
// onto error/nextState so we don't have to matchRoutes
// again in the listen callback.
callback();
return;
}
// Cache some state here so we don't have to
// matchRoutes() again in the listen callback.
partialNextState = _extends({}, nextState, { location: location });
var hooks = getRouteHooksForRoutes(_computeChangedRoutes3['default'](state, partialNextState).leaveRoutes);
var result = undefined;
for (var i = 0, len = hooks.length; result == null && i < len; ++i) {
// Passing the location arg here indicates to
// the user that this is a transition hook.
result = hooks[i](location);
}
callback(result);
});
}
/* istanbul ignore next: untestable with Karma */
function beforeUnloadHook() {
// Synchronously check to see if any route hooks want
// to prevent the current window/tab from closing.
if (state.routes) {
var hooks = getRouteHooksForRoutes(state.routes);
var message = undefined;
for (var i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
// Passing no args indicates to the user that this is a
// beforeunload hook. We don't know the next location.
message = hooks[i]();
}
return message;
}
}
var unlistenBefore = undefined,
unlistenBeforeUnload = undefined;
function removeListenBeforeHooksForRoute(route) {
var routeID = getRouteID(route, false);
if (!routeID) {
return;
}
delete RouteHooks[routeID];
if (!hasAnyProperties(RouteHooks)) {
// teardown transition & beforeunload hooks
if (unlistenBefore) {
unlistenBefore();
unlistenBefore = null;
}
if (unlistenBeforeUnload) {
unlistenBeforeUnload();
unlistenBeforeUnload = null;
}
}
}
/**
* Registers the given hook function to run before leaving the given route.
*
* During a normal transition, the hook function receives the next location
* as its only argument and must return either a) a prompt message to show
* the user, to make sure they want to leave the page or b) false, to prevent
* the transition.
*
* During the beforeunload event (in browsers) the hook receives no arguments.
* In this case it must return a prompt message to prevent the transition.
*
* Returns a function that may be used to unbind the listener.
*/
function listenBeforeLeavingRoute(route, hook) {
// TODO: Warn if they register for a route that isn't currently
// active. They're probably doing something wrong, like re-creating
// route objects on every location change.
var routeID = getRouteID(route);
var hooks = RouteHooks[routeID];
if (!hooks) {
var thereWereNoRouteHooks = !hasAnyProperties(RouteHooks);
RouteHooks[routeID] = [hook];
if (thereWereNoRouteHooks) {
// setup transition & beforeunload hooks
unlistenBefore = history.listenBefore(transitionHook);
if (history.listenBeforeUnload) unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook);
}
} else {
false ? _warning2['default'](false, 'adding multiple leave hooks for the same route is deprecated; manage multiple confirmations in your own code instead') : undefined;
if (hooks.indexOf(hook) === -1) {
hooks.push(hook);
}
}
return function () {
var hooks = RouteHooks[routeID];
if (hooks) {
var newHooks = hooks.filter(function (item) {
return item !== hook;
});
if (newHooks.length === 0) {
removeListenBeforeHooksForRoute(route);
} else {
RouteHooks[routeID] = newHooks;
}
}
};
}
/**
* This is the API for stateful environments. As the location
* changes, we update state and call the listener. We can also
* gracefully handle errors and redirects.
*/
function listen(listener) {
// TODO: Only use a single history listener. Otherwise we'll
// end up with multiple concurrent calls to match.
return history.listen(function (location) {
if (state.location === location) {
listener(null, state);
} else {
match(location, function (error, redirectLocation, nextState) {
if (error) {
listener(error);
} else if (redirectLocation) {
history.transitionTo(redirectLocation);
} else if (nextState) {
listener(null, nextState);
} else {
false ? _warning2['default'](false, 'Location "%s" did not match any routes', location.pathname + location.search + location.hash) : undefined;
}
});
}
});
}
return {
isActive: isActive,
match: match,
listenBeforeLeavingRoute: listenBeforeLeavingRoute,
listen: listen
};
}
//export default useRoutes
module.exports = exports['default'];
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports.addEventListener = addEventListener;
exports.removeEventListener = removeEventListener;
exports.getHashPath = getHashPath;
exports.replaceHashPath = replaceHashPath;
exports.getWindowPath = getWindowPath;
exports.go = go;
exports.getUserConfirmation = getUserConfirmation;
exports.supportsHistory = supportsHistory;
exports.supportsGoWithoutReloadUsingHash = supportsGoWithoutReloadUsingHash;
function addEventListener(node, event, listener) {
if (node.addEventListener) {
node.addEventListener(event, listener, false);
} else {
node.attachEvent('on' + event, listener);
}
}
function removeEventListener(node, event, listener) {
if (node.removeEventListener) {
node.removeEventListener(event, listener, false);
} else {
node.detachEvent('on' + event, listener);
}
}
function getHashPath() {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
return window.location.href.split('#')[1] || '';
}
function replaceHashPath(path) {
window.location.replace(window.location.pathname + window.location.search + '#' + path);
}
function getWindowPath() {
return window.location.pathname + window.location.search + window.location.hash;
}
function go(n) {
if (n) window.history.go(n);
}
function getUserConfirmation(message, callback) {
callback(window.confirm(message));
}
/**
* Returns true if the HTML5 history API is supported. Taken from Modernizr.
*
* https://github.com/Modernizr/Modernizr/blob/master/LICENSE
* https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
* changed to avoid false negatives for Windows Phones: https://github.com/rackt/react-router/issues/586
*/
function supportsHistory() {
var ua = navigator.userAgent;
if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) {
return false;
}
// FIXME: Work around our browser history not working correctly on Chrome
// iOS: https://github.com/rackt/react-router/issues/2565
if (ua.indexOf('CriOS') !== -1) {
return false;
}
return window.history && 'pushState' in window.history;
}
/**
* Returns false if using go(n) with hash history causes a full page reload.
*/
function supportsGoWithoutReloadUsingHash() {
var ua = navigator.userAgent;
return ua.indexOf('Firefox') === -1;
}
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
function deprecate(fn, message) {
return function () {
false ? _warning2['default'](false, '[history] ' + message) : undefined;
return fn.apply(this, arguments);
};
}
exports['default'] = deprecate;
module.exports = exports['default'];
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
function runTransitionHook(hook, location, callback) {
var result = hook(location, callback);
if (hook.length < 2) {
// Assume the hook runs synchronously and automatically
// call the callback with the return value.
callback(result);
} else {
false ? _warning2['default'](result === undefined, 'You should not "return" in a transition hook with a callback argument; call the callback instead') : undefined;
}
}
exports['default'] = runTransitionHook;
module.exports = exports['default'];
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _React$PropTypes = _react2['default'].PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function isEmptyObject(object) {
for (var p in object) {
if (object.hasOwnProperty(p)) return false;
}return true;
}
function createLocationDescriptor(_ref) {
var to = _ref.to;
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (typeof to !== 'object') {
return { pathname: to, query: query, hash: hash, state: state };
} else {
return _extends({ query: query, hash: hash, state: state }, to);
}
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = _react2['default'].createClass({
displayName: 'Link',
contextTypes: {
router: object
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
className: '',
style: {}
};
},
handleClick: function handleClick(event) {
var allowTransition = true;
if (this.props.onClick) this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
if (event.defaultPrevented === true) allowTransition = false;
// If target prop is set (e.g. to "_blank") let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) {
if (!allowTransition) event.preventDefault();
return;
}
event.preventDefault();
if (allowTransition) {
var _props = this.props;
var state = _props.state;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var _location = createLocationDescriptor({ to: to, query: query, hash: hash, state: state });
this.context.router.push(_location);
}
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
false ? _warning2['default'](!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var loc = createLocationDescriptor({ to: to, query: query, hash: hash, state: state });
props.href = router.createHref(loc);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(loc, onlyActiveOnIndex)) {
if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName;
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return _react2['default'].createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
exports['default'] = Link;
module.exports = exports['default'];
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _RouteUtils = __webpack_require__(5);
var _PatternUtils = __webpack_require__(8);
var _PropTypes = __webpack_require__(6);
var _React$PropTypes = _react2['default'].PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
var Redirect = _react2['default'].createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _RouteUtils.createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location;
var params = nextState.params;
var pathname = undefined;
if (route.to.charAt(0) === '/') {
pathname = _PatternUtils.formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = _PatternUtils.formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: _PropTypes.falsy,
children: _PropTypes.falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
true ? false ? _invariant2['default'](false, '<Redirect> elements are for router configuration only and should not be rendered') : _invariant2['default'](false) : undefined;
}
});
exports['default'] = Redirect;
module.exports = exports['default'];
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.createRouterObject = createRouterObject;
exports.createRoutingHistory = createRoutingHistory;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _deprecateObjectProperties = __webpack_require__(23);
var _deprecateObjectProperties2 = _interopRequireDefault(_deprecateObjectProperties);
function createRouterObject(history, transitionManager) {
return _extends({}, history, {
setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,
isActive: transitionManager.isActive
});
}
// deprecated
function createRoutingHistory(history, transitionManager) {
history = _extends({}, history, transitionManager);
if (false) {
history = _deprecateObjectProperties2['default'](history, '`props.history` and `context.history` are deprecated. Please use `context.router`. http://tiny.cc/router-contextchanges');
}
return history;
}
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createMemoryHistory;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _historyLibUseQueries = __webpack_require__(11);
var _historyLibUseQueries2 = _interopRequireDefault(_historyLibUseQueries);
var _historyLibCreateMemoryHistory = __webpack_require__(55);
var _historyLibCreateMemoryHistory2 = _interopRequireDefault(_historyLibCreateMemoryHistory);
function createMemoryHistory(options) {
// signatures and type checking differ between `useRoutes` and
// `createMemoryHistory`, have to create `memoryHistory` first because
// `useQueries` doesn't understand the signature
var memoryHistory = _historyLibCreateMemoryHistory2['default'](options);
var createHistory = function createHistory() {
return memoryHistory;
};
var history = _historyLibUseQueries2['default'](createHistory)(options);
history.__v2_compatible__ = true;
return history;
}
module.exports = exports['default'];
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _useRouterHistory = __webpack_require__(24);
var _useRouterHistory2 = _interopRequireDefault(_useRouterHistory);
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
exports['default'] = function (createHistory) {
var history = undefined;
if (canUseDOM) history = _useRouterHistory2['default'](createHistory)();
return history;
};
module.exports = exports['default'];
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/*eslint no-empty: 0*/
'use strict';
exports.__esModule = true;
exports['default'] = deprecateObjectProperties;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var useMembrane = false;
if (false) {
try {
if (Object.defineProperty({}, 'x', { get: function get() {
return true;
} }).x) {
useMembrane = true;
}
} catch (e) {}
}
// wraps an object in a membrane to warn about deprecated property access
function deprecateObjectProperties(object, message) {
if (!useMembrane) return object;
var membrane = {};
var _loop = function (prop) {
if (typeof object[prop] === 'function') {
membrane[prop] = function () {
false ? _warning2['default'](false, message) : undefined;
return object[prop].apply(object, arguments);
};
} else {
Object.defineProperty(membrane, prop, {
configurable: false,
enumerable: false,
get: function get() {
false ? _warning2['default'](false, message) : undefined;
return object[prop];
}
});
}
};
for (var prop in object) {
_loop(prop);
}
return membrane;
}
module.exports = exports['default'];
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = useRouterHistory;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _historyLibUseQueries = __webpack_require__(11);
var _historyLibUseQueries2 = _interopRequireDefault(_historyLibUseQueries);
var _historyLibUseBasename = __webpack_require__(56);
var _historyLibUseBasename2 = _interopRequireDefault(_historyLibUseBasename);
function useRouterHistory(createHistory) {
return function (options) {
var history = _historyLibUseQueries2['default'](_historyLibUseBasename2['default'](createHistory))(options);
history.__v2_compatible__ = true;
return history;
};
}
module.exports = exports['default'];
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable no-empty */
'use strict';
exports.__esModule = true;
exports.saveState = saveState;
exports.readState = readState;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var KeyPrefix = '@@History/';
var QuotaExceededError = 'QuotaExceededError';
var SecurityError = 'SecurityError';
function createKey(key) {
return KeyPrefix + key;
}
function saveState(key, state) {
try {
if (state == null) {
window.sessionStorage.removeItem(createKey(key));
} else {
window.sessionStorage.setItem(createKey(key), JSON.stringify(state));
}
} catch (error) {
if (error.name === SecurityError) {
// Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any
// attempt to access window.sessionStorage.
false ? _warning2['default'](false, '[history] Unable to save state; sessionStorage is not available due to security settings') : undefined;
return;
}
if (error.name === QuotaExceededError && window.sessionStorage.length === 0) {
// Safari "private mode" throws QuotaExceededError.
false ? _warning2['default'](false, '[history] Unable to save state; sessionStorage is not available in Safari private mode') : undefined;
return;
}
throw error;
}
}
function readState(key) {
var json = undefined;
try {
json = window.sessionStorage.getItem(createKey(key));
} catch (error) {
if (error.name === SecurityError) {
// Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any
// attempt to access window.sessionStorage.
false ? _warning2['default'](false, '[history] Unable to read state; sessionStorage is not available due to security settings') : undefined;
return null;
}
}
if (json) {
try {
return JSON.parse(json);
} catch (error) {
// Ignore invalid JSON.
}
}
return null;
}
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _ExecutionEnvironment = __webpack_require__(10);
var _DOMUtils = __webpack_require__(15);
var _createHistory = __webpack_require__(28);
var _createHistory2 = _interopRequireDefault(_createHistory);
function createDOMHistory(options) {
var history = _createHistory2['default'](_extends({
getUserConfirmation: _DOMUtils.getUserConfirmation
}, options, {
go: _DOMUtils.go
}));
function listen(listener) {
!_ExecutionEnvironment.canUseDOM ? false ? _invariant2['default'](false, 'DOM history needs a DOM') : _invariant2['default'](false) : undefined;
return history.listen(listener);
}
return _extends({}, history, {
listen: listen
});
}
exports['default'] = createDOMHistory;
module.exports = exports['default'];
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _Actions = __webpack_require__(9);
var _ExecutionEnvironment = __webpack_require__(10);
var _DOMUtils = __webpack_require__(15);
var _DOMStateStorage = __webpack_require__(25);
var _createDOMHistory = __webpack_require__(26);
var _createDOMHistory2 = _interopRequireDefault(_createDOMHistory);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
function isAbsolutePath(path) {
return typeof path === 'string' && path.charAt(0) === '/';
}
function ensureSlash() {
var path = _DOMUtils.getHashPath();
if (isAbsolutePath(path)) return true;
_DOMUtils.replaceHashPath('/' + path);
return false;
}
function addQueryStringValueToPath(path, key, value) {
return path + (path.indexOf('?') === -1 ? '?' : '&') + (key + '=' + value);
}
function stripQueryStringValueFromPath(path, key) {
return path.replace(new RegExp('[?&]?' + key + '=[a-zA-Z0-9]+'), '');
}
function getQueryStringValueFromPath(path, key) {
var match = path.match(new RegExp('\\?.*?\\b' + key + '=(.+?)\\b'));
return match && match[1];
}
var DefaultQueryKey = '_k';
function createHashHistory() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
!_ExecutionEnvironment.canUseDOM ? false ? _invariant2['default'](false, 'Hash history needs a DOM') : _invariant2['default'](false) : undefined;
var queryKey = options.queryKey;
if (queryKey === undefined || !!queryKey) queryKey = typeof queryKey === 'string' ? queryKey : DefaultQueryKey;
function getCurrentLocation() {
var path = _DOMUtils.getHashPath();
var key = undefined,
state = undefined;
if (queryKey) {
key = getQueryStringValueFromPath(path, queryKey);
path = stripQueryStringValueFromPath(path, queryKey);
if (key) {
state = _DOMStateStorage.readState(key);
} else {
state = null;
key = history.createKey();
_DOMUtils.replaceHashPath(addQueryStringValueToPath(path, queryKey, key));
}
} else {
key = state = null;
}
var location = _parsePath2['default'](path);
return history.createLocation(_extends({}, location, { state: state }), undefined, key);
}
function startHashChangeListener(_ref) {
var transitionTo = _ref.transitionTo;
function hashChangeListener() {
if (!ensureSlash()) return; // Always make sure hashes are preceeded with a /.
transitionTo(getCurrentLocation());
}
ensureSlash();
_DOMUtils.addEventListener(window, 'hashchange', hashChangeListener);
return function () {
_DOMUtils.removeEventListener(window, 'hashchange', hashChangeListener);
};
}
function finishTransition(location) {
var basename = location.basename;
var pathname = location.pathname;
var search = location.search;
var state = location.state;
var action = location.action;
var key = location.key;
if (action === _Actions.POP) return; // Nothing to do.
var path = (basename || '') + pathname + search;
if (queryKey) {
path = addQueryStringValueToPath(path, queryKey, key);
_DOMStateStorage.saveState(key, state);
} else {
// Drop key and state.
location.key = location.state = null;
}
var currentHash = _DOMUtils.getHashPath();
if (action === _Actions.PUSH) {
if (currentHash !== path) {
window.location.hash = path;
} else {
false ? _warning2['default'](false, 'You cannot PUSH the same path using hash history') : undefined;
}
} else if (currentHash !== path) {
// REPLACE
_DOMUtils.replaceHashPath(path);
}
}
var history = _createDOMHistory2['default'](_extends({}, options, {
getCurrentLocation: getCurrentLocation,
finishTransition: finishTransition,
saveState: _DOMStateStorage.saveState
}));
var listenerCount = 0,
stopHashChangeListener = undefined;
function listenBefore(listener) {
if (++listenerCount === 1) stopHashChangeListener = startHashChangeListener(history);
var unlisten = history.listenBefore(listener);
return function () {
unlisten();
if (--listenerCount === 0) stopHashChangeListener();
};
}
function listen(listener) {
if (++listenerCount === 1) stopHashChangeListener = startHashChangeListener(history);
var unlisten = history.listen(listener);
return function () {
unlisten();
if (--listenerCount === 0) stopHashChangeListener();
};
}
function push(location) {
false ? _warning2['default'](queryKey || location.state == null, 'You cannot use state without a queryKey it will be dropped') : undefined;
history.push(location);
}
function replace(location) {
false ? _warning2['default'](queryKey || location.state == null, 'You cannot use state without a queryKey it will be dropped') : undefined;
history.replace(location);
}
var goIsSupportedWithoutReload = _DOMUtils.supportsGoWithoutReloadUsingHash();
function go(n) {
false ? _warning2['default'](goIsSupportedWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : undefined;
history.go(n);
}
function createHref(path) {
return '#' + history.createHref(path);
}
// deprecated
function registerTransitionHook(hook) {
if (++listenerCount === 1) stopHashChangeListener = startHashChangeListener(history);
history.registerTransitionHook(hook);
}
// deprecated
function unregisterTransitionHook(hook) {
history.unregisterTransitionHook(hook);
if (--listenerCount === 0) stopHashChangeListener();
}
// deprecated
function pushState(state, path) {
false ? _warning2['default'](queryKey || state == null, 'You cannot use state without a queryKey it will be dropped') : undefined;
history.pushState(state, path);
}
// deprecated
function replaceState(state, path) {
false ? _warning2['default'](queryKey || state == null, 'You cannot use state without a queryKey it will be dropped') : undefined;
history.replaceState(state, path);
}
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen,
push: push,
replace: replace,
go: go,
createHref: createHref,
registerTransitionHook: registerTransitionHook, // deprecated - warning is in createHistory
unregisterTransitionHook: unregisterTransitionHook, // deprecated - warning is in createHistory
pushState: pushState, // deprecated - warning is in createHistory
replaceState: replaceState // deprecated - warning is in createHistory
});
}
exports['default'] = createHashHistory;
module.exports = exports['default'];
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _deepEqual = __webpack_require__(49);
var _deepEqual2 = _interopRequireDefault(_deepEqual);
var _AsyncUtils = __webpack_require__(52);
var _Actions = __webpack_require__(9);
var _createLocation2 = __webpack_require__(54);
var _createLocation3 = _interopRequireDefault(_createLocation2);
var _runTransitionHook = __webpack_require__(17);
var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
var _deprecate = __webpack_require__(16);
var _deprecate2 = _interopRequireDefault(_deprecate);
function createRandomKey(length) {
return Math.random().toString(36).substr(2, length);
}
function locationsAreEqual(a, b) {
return a.pathname === b.pathname && a.search === b.search &&
//a.action === b.action && // Different action !== location change.
a.key === b.key && _deepEqual2['default'](a.state, b.state);
}
var DefaultKeyLength = 6;
function createHistory() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var getCurrentLocation = options.getCurrentLocation;
var finishTransition = options.finishTransition;
var saveState = options.saveState;
var go = options.go;
var keyLength = options.keyLength;
var getUserConfirmation = options.getUserConfirmation;
if (typeof keyLength !== 'number') keyLength = DefaultKeyLength;
var transitionHooks = [];
function listenBefore(hook) {
transitionHooks.push(hook);
return function () {
transitionHooks = transitionHooks.filter(function (item) {
return item !== hook;
});
};
}
var allKeys = [];
var changeListeners = [];
var location = undefined;
function getCurrent() {
if (pendingLocation && pendingLocation.action === _Actions.POP) {
return allKeys.indexOf(pendingLocation.key);
} else if (location) {
return allKeys.indexOf(location.key);
} else {
return -1;
}
}
function updateLocation(newLocation) {
var current = getCurrent();
location = newLocation;
if (location.action === _Actions.PUSH) {
allKeys = [].concat(allKeys.slice(0, current + 1), [location.key]);
} else if (location.action === _Actions.REPLACE) {
allKeys[current] = location.key;
}
changeListeners.forEach(function (listener) {
listener(location);
});
}
function listen(listener) {
changeListeners.push(listener);
if (location) {
listener(location);
} else {
var _location = getCurrentLocation();
allKeys = [_location.key];
updateLocation(_location);
}
return function () {
changeListeners = changeListeners.filter(function (item) {
return item !== listener;
});
};
}
function confirmTransitionTo(location, callback) {
_AsyncUtils.loopAsync(transitionHooks.length, function (index, next, done) {
_runTransitionHook2['default'](transitionHooks[index], location, function (result) {
if (result != null) {
done(result);
} else {
next();
}
});
}, function (message) {
if (getUserConfirmation && typeof message === 'string') {
getUserConfirmation(message, function (ok) {
callback(ok !== false);
});
} else {
callback(message !== false);
}
});
}
var pendingLocation = undefined;
function transitionTo(nextLocation) {
if (location && locationsAreEqual(location, nextLocation)) return; // Nothing to do.
pendingLocation = nextLocation;
confirmTransitionTo(nextLocation, function (ok) {
if (pendingLocation !== nextLocation) return; // Transition was interrupted.
if (ok) {
// treat PUSH to current path like REPLACE to be consistent with browsers
if (nextLocation.action === _Actions.PUSH) {
var prevPath = createPath(location);
var nextPath = createPath(nextLocation);
if (nextPath === prevPath) nextLocation.action = _Actions.REPLACE;
}
if (finishTransition(nextLocation) !== false) updateLocation(nextLocation);
} else if (location && nextLocation.action === _Actions.POP) {
var prevIndex = allKeys.indexOf(location.key);
var nextIndex = allKeys.indexOf(nextLocation.key);
if (prevIndex !== -1 && nextIndex !== -1) go(prevIndex - nextIndex); // Restore the URL.
}
});
}
function push(location) {
transitionTo(createLocation(location, _Actions.PUSH, createKey()));
}
function replace(location) {
transitionTo(createLocation(location, _Actions.REPLACE, createKey()));
}
function goBack() {
go(-1);
}
function goForward() {
go(1);
}
function createKey() {
return createRandomKey(keyLength);
}
function createPath(location) {
if (location == null || typeof location === 'string') return location;
var pathname = location.pathname;
var search = location.search;
var hash = location.hash;
var result = pathname;
if (search) result += search;
if (hash) result += hash;
return result;
}
function createHref(location) {
return createPath(location);
}
function createLocation(location, action) {
var key = arguments.length <= 2 || arguments[2] === undefined ? createKey() : arguments[2];
if (typeof action === 'object') {
false ? _warning2['default'](false, 'The state (2nd) argument to history.createLocation is deprecated; use a ' + 'location descriptor instead') : undefined;
if (typeof location === 'string') location = _parsePath2['default'](location);
location = _extends({}, location, { state: action });
action = key;
key = arguments[3] || createKey();
}
return _createLocation3['default'](location, action, key);
}
// deprecated
function setState(state) {
if (location) {
updateLocationState(location, state);
updateLocation(location);
} else {
updateLocationState(getCurrentLocation(), state);
}
}
function updateLocationState(location, state) {
location.state = _extends({}, location.state, state);
saveState(location.key, location.state);
}
// deprecated
function registerTransitionHook(hook) {
if (transitionHooks.indexOf(hook) === -1) transitionHooks.push(hook);
}
// deprecated
function unregisterTransitionHook(hook) {
transitionHooks = transitionHooks.filter(function (item) {
return item !== hook;
});
}
// deprecated
function pushState(state, path) {
if (typeof path === 'string') path = _parsePath2['default'](path);
push(_extends({ state: state }, path));
}
// deprecated
function replaceState(state, path) {
if (typeof path === 'string') path = _parsePath2['default'](path);
replace(_extends({ state: state }, path));
}
return {
listenBefore: listenBefore,
listen: listen,
transitionTo: transitionTo,
push: push,
replace: replace,
go: go,
goBack: goBack,
goForward: goForward,
createKey: createKey,
createPath: createPath,
createHref: createHref,
createLocation: createLocation,
setState: _deprecate2['default'](setState, 'setState is deprecated; use location.key to save state instead'),
registerTransitionHook: _deprecate2['default'](registerTransitionHook, 'registerTransitionHook is deprecated; use listenBefore instead'),
unregisterTransitionHook: _deprecate2['default'](unregisterTransitionHook, 'unregisterTransitionHook is deprecated; use the callback returned from listenBefore instead'),
pushState: _deprecate2['default'](pushState, 'pushState is deprecated; use push instead'),
replaceState: _deprecate2['default'](replaceState, 'replaceState is deprecated; use replace instead')
};
}
exports['default'] = createHistory;
module.exports = exports['default'];
/***/ },
/* 29 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
function extractPath(string) {
var match = string.match(/^https?:\/\/[^\/]*/);
if (match == null) return string;
return string.substring(match[0].length);
}
exports["default"] = extractPath;
module.exports = exports["default"];
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _PropTypes = __webpack_require__(6);
/**
* A mixin that adds the "history" instance variable to components.
*/
var History = {
contextTypes: {
history: _PropTypes.history
},
componentWillMount: function componentWillMount() {
false ? _warning2['default'](false, 'the `History` mixin is deprecated, please access `context.router` with your own `contextTypes`. http://tiny.cc/router-historymixin') : undefined;
this.history = this.context.history;
}
};
exports['default'] = History;
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Link = __webpack_require__(18);
var _Link2 = _interopRequireDefault(_Link);
/**
* An <IndexLink> is used to link to an <IndexRoute>.
*/
var IndexLink = _react2['default'].createClass({
displayName: 'IndexLink',
render: function render() {
return _react2['default'].createElement(_Link2['default'], _extends({}, this.props, { onlyActiveOnIndex: true }));
}
});
exports['default'] = IndexLink;
module.exports = exports['default'];
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _Redirect = __webpack_require__(19);
var _Redirect2 = _interopRequireDefault(_Redirect);
var _PropTypes = __webpack_require__(6);
var _React$PropTypes = _react2['default'].PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
var IndexRedirect = _react2['default'].createClass({
displayName: 'IndexRedirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _Redirect2['default'].createRouteFromReactElement(element);
} else {
false ? _warning2['default'](false, 'An <IndexRedirect> does not make sense at the root of your route config') : undefined;
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: _PropTypes.falsy,
children: _PropTypes.falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
true ? false ? _invariant2['default'](false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : _invariant2['default'](false) : undefined;
}
});
exports['default'] = IndexRedirect;
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _RouteUtils = __webpack_require__(5);
var _PropTypes = __webpack_require__(6);
var func = _react2['default'].PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
var IndexRoute = _react2['default'].createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _RouteUtils.createRouteFromReactElement(element);
} else {
false ? _warning2['default'](false, 'An <IndexRoute> does not make sense at the root of your route config') : undefined;
}
}
},
propTypes: {
path: _PropTypes.falsy,
component: _PropTypes.component,
components: _PropTypes.components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
true ? false ? _invariant2['default'](false, '<IndexRoute> elements are for router configuration only and should not be rendered') : _invariant2['default'](false) : undefined;
}
});
exports['default'] = IndexRoute;
module.exports = exports['default'];
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var object = _react2['default'].PropTypes.object;
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method to a
* component that may be used to cancel a transition or prompt the user
* for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* During the beforeunload event (assuming you're using the useBeforeUnload
* history enhancer), routerWillLeave does not receive a location object
* because it isn't possible for us to know the location we're transitioning
* to. In this case routerWillLeave must return a prompt message to prevent
* the user from closing the window/tab.
*/
var Lifecycle = {
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
propTypes: {
// Route components receive the route object as a prop.
route: object
},
componentDidMount: function componentDidMount() {
false ? _warning2['default'](false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : undefined;
!this.routerWillLeave ? false ? _invariant2['default'](false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : _invariant2['default'](false) : undefined;
var route = this.props.route || this.context.route;
!route ? false ? _invariant2['default'](false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : _invariant2['default'](false) : undefined;
this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave);
},
componentWillUnmount: function componentWillUnmount() {
if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute();
}
};
exports['default'] = Lifecycle;
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _RouteUtils = __webpack_require__(5);
var _PropTypes = __webpack_require__(6);
var _React$PropTypes = _react2['default'].PropTypes;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
var Route = _react2['default'].createClass({
displayName: 'Route',
statics: {
createRouteFromReactElement: _RouteUtils.createRouteFromReactElement
},
propTypes: {
path: string,
component: _PropTypes.component,
components: _PropTypes.components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
true ? false ? _invariant2['default'](false, '<Route> elements are for router configuration only and should not be rendered') : _invariant2['default'](false) : undefined;
}
});
exports['default'] = Route;
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var object = _react2['default'].PropTypes.object;
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
var RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext: function getChildContext() {
return {
route: this.props.route
};
},
componentWillMount: function componentWillMount() {
false ? _warning2['default'](false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin') : undefined;
}
};
exports['default'] = RouteContext;
module.exports = exports['default'];
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _historyLibCreateHashHistory = __webpack_require__(27);
var _historyLibCreateHashHistory2 = _interopRequireDefault(_historyLibCreateHashHistory);
var _historyLibUseQueries = __webpack_require__(11);
var _historyLibUseQueries2 = _interopRequireDefault(_historyLibUseQueries);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _createTransitionManager = __webpack_require__(14);
var _createTransitionManager2 = _interopRequireDefault(_createTransitionManager);
var _PropTypes = __webpack_require__(6);
var _RouterContext = __webpack_require__(13);
var _RouterContext2 = _interopRequireDefault(_RouterContext);
var _RouteUtils = __webpack_require__(5);
var _RouterUtils = __webpack_require__(20);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
function isDeprecatedHistory(history) {
return !history || !history.__v2_compatible__;
}
var _React$PropTypes = _react2['default'].PropTypes;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RouterContext> with all the props
* it needs each time the URL changes.
*/
var Router = _react2['default'].createClass({
displayName: 'Router',
propTypes: {
history: object,
children: _PropTypes.routes,
routes: _PropTypes.routes, // alias for children
render: func,
createElement: func,
onError: func,
onUpdate: func
},
getDefaultProps: function getDefaultProps() {
return {
render: function render(props) {
return _react2['default'].createElement(_RouterContext2['default'], props);
}
};
},
getInitialState: function getInitialState() {
// Use initial state from renderProps when available, to allow using match
// on client side when doing server-side rendering.
var _props = this.props;
var location = _props.location;
var routes = _props.routes;
var params = _props.params;
var components = _props.components;
return { location: location, routes: routes, params: params, components: components };
},
handleError: function handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error);
} else {
// Throw errors by default so we don't silently swallow them!
throw error; // This error probably occurred in getChildRoutes or getComponents.
}
},
componentWillMount: function componentWillMount() {
var _this = this;
var history = this.props.history;
var _props2 = this.props;
var routes = _props2.routes;
var children = _props2.children;
var _props3 = this.props;
var parseQueryString = _props3.parseQueryString;
var stringifyQuery = _props3.stringifyQuery;
false ? _warning2['default'](!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : undefined;
if (isDeprecatedHistory(history)) {
history = this.wrapDeprecatedHistory(history);
}
var transitionManager = _createTransitionManager2['default'](history, _RouteUtils.createRoutes(routes || children));
this._unlisten = transitionManager.listen(function (error, state) {
if (error) {
_this.handleError(error);
} else {
_this.setState(state, _this.props.onUpdate);
}
});
this.router = _RouterUtils.createRouterObject(history, transitionManager);
this.history = _RouterUtils.createRoutingHistory(history, transitionManager);
},
wrapDeprecatedHistory: function wrapDeprecatedHistory(history) {
var _props4 = this.props;
var parseQueryString = _props4.parseQueryString;
var stringifyQuery = _props4.stringifyQuery;
var createHistory = undefined;
if (history) {
false ? _warning2['default'](false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : undefined;
createHistory = function () {
return history;
};
} else {
false ? _warning2['default'](false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : undefined;
createHistory = _historyLibCreateHashHistory2['default'];
}
return _historyLibUseQueries2['default'](createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery });
},
/* istanbul ignore next: sanity check */
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
false ? _warning2['default'](nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : undefined;
false ? _warning2['default']((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : undefined;
},
componentWillUnmount: function componentWillUnmount() {
if (this._unlisten) this._unlisten();
},
render: function render() {
var _state = this.state;
var location = _state.location;
var routes = _state.routes;
var params = _state.params;
var components = _state.components;
var _props5 = this.props;
var createElement = _props5.createElement;
var render = _props5.render;
var props = _objectWithoutProperties(_props5, ['createElement', 'render']);
if (location == null) return null; // Async match
// Only forward non-Router-specific props to routing context, as those are
// the only ones that might be custom routing context props.
Object.keys(Router.propTypes).forEach(function (propType) {
return delete props[propType];
});
return render(_extends({}, props, {
history: this.history,
router: this.router,
location: location,
routes: routes,
params: params,
components: components,
createElement: createElement
}));
}
});
exports['default'] = Router;
module.exports = exports['default'];
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _RouterContext = __webpack_require__(13);
var _RouterContext2 = _interopRequireDefault(_RouterContext);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var RoutingContext = _react2['default'].createClass({
displayName: 'RoutingContext',
componentWillMount: function componentWillMount() {
false ? _warning2['default'](false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : undefined;
},
render: function render() {
return _react2['default'].createElement(_RouterContext2['default'], this.props);
}
});
exports['default'] = RoutingContext;
module.exports = exports['default'];
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.runEnterHooks = runEnterHooks;
exports.runLeaveHooks = runLeaveHooks;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _AsyncUtils = __webpack_require__(12);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
function createEnterHook(hook, route) {
return function (a, b, callback) {
hook.apply(route, arguments);
if (hook.length < 3) {
// Assume hook executes synchronously and
// automatically call the callback.
callback();
}
};
}
function getEnterHooks(routes) {
return routes.reduce(function (hooks, route) {
if (route.onEnter) hooks.push(createEnterHook(route.onEnter, route));
return hooks;
}, []);
}
/**
* Runs all onEnter hooks in the given array of routes in order
* with onEnter(nextState, replace, callback) and calls
* callback(error, redirectInfo) when finished. The first hook
* to use replace short-circuits the loop.
*
* If a hook needs to run asynchronously, it may use the callback
* function. However, doing so will cause the transition to pause,
* which could lead to a non-responsive UI if the hook is slow.
*/
function runEnterHooks(routes, nextState, callback) {
var hooks = getEnterHooks(routes);
if (!hooks.length) {
callback();
return;
}
var redirectInfo = undefined;
function replace(location, deprecatedPathname, deprecatedQuery) {
if (deprecatedPathname) {
false ? _warning2['default'](false, '`replaceState(state, pathname, query) is deprecated; use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated') : undefined;
redirectInfo = {
pathname: deprecatedPathname,
query: deprecatedQuery,
state: location
};
return;
}
redirectInfo = location;
}
_AsyncUtils.loopAsync(hooks.length, function (index, next, done) {
hooks[index](nextState, replace, function (error) {
if (error || redirectInfo) {
done(error, redirectInfo); // No need to continue.
} else {
next();
}
});
}, callback);
}
/**
* Runs all onLeave hooks in the given array of routes in order.
*/
function runLeaveHooks(routes) {
for (var i = 0, len = routes.length; i < len; ++i) {
if (routes[i].onLeave) routes[i].onLeave.call(routes[i]);
}
}
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _historyLibCreateBrowserHistory = __webpack_require__(53);
var _historyLibCreateBrowserHistory2 = _interopRequireDefault(_historyLibCreateBrowserHistory);
var _createRouterHistory = __webpack_require__(22);
var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory);
exports['default'] = _createRouterHistory2['default'](_historyLibCreateBrowserHistory2['default']);
module.exports = exports['default'];
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _PatternUtils = __webpack_require__(8);
function routeParamsChanged(route, prevState, nextState) {
if (!route.path) return false;
var paramNames = _PatternUtils.getParamNames(route.path);
return paramNames.some(function (paramName) {
return prevState.params[paramName] !== nextState.params[paramName];
});
}
/**
* Returns an object of { leaveRoutes, enterRoutes } determined by
* the change from prevState to nextState. We leave routes if either
* 1) they are not in the next state or 2) they are in the next state
* but their params have changed (i.e. /users/123 => /users/456).
*
* leaveRoutes are ordered starting at the leaf route of the tree
* we're leaving up to the common parent route. enterRoutes are ordered
* from the top of the tree we're entering down to the leaf route.
*/
function computeChangedRoutes(prevState, nextState) {
var prevRoutes = prevState && prevState.routes;
var nextRoutes = nextState.routes;
var leaveRoutes = undefined,
enterRoutes = undefined;
if (prevRoutes) {
leaveRoutes = prevRoutes.filter(function (route) {
return nextRoutes.indexOf(route) === -1 || routeParamsChanged(route, prevState, nextState);
});
// onLeave hooks start at the leaf route.
leaveRoutes.reverse();
enterRoutes = nextRoutes.filter(function (route) {
return prevRoutes.indexOf(route) === -1 || leaveRoutes.indexOf(route) !== -1;
});
} else {
leaveRoutes = [];
enterRoutes = nextRoutes;
}
return {
leaveRoutes: leaveRoutes,
enterRoutes: enterRoutes
};
}
exports['default'] = computeChangedRoutes;
module.exports = exports['default'];
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _AsyncUtils = __webpack_require__(12);
function getComponentsForRoute(location, route, callback) {
if (route.component || route.components) {
callback(null, route.component || route.components);
} else if (route.getComponent) {
route.getComponent(location, callback);
} else if (route.getComponents) {
route.getComponents(location, callback);
} else {
callback();
}
}
/**
* Asynchronously fetches all components needed for the given router
* state and calls callback(error, components) when finished.
*
* Note: This operation may finish synchronously if no routes have an
* asynchronous getComponents method.
*/
function getComponents(nextState, callback) {
_AsyncUtils.mapAsync(nextState.routes, function (route, index, callback) {
getComponentsForRoute(nextState.location, route, callback);
}, callback);
}
exports['default'] = getComponents;
module.exports = exports['default'];
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _PatternUtils = __webpack_require__(8);
/**
* Extracts an object of params the given route cares about from
* the given params object.
*/
function getRouteParams(route, params) {
var routeParams = {};
if (!route.path) return routeParams;
var paramNames = _PatternUtils.getParamNames(route.path);
for (var p in params) {
if (params.hasOwnProperty(p) && paramNames.indexOf(p) !== -1) routeParams[p] = params[p];
}return routeParams;
}
exports['default'] = getRouteParams;
module.exports = exports['default'];
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _historyLibCreateHashHistory = __webpack_require__(27);
var _historyLibCreateHashHistory2 = _interopRequireDefault(_historyLibCreateHashHistory);
var _createRouterHistory = __webpack_require__(22);
var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory);
exports['default'] = _createRouterHistory2['default'](_historyLibCreateHashHistory2['default']);
module.exports = exports['default'];
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = isActive;
var _PatternUtils = __webpack_require__(8);
function deepEqual(a, b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (Array.isArray(a)) {
return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {
return deepEqual(item, b[index]);
});
}
if (typeof a === 'object') {
for (var p in a) {
if (!a.hasOwnProperty(p)) {
continue;
}
if (a[p] === undefined) {
if (b[p] !== undefined) {
return false;
}
} else if (!b.hasOwnProperty(p)) {
return false;
} else if (!deepEqual(a[p], b[p])) {
return false;
}
}
return true;
}
return String(a) === String(b);
}
function paramsAreActive(paramNames, paramValues, activeParams) {
// FIXME: This doesn't work on repeated params in activeParams.
return paramNames.every(function (paramName, index) {
return String(paramValues[index]) === String(activeParams[paramName]);
});
}
function getMatchingRouteIndex(pathname, activeRoutes, activeParams) {
var remainingPathname = pathname,
paramNames = [],
paramValues = [];
for (var i = 0, len = activeRoutes.length; i < len; ++i) {
var route = activeRoutes[i];
var pattern = route.path || '';
if (pattern.charAt(0) === '/') {
remainingPathname = pathname;
paramNames = [];
paramValues = [];
}
if (remainingPathname !== null) {
var matched = _PatternUtils.matchPattern(pattern, remainingPathname);
remainingPathname = matched.remainingPathname;
paramNames = [].concat(paramNames, matched.paramNames);
paramValues = [].concat(paramValues, matched.paramValues);
}
if (remainingPathname === '' && route.path && paramsAreActive(paramNames, paramValues, activeParams)) return i;
}
return null;
}
/**
* Returns true if the given pathname matches the active routes
* and params.
*/
function routeIsActive(pathname, routes, params, indexOnly) {
var i = getMatchingRouteIndex(pathname, routes, params);
if (i === null) {
// No match.
return false;
} else if (!indexOnly) {
// Any match is good enough.
return true;
}
// If any remaining routes past the match index have paths, then we can't
// be on the index route.
return routes.slice(i + 1).every(function (route) {
return !route.path;
});
}
/**
* Returns true if all key/value pairs in the given query are
* currently active.
*/
function queryIsActive(query, activeQuery) {
if (activeQuery == null) return query == null;
if (query == null) return true;
return deepEqual(query, activeQuery);
}
/**
* Returns true if a <Link> to the given pathname/query combination is
* currently active.
*/
function isActive(_ref, indexOnly, currentLocation, routes, params) {
var pathname = _ref.pathname;
var query = _ref.query;
if (currentLocation == null) return false;
if (!routeIsActive(pathname, routes, params, indexOnly)) return false;
return queryIsActive(query, currentLocation.query);
}
module.exports = exports['default'];
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _createMemoryHistory = __webpack_require__(21);
var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory);
var _createTransitionManager = __webpack_require__(14);
var _createTransitionManager2 = _interopRequireDefault(_createTransitionManager);
var _RouteUtils = __webpack_require__(5);
var _RouterUtils = __webpack_require__(20);
/**
* A high-level API to be used for server-side rendering.
*
* This function matches a location to a set of routes and calls
* callback(error, redirectLocation, renderProps) when finished.
*
* Note: You probably don't want to use this in a browser. Use
* the history.listen API instead.
*/
function match(_ref, callback) {
var history = _ref.history;
var routes = _ref.routes;
var location = _ref.location;
var options = _objectWithoutProperties(_ref, ['history', 'routes', 'location']);
!location ? false ? _invariant2['default'](false, 'match needs a location') : _invariant2['default'](false) : undefined;
history = history ? history : _createMemoryHistory2['default'](options);
var transitionManager = _createTransitionManager2['default'](history, _RouteUtils.createRoutes(routes));
// Allow match({ location: '/the/path', ... })
if (typeof location === 'string') location = history.createLocation(location);
var router = _RouterUtils.createRouterObject(history, transitionManager);
history = _RouterUtils.createRoutingHistory(history, transitionManager);
transitionManager.match(location, function (error, redirectLocation, nextState) {
callback(error, redirectLocation, nextState && _extends({}, nextState, { history: history, router: router }));
});
}
exports['default'] = match;
module.exports = exports['default'];
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
var _AsyncUtils = __webpack_require__(12);
var _PatternUtils = __webpack_require__(8);
var _RouteUtils = __webpack_require__(5);
function getChildRoutes(route, location, callback) {
if (route.childRoutes) {
callback(null, route.childRoutes);
} else if (route.getChildRoutes) {
route.getChildRoutes(location, function (error, childRoutes) {
callback(error, !error && _RouteUtils.createRoutes(childRoutes));
});
} else {
callback();
}
}
function getIndexRoute(route, location, callback) {
if (route.indexRoute) {
callback(null, route.indexRoute);
} else if (route.getIndexRoute) {
route.getIndexRoute(location, function (error, indexRoute) {
callback(error, !error && _RouteUtils.createRoutes(indexRoute)[0]);
});
} else if (route.childRoutes) {
(function () {
var pathless = route.childRoutes.filter(function (obj) {
return !obj.hasOwnProperty('path');
});
_AsyncUtils.loopAsync(pathless.length, function (index, next, done) {
getIndexRoute(pathless[index], location, function (error, indexRoute) {
if (error || indexRoute) {
var routes = [pathless[index]].concat(Array.isArray(indexRoute) ? indexRoute : [indexRoute]);
done(error, routes);
} else {
next();
}
});
}, function (err, routes) {
callback(null, routes);
});
})();
} else {
callback();
}
}
function assignParams(params, paramNames, paramValues) {
return paramNames.reduce(function (params, paramName, index) {
var paramValue = paramValues && paramValues[index];
if (Array.isArray(params[paramName])) {
params[paramName].push(paramValue);
} else if (paramName in params) {
params[paramName] = [params[paramName], paramValue];
} else {
params[paramName] = paramValue;
}
return params;
}, params);
}
function createParams(paramNames, paramValues) {
return assignParams({}, paramNames, paramValues);
}
function matchRouteDeep(route, location, remainingPathname, paramNames, paramValues, callback) {
var pattern = route.path || '';
if (pattern.charAt(0) === '/') {
remainingPathname = location.pathname;
paramNames = [];
paramValues = [];
}
if (remainingPathname !== null) {
var matched = _PatternUtils.matchPattern(pattern, remainingPathname);
remainingPathname = matched.remainingPathname;
paramNames = [].concat(paramNames, matched.paramNames);
paramValues = [].concat(paramValues, matched.paramValues);
if (remainingPathname === '' && route.path) {
var _ret2 = (function () {
var match = {
routes: [route],
params: createParams(paramNames, paramValues)
};
getIndexRoute(route, location, function (error, indexRoute) {
if (error) {
callback(error);
} else {
if (Array.isArray(indexRoute)) {
var _match$routes;
false ? _warning2['default'](indexRoute.every(function (route) {
return !route.path;
}), 'Index routes should not have paths') : undefined;
(_match$routes = match.routes).push.apply(_match$routes, indexRoute);
} else if (indexRoute) {
false ? _warning2['default'](!indexRoute.path, 'Index routes should not have paths') : undefined;
match.routes.push(indexRoute);
}
callback(null, match);
}
});
return {
v: undefined
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
}
}
if (remainingPathname != null || route.childRoutes) {
// Either a) this route matched at least some of the path or b)
// we don't have to load this route's children asynchronously. In
// either case continue checking for matches in the subtree.
getChildRoutes(route, location, function (error, childRoutes) {
if (error) {
callback(error);
} else if (childRoutes) {
// Check the child routes to see if any of them match.
matchRoutes(childRoutes, location, function (error, match) {
if (error) {
callback(error);
} else if (match) {
// A child route matched! Augment the match and pass it up the stack.
match.routes.unshift(route);
callback(null, match);
} else {
callback();
}
}, remainingPathname, paramNames, paramValues);
} else {
callback();
}
});
} else {
callback();
}
}
/**
* Asynchronously matches the given location to a set of routes and calls
* callback(error, state) when finished. The state object will have the
* following properties:
*
* - routes An array of routes that matched, in hierarchical order
* - params An object of URL parameters
*
* Note: This operation may finish synchronously if no routes have an
* asynchronous getChildRoutes method.
*/
function matchRoutes(routes, location, callback) {
var remainingPathname = arguments.length <= 3 || arguments[3] === undefined ? location.pathname : arguments[3];
var paramNames = arguments.length <= 4 || arguments[4] === undefined ? [] : arguments[4];
var paramValues = arguments.length <= 5 || arguments[5] === undefined ? [] : arguments[5];
return (function () {
_AsyncUtils.loopAsync(routes.length, function (index, next, done) {
matchRouteDeep(routes[index], location, remainingPathname, paramNames, paramValues, function (error, match) {
if (error || match) {
done(error, match);
} else {
next();
}
});
}, callback);
})();
}
exports['default'] = matchRoutes;
module.exports = exports['default'];
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _historyLibUseQueries = __webpack_require__(11);
var _historyLibUseQueries2 = _interopRequireDefault(_historyLibUseQueries);
var _createTransitionManager = __webpack_require__(14);
var _createTransitionManager2 = _interopRequireDefault(_createTransitionManager);
var _warning = __webpack_require__(1);
var _warning2 = _interopRequireDefault(_warning);
/**
* Returns a new createHistory function that may be used to create
* history objects that know about routing.
*
* Enhances history objects with the following methods:
*
* - listen((error, nextState) => {})
* - listenBeforeLeavingRoute(route, (nextLocation) => {})
* - match(location, (error, redirectLocation, nextState) => {})
* - isActive(pathname, query, indexOnly=false)
*/
function useRoutes(createHistory) {
false ? _warning2['default'](false, '`useRoutes` is deprecated. Please use `createTransitionManager` instead.') : undefined;
return function () {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var routes = _ref.routes;
var options = _objectWithoutProperties(_ref, ['routes']);
var history = _historyLibUseQueries2['default'](createHistory)(options);
var transitionManager = _createTransitionManager2['default'](history, routes);
return _extends({}, history, transitionManager);
};
}
exports['default'] = useRoutes;
module.exports = exports['default'];
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var pSlice = Array.prototype.slice;
var objectKeys = __webpack_require__(51);
var isArguments = __webpack_require__(50);
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
/***/ },
/* 50 */
/***/ function(module, exports) {
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
/***/ },
/* 51 */
/***/ function(module, exports) {
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/***/ },
/* 52 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports.loopAsync = loopAsync;
function loopAsync(turns, work, callback) {
var currentTurn = 0;
var isDone = false;
function done() {
isDone = true;
callback.apply(this, arguments);
}
function next() {
if (isDone) return;
if (currentTurn < turns) {
work.call(this, currentTurn++, next, done);
} else {
done.apply(this, arguments);
}
}
next();
}
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _Actions = __webpack_require__(9);
var _ExecutionEnvironment = __webpack_require__(10);
var _DOMUtils = __webpack_require__(15);
var _DOMStateStorage = __webpack_require__(25);
var _createDOMHistory = __webpack_require__(26);
var _createDOMHistory2 = _interopRequireDefault(_createDOMHistory);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
/**
* Creates and returns a history object that uses HTML5's history API
* (pushState, replaceState, and the popstate event) to manage history.
* This is the recommended method of managing history in browsers because
* it provides the cleanest URLs.
*
* Note: In browsers that do not support the HTML5 history API full
* page reloads will be used to preserve URLs.
*/
function createBrowserHistory() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
!_ExecutionEnvironment.canUseDOM ? false ? _invariant2['default'](false, 'Browser history needs a DOM') : _invariant2['default'](false) : undefined;
var forceRefresh = options.forceRefresh;
var isSupported = _DOMUtils.supportsHistory();
var useRefresh = !isSupported || forceRefresh;
function getCurrentLocation(historyState) {
historyState = historyState || window.history.state || {};
var path = _DOMUtils.getWindowPath();
var _historyState = historyState;
var key = _historyState.key;
var state = undefined;
if (key) {
state = _DOMStateStorage.readState(key);
} else {
state = null;
key = history.createKey();
if (isSupported) window.history.replaceState(_extends({}, historyState, { key: key }), null, path);
}
var location = _parsePath2['default'](path);
return history.createLocation(_extends({}, location, { state: state }), undefined, key);
}
function startPopStateListener(_ref) {
var transitionTo = _ref.transitionTo;
function popStateListener(event) {
if (event.state === undefined) return; // Ignore extraneous popstate events in WebKit.
transitionTo(getCurrentLocation(event.state));
}
_DOMUtils.addEventListener(window, 'popstate', popStateListener);
return function () {
_DOMUtils.removeEventListener(window, 'popstate', popStateListener);
};
}
function finishTransition(location) {
var basename = location.basename;
var pathname = location.pathname;
var search = location.search;
var hash = location.hash;
var state = location.state;
var action = location.action;
var key = location.key;
if (action === _Actions.POP) return; // Nothing to do.
_DOMStateStorage.saveState(key, state);
var path = (basename || '') + pathname + search + hash;
var historyState = {
key: key
};
if (action === _Actions.PUSH) {
if (useRefresh) {
window.location.href = path;
return false; // Prevent location update.
} else {
window.history.pushState(historyState, null, path);
}
} else {
// REPLACE
if (useRefresh) {
window.location.replace(path);
return false; // Prevent location update.
} else {
window.history.replaceState(historyState, null, path);
}
}
}
var history = _createDOMHistory2['default'](_extends({}, options, {
getCurrentLocation: getCurrentLocation,
finishTransition: finishTransition,
saveState: _DOMStateStorage.saveState
}));
var listenerCount = 0,
stopPopStateListener = undefined;
function listenBefore(listener) {
if (++listenerCount === 1) stopPopStateListener = startPopStateListener(history);
var unlisten = history.listenBefore(listener);
return function () {
unlisten();
if (--listenerCount === 0) stopPopStateListener();
};
}
function listen(listener) {
if (++listenerCount === 1) stopPopStateListener = startPopStateListener(history);
var unlisten = history.listen(listener);
return function () {
unlisten();
if (--listenerCount === 0) stopPopStateListener();
};
}
// deprecated
function registerTransitionHook(hook) {
if (++listenerCount === 1) stopPopStateListener = startPopStateListener(history);
history.registerTransitionHook(hook);
}
// deprecated
function unregisterTransitionHook(hook) {
history.unregisterTransitionHook(hook);
if (--listenerCount === 0) stopPopStateListener();
}
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen,
registerTransitionHook: registerTransitionHook,
unregisterTransitionHook: unregisterTransitionHook
});
}
exports['default'] = createBrowserHistory;
module.exports = exports['default'];
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _Actions = __webpack_require__(9);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
function createLocation() {
var location = arguments.length <= 0 || arguments[0] === undefined ? '/' : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? _Actions.POP : arguments[1];
var key = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
var _fourthArg = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];
if (typeof location === 'string') location = _parsePath2['default'](location);
if (typeof action === 'object') {
false ? _warning2['default'](false, 'The state (2nd) argument to createLocation is deprecated; use a ' + 'location descriptor instead') : undefined;
location = _extends({}, location, { state: action });
action = key || _Actions.POP;
key = _fourthArg;
}
var pathname = location.pathname || '/';
var search = location.search || '';
var hash = location.hash || '';
var state = location.state || null;
return {
pathname: pathname,
search: search,
hash: hash,
state: state,
action: action,
key: key
};
}
exports['default'] = createLocation;
module.exports = exports['default'];
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(4);
var _warning2 = _interopRequireDefault(_warning);
var _invariant = __webpack_require__(3);
var _invariant2 = _interopRequireDefault(_invariant);
var _Actions = __webpack_require__(9);
var _createHistory = __webpack_require__(28);
var _createHistory2 = _interopRequireDefault(_createHistory);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
function createStateStorage(entries) {
return entries.filter(function (entry) {
return entry.state;
}).reduce(function (memo, entry) {
memo[entry.key] = entry.state;
return memo;
}, {});
}
function createMemoryHistory() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (Array.isArray(options)) {
options = { entries: options };
} else if (typeof options === 'string') {
options = { entries: [options] };
}
var history = _createHistory2['default'](_extends({}, options, {
getCurrentLocation: getCurrentLocation,
finishTransition: finishTransition,
saveState: saveState,
go: go
}));
var _options = options;
var entries = _options.entries;
var current = _options.current;
if (typeof entries === 'string') {
entries = [entries];
} else if (!Array.isArray(entries)) {
entries = ['/'];
}
entries = entries.map(function (entry) {
var key = history.createKey();
if (typeof entry === 'string') return { pathname: entry, key: key };
if (typeof entry === 'object' && entry) return _extends({}, entry, { key: key });
true ? false ? _invariant2['default'](false, 'Unable to create history entry from %s', entry) : _invariant2['default'](false) : undefined;
});
if (current == null) {
current = entries.length - 1;
} else {
!(current >= 0 && current < entries.length) ? false ? _invariant2['default'](false, 'Current index must be >= 0 and < %s, was %s', entries.length, current) : _invariant2['default'](false) : undefined;
}
var storage = createStateStorage(entries);
function saveState(key, state) {
storage[key] = state;
}
function readState(key) {
return storage[key];
}
function getCurrentLocation() {
var entry = entries[current];
var key = entry.key;
var basename = entry.basename;
var pathname = entry.pathname;
var search = entry.search;
var path = (basename || '') + pathname + (search || '');
var state = undefined;
if (key) {
state = readState(key);
} else {
state = null;
key = history.createKey();
entry.key = key;
}
var location = _parsePath2['default'](path);
return history.createLocation(_extends({}, location, { state: state }), undefined, key);
}
function canGo(n) {
var index = current + n;
return index >= 0 && index < entries.length;
}
function go(n) {
if (n) {
if (!canGo(n)) {
false ? _warning2['default'](false, 'Cannot go(%s) there is not enough history', n) : undefined;
return;
}
current += n;
var currentLocation = getCurrentLocation();
// change action to POP
history.transitionTo(_extends({}, currentLocation, { action: _Actions.POP }));
}
}
function finishTransition(location) {
switch (location.action) {
case _Actions.PUSH:
current += 1;
// if we are not on the top of stack
// remove rest and push new
if (current < entries.length) entries.splice(current);
entries.push(location);
saveState(location.key, location.state);
break;
case _Actions.REPLACE:
entries[current] = location;
saveState(location.key, location.state);
break;
}
}
return history;
}
exports['default'] = createMemoryHistory;
module.exports = exports['default'];
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _ExecutionEnvironment = __webpack_require__(10);
var _runTransitionHook = __webpack_require__(17);
var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook);
var _extractPath = __webpack_require__(29);
var _extractPath2 = _interopRequireDefault(_extractPath);
var _parsePath = __webpack_require__(7);
var _parsePath2 = _interopRequireDefault(_parsePath);
var _deprecate = __webpack_require__(16);
var _deprecate2 = _interopRequireDefault(_deprecate);
function useBasename(createHistory) {
return function () {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var basename = options.basename;
var historyOptions = _objectWithoutProperties(options, ['basename']);
var history = createHistory(historyOptions);
// Automatically use the value of <base href> in HTML
// documents as basename if it's not explicitly given.
if (basename == null && _ExecutionEnvironment.canUseDOM) {
var base = document.getElementsByTagName('base')[0];
if (base) basename = _extractPath2['default'](base.href);
}
function addBasename(location) {
if (basename && location.basename == null) {
if (location.pathname.indexOf(basename) === 0) {
location.pathname = location.pathname.substring(basename.length);
location.basename = basename;
if (location.pathname === '') location.pathname = '/';
} else {
location.basename = '';
}
}
return location;
}
function prependBasename(location) {
if (!basename) return location;
if (typeof location === 'string') location = _parsePath2['default'](location);
var pname = location.pathname;
var normalizedBasename = basename.slice(-1) === '/' ? basename : basename + '/';
var normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname;
var pathname = normalizedBasename + normalizedPathname;
return _extends({}, location, {
pathname: pathname
});
}
// Override all read methods with basename-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
_runTransitionHook2['default'](hook, addBasename(location), callback);
});
}
function listen(listener) {
return history.listen(function (location) {
listener(addBasename(location));
});
}
// Override all write methods with basename-aware versions.
function push(location) {
history.push(prependBasename(location));
}
function replace(location) {
history.replace(prependBasename(location));
}
function createPath(location) {
return history.createPath(prependBasename(location));
}
function createHref(location) {
return history.createHref(prependBasename(location));
}
function createLocation() {
return addBasename(history.createLocation.apply(history, arguments));
}
// deprecated
function pushState(state, path) {
if (typeof path === 'string') path = _parsePath2['default'](path);
push(_extends({ state: state }, path));
}
// deprecated
function replaceState(state, path) {
if (typeof path === 'string') path = _parsePath2['default'](path);
replace(_extends({ state: state }, path));
}
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen,
push: push,
replace: replace,
createPath: createPath,
createHref: createHref,
createLocation: createLocation,
pushState: _deprecate2['default'](pushState, 'pushState is deprecated; use push instead'),
replaceState: _deprecate2['default'](replaceState, 'replaceState is deprecated; use replace instead')
});
};
}
exports['default'] = useBasename;
module.exports = exports['default'];
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strictUriEncode = __webpack_require__(58);
exports.extract = function (str) {
return str.split('?')[1] || '';
};
exports.parse = function (str) {
if (typeof str !== 'string') {
return {};
}
str = str.trim().replace(/^(\?|#|&)/, '');
if (!str) {
return {};
}
return str.split('&').reduce(function (ret, param) {
var parts = param.replace(/\+/g, ' ').split('=');
// Firefox (pre 40) decodes `%3D` to `=`
// https://github.com/sindresorhus/query-string/pull/37
var key = parts.shift();
var val = parts.length > 0 ? parts.join('=') : undefined;
key = decodeURIComponent(key);
// missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
val = val === undefined ? null : decodeURIComponent(val);
if (!ret.hasOwnProperty(key)) {
ret[key] = val;
} else if (Array.isArray(ret[key])) {
ret[key].push(val);
} else {
ret[key] = [ret[key], val];
}
return ret;
}, {});
};
exports.stringify = function (obj) {
return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];
if (val === undefined) {
return '';
}
if (val === null) {
return key;
}
if (Array.isArray(val)) {
return val.sort().map(function (val2) {
return strictUriEncode(key) + '=' + strictUriEncode(val2);
}).join('&');
}
return strictUriEncode(key) + '=' + strictUriEncode(val);
}).filter(function (x) {
return x.length > 0;
}).join('&') : '';
};
/***/ },
/* 58 */
/***/ function(module, exports) {
'use strict';
module.exports = function (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
};
/***/ }
/******/ ])
});
; |
src/parser/shared/modules/features/RaidHealthTab/TabComponent/Graph.js | yajinni/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import fetchWcl from 'common/fetchWclApi';
import RaidHealthChart from './RaidHealthChart';
const CLASS_CHART_LINE_COLORS = {
DeathKnight: 'rgba(196, 31, 59, 0.6)',
Druid: 'rgba(255, 125, 10, 0.6)',
Hunter: 'rgba(171, 212, 115, 0.6)',
Mage: 'rgba(105, 204, 240, 0.6)',
Monk: 'rgba(45, 155, 120, 0.6)',
Paladin: 'rgba(245, 140, 186, 0.6)',
Priest: 'rgba(255, 255, 255, 0.6)',
Rogue: 'rgba(255, 245, 105, 0.6)',
Shaman: 'rgba(36, 89, 255, 0.6)',
Warlock: 'rgba(148, 130, 201, 0.6)',
Warrior: 'rgba(199, 156, 110, 0.6)',
DemonHunter: 'rgba(163, 48, 201, 0.6)',
};
class Graph extends React.PureComponent {
static propTypes = {
reportCode: PropTypes.string.isRequired,
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
offset: PropTypes.number.isRequired,
};
constructor() {
super();
this.state = {
data: null,
};
}
componentDidMount() {
this.load();
}
componentDidUpdate(prevProps) {
if (prevProps.reportCode !== this.props.reportCode || prevProps.start !== this.props.start || prevProps.end !== this.props.end) {
this.load();
}
}
load() {
const { reportCode, start, end } = this.props;
fetchWcl(`report/tables/resources/${reportCode}`, {
start,
end,
abilityid: 1000,
})
.then(json => {
console.log('Received player health', json);
this.setState({
data: json,
});
});
}
render() {
const data = this.state.data;
if (!data) {
return (
<div>
Loading...
</div>
);
}
const { start, end, offset } = this.props;
const players = data.series.filter(item => Boolean(CLASS_CHART_LINE_COLORS[item.type]));
const entities = [];
players.forEach(series => {
const newSeries = {
...series,
lastValue: 100, // fights start at full hp
data: {},
};
series.data.forEach((item) => {
const secIntoFight = Math.floor((item[0] - start) / 1000);
const health = item[1];
newSeries.data[secIntoFight] = Math.min(100, health);
});
entities.push(newSeries);
});
const deathsBySecond = {};
if (this.state.data.deaths) {
this.state.data.deaths.forEach((death) => {
const secIntoFight = Math.floor((death.timestamp - start) / 1000);
if (death.targetIsFriendly) {
deathsBySecond[secIntoFight] = true;
}
});
}
const fightDurationSec = Math.ceil((end - start) / 1000);
for (let i = 0; i <= fightDurationSec; i += 1) {
entities.forEach((series) => {
series.data[i] = series.data[i] !== undefined ? series.data[i] : series.lastValue;
series.lastValue = series.data[i];
});
deathsBySecond[i] = deathsBySecond[i] !== undefined ? deathsBySecond[i] : undefined;
}
// transform data into react-vis format
const playerHealth = entities.map(player => {
const data = Object.entries(player.data).map(([key, value]) => ({ x: Number(key), y: value }));
return {
title: player.name,
backgroundColor: CLASS_CHART_LINE_COLORS[player.type],
borderColor: CLASS_CHART_LINE_COLORS[player.type],
data,
};
});
const deaths = Object.entries(deathsBySecond).filter(([_, value]) => Boolean(value)).map(([key]) => ({ x: Number(key) }));
return (
<div className="graph-container">
<RaidHealthChart
players={playerHealth}
deaths={deaths}
startTime={start}
endTime={end}
offsetTime={offset}
/>
</div>
);
}
}
export default Graph;
|
imports/ui/components/templates/PageTemplate/PageTemplate.js | latotty/meteor-sweeper | import React from 'react';
import PropTypes from 'prop-types';
import { Grid } from 'react-bootstrap';
export const PageTemplate = ({ navigation, children, ...props }) => (
<div>
{navigation}
<Grid {...props}>
{children}
</Grid>
</div>
);
PageTemplate.propTypes = {
navigation: PropTypes.node.isRequired,
children: PropTypes.node.isRequired,
};
export default PageTemplate;
|
simple/index.ios.js | IllegalCreed/react-native-webview-richeditor | /**
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Button,
Text,
View
} from 'react-native';
import RichEditor from 'react-native-webview-richeditor';
import KeyboardSpacer from 'react-native-keyboard-spacer';
export default class simple extends Component {
render() {
return (
<View style={styles.container}>
<RichEditor />
<KeyboardSpacer/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('simple', () => simple);
|
src/components/LocationMap/LocationMap.js | rlesniak/tind3r.com | // @flow
import React, { Component } from 'react';
import ReactGA from 'react-ga';
import { observer } from 'mobx-react';
import GoogleMap from 'google-map-react';
import NotificationSystem from 'react-notification-system';
import { CurrentUser } from 'models/CurrentUser';
import './LocationMap.scss';
type PropsType = {
currentUser: CurrentUser,
};
const K_WIDTH = 10;
const K_HEIGHT = 10;
const greatPlaceStyle = {
position: 'absolute',
width: K_WIDTH,
height: K_HEIGHT,
left: -K_WIDTH / 2,
top: -K_HEIGHT / 2,
borderRadius: K_HEIGHT,
backgroundColor: '#0084ff',
};
const Marker = () => (
<div className="marker">
<div style={greatPlaceStyle} />
</div>
);
@observer
class LocationMap extends Component {
props: PropsType;
notificationSystem: ?any;
handleError = () => {
if (this.notificationSystem) {
this.notificationSystem.addNotification({
level: 'error',
position: 'tc',
autoDismiss: 5,
message: 'Position change not significant or you change too far in small amount of time. Try again later',
});
}
ReactGA.event({
category: 'Settings',
action: 'Update location error',
});
}
handleOnMapClick = ({ lat, lng }: Object) => {
this.props.currentUser.updateLocation(lat, lng, this.handleError);
ReactGA.event({
category: 'Settings',
action: 'Update location',
});
}
render() {
const { currentUser } = this.props;
const center = [currentUser.pos.lat, currentUser.pos.lon];
if (!currentUser.pos.lat) {
return (
<div className="location-map">
<h1>To see map and to be able to change location, click save to fetch your current location.</h1>
</div>
);
}
return (
<div className="location-map">
<NotificationSystem ref={(ref) => { this.notificationSystem = ref; }} />
<GoogleMap
bootstrapURLKeys={{ key: 'AIzaSyDd3XG700RoXgHsnnu53gMz13gO8SOWqZc' }}
center={center}
zoom={12}
onClick={this.handleOnMapClick}
>
<Marker lat={currentUser.pos.lat} lng={currentUser.pos.lon} />
</GoogleMap>
</div>
);
}
}
export default LocationMap;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.