target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
app/containers/Swash/index.js
jonnymarsh96/wuzgud
/* * * Swash * */ import React from 'react'; import Helmet from 'react-helmet'; import Responsive from 'react-responsive'; import {Link} from 'react-router'; import Menu from 'material-ui/svg-icons/navigation/Menu'; import TextField from 'material-ui/TextField'; import Person from 'material-ui/svg-icons/social/person'; import Description from 'material-ui/svg-icons/action/description'; import AccountBalance from 'material-ui/svg-icons/action/account-balance'; import ContentCopy from 'material-ui/svg-icons/content/content-copy'; import Assignment from 'material-ui/svg-icons/action/assignment'; import AttachMoney from 'material-ui/svg-icons/editor/attach-money'; import CheckCircle from 'material-ui/svg-icons/action/check-circle'; import Arrow from 'material-ui/svg-icons/navigation/arrow-downward'; import Toggle from 'material-ui/Toggle'; import FlatButton from "material-ui/FlatButton"; import Dialog from 'material-ui/Dialog'; export default class Swash extends React.PureComponent { constructor(props){ super(props); this.state={ open:false, name:'', email:'', password:'', signUpName:'', signUpEmail:'', signUpPassword:'', } } handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; scrollDown=(num)=>{ window.scrollBy(0,num); } handleName = (event) =>{ this.setState({ name:event.target.value }) } handleEmail = (event) =>{ this.setState({ email:event.target.value }) } handlePassword = (event) =>{ this.setState({ password:event.target.value }) } handleSignUpName = (event) =>{ this.setState({ name:event.target.value }) } handleSignUpEmail = (event) =>{ this.setState({ email:event.target.value }) } handleSignUpPassword = (event) =>{ this.setState({ password:event.target.value }) } signUp = () => { var data = new FormData(); data.append("name", this.state.name); data.append("email", this.state.email); data.append("password", this.state.password); fetch("http://localhost:8000/api/signUp", { method:"post", body:data }) .then(function(response){ return response.json(); }) .then(function(json){ if(json.success){ alert("success"); } else if(json.error){ alert(json.error); } }) } render() { const headerStyle={ display:"flex", minHeight:"100vh", background:"url(http://localhost:8000/terrah-holly-241981.jpg)", backgroundSize:"cover", width:"100%", flexDirection:"column", justifyContent:"center", alignItems:"center" } const navBar={ display:"flex", flexDirection:"row", width:"100%", height:"124px", justifyContent:"space-between", position:"absolute", top:"0", } const signIn={ } const imageStyle={ display:"flex", flexDirection:"row", } const logoStyle={ width:"100px", height:"100px", marginTop:"30px", color:"#ffffff", marginLeft:"50px", fontSize:"300px", } const navLink={ textDecoration:"0", display:"flex", flexDirection:"column", padding:"15px", marginTop:"25px", color:"#555555", fontSize:"18px", fontFamily:"Open Sans", fontWeight:"bold", } const boxOne={ display:"flex", flexDirection:"column", width:"50%", height:"700px", color:"#F28705", margin:"0 auto", marginTop:"200px", } const heading={ display:"flex", fontSize:"25px", justifyContent:"center", color:"#ffffff", fontFamily:"Berkshire Swash", padding:"10px", marginTop:"20px" } const h1={ fontFamily:"Berkshire Swash", textShadow:"2px 2px 2px #000000", fontSize:"5em", color:"#F1A524", } const parStyle1={ width:"100%", borderRadius:"5px", background:"rgba(0,0,0,.0)", display:"flex", flexDirection:"column", fontSize:"15px", color:"#ffffff", fontFamily:"Roboto, sans serif", marginBottom:"0px", padding:"25px" } const take={ height:"20px", fontSize:"1.7em", color:"#F1A524", fontFamily:"Patrick Hand SC", textAlign:"center", pddingTop:"200px", fontweight:"bold", textShadow:"2px 2px 2px #DB2C28", } const arrow={ height:"50px", color:"#F1A524", textShadow:"2px 2px 2px #DB2C28", } const mainStyle={ display:"flex", flexDirection:"row", marginTop:"0px", height:"334px", } const container={ position:"relative", width:"50%", } const image={ display:"block", width:"100%", height:"auto", } const overlay={ position:"absolute", top:"0", bottom:"0", left:"0", right:"0", height:"334px", width:"100%", transition:".5s ease", background:"rgba(72,127,60, 0.8)", borderRadius:"0px", } const text={ color:"white", fontSize:"3em", fontWeight:"bold", position:"absolute", top:"50%", left:"50%", transform:"translate(-50%, -50%)", textAlign:"center", display:"flex", flexDirection:"row", justifyContent:"center", alignItems:"center", } const pescatarian={ position:"relative", width:"600px", backgroundImage:"url(http://localhost:8000/Brown_Trout_Rising_grande.jpg)", backgroundRepeat:"no-repeat", marginTop:"0px", borderRadius:"0px", display:"flex", flexDirection:"row", } const trekker={ position:"relative", width:"580px", backgroundImage:"url(http://localhost:8000/kaidi-guo-236880.jpg)", backgroundRepeat:"no-repeat", marginTop:"0px", borderRadius:"0px", } const textT={ color:"white", fontSize:"3em", fontWeight:"bold", position:"absolute", top:"50%", left:"50%", transform:"translate(-50%, -50%)", textAlign:"center", display:"flex", flexDirection:"row", justifyContent:"center", alignItems:"center", } const overlayT={ position:"absolute", top:"0", bottom:"0", left:"0", right:"0", height:"334px", width:"100%", transition:".5s ease", background:"rgba(18,12,133, 0.8)", borderRadius:"0px", } const homeBase={ position:"relative", width:"580px", backgroundImage:"url(http://localhost:8000/Homebase.jpg)", backgroundRepeat:"no-repeat", marginTop:"0px", borderRadius:"0px", } const textH={ color:"white", fontSize:"3em", fontWeight:"bold", position:"absolute", top:"50%", left:"50%", transform:"translate(-50%, -50%)", textAlign:"center", display:"flex", flexDirection:"row", justifyContent:"center", alignItems:"center", } const overlayH={ position:"absolute", top:"0", bottom:"0", left:"0", right:"0", height:"334px", width:"100%", transition:".5s ease", background:"rgba(120,69,26, 0.8)", borderRadius:"0px", } const pescBox={ height:"30%", width:"40%", display:"flex", alignContent:"center", background:"rgba(72,127,60, 0.8)", margin:"0 auto", borderRadius:"5px", border:"1px solid rgba(72,127,60, 0.8) " } const brands={ color:"#", padding:"20px", fontSize:"1em", fontFamily:"Patrick Hand SC", textAlign:"center", color:"#F1A524", } const pescText={ color:"#FFFFFF", padding:"20px", fontSize:"2em", fontFamily:"Patrick Hand SC", textAlign:"center", } const pescLink={ height:"100px", width:"10%", display:"flex", alignContent:"center", background:"rgba(72,127,60, 1)", margin:"0 auto", marginTop:"20px", borderRadius:"5px" } const homeBox={ height:"30%", width:"40%", display:"flex", alignContent:"center", background:"rgba(120,69,26, 0.8)", margin:"0 auto", borderRadius:"5px", border:"1px solid rgba(120,69,26, .95) " } const homeText={ color:"#ffffff", padding:"20px", fontSize:"2em", fontFamily:"Patrick Hand SC", textAlign:"center", fontweight:"bold", } const homeLink={ height:"100px", width:"10%", display:"flex", alignContent:"center", background:"rgba(120,69,26, 1)", margin:"0 auto", marginTop:"20px", borderRadius:"5px" } const trekBox={ height:"30%", width:"40%", display:"flex", alignContent:"center", background:"rgba(18,12,133, 0.8)", margin:"0 auto", borderRadius:"5px", border:"1px solid rgba(18,12,133, 0.8) " } const trekText={ color:"#ffffff", padding:"30px", fontSize:"2.3em", fontFamily:"Patrick Hand SC", textAlign:"center", margin:"0 auto", } const trekLink={ height:"100px", width:"10%", display:"flex", alignContent:"center", background:"rgba(18,12,133, 1)", margin:"0 auto", marginTop:"20px", borderRadius:"5px" } const paragraphStyle={ display:"flex", fontSize:"2em", justifyContent:"center", color:"#CEDAF5", fontFamily:"Patrick Hand SC", textAlign:"start", fontWeight:"bold", } const parallax={ backgroundImage: "url(http://localhost:8000/pescatarian.jpg)", minHeight: "700px", backgroundAttachment: "fixed", backgroundPosition: "center", backgroundRepeat: "no-repeat", backgroundSize:"cover", display:"flex", flexDirection:"column", justifyContent:"center", } const parallaxTrek={ backgroundImage: "url(http://localhost:8000/Thetrekker.jpg)", minHeight: "700px", backgroundAttachment: "fixed", backgroundPosition: "center", backgroundRepeat: "no-repeat", backgroundSize:"cover", display:"flex", flexDirection:"column", justifyContent:"center", } const parallaxHome={ backgroundImage: "url(http://localhost:8000/Homebase2.jpg)", minHeight: "700px", backgroundAttachment: "fixed", backgroundPosition: "center", backgroundRepeat: "no-repeat", backgroundSize:"cover", display:"flex", flexDirection:"column", justifyContent:"center", } const tentFPR={ width:"64px", margin:"0 auto", marginTop:"0px", } const packFPR={ width:"64px", margin:"0 auto", marginTop:"0px", } const poleFPR={ width:"64px", margin:"0 auto", marginTop:"0px", } const tentFPR2={ width:"64px", margin:"0 auto", marginTop:"0px", } const packFPR2={ width:"64px", margin:"0 auto", marginTop:"0px", } const poleFPR2={ width:"64px", margin:"0 auto", marginTop:"0px", } const fullPage={ width:"70%", height:"70px", borderRadius:"6px", background:"#ffffff", display:"flex", flexDirection:"row", justifyContent:"center", marginTop:"200px", marginLeft:"50px" } const cont={ height:"100px", width:"100%", display:"flex", flexDirection:"row", fontSize:"5em" } const contin={ fontDecoration:"none", fontFamily:"Permanent Marker", textAlign:"center", margin:"0 auto", } const copy={ fontSize:".4em", marginTop:"-15px", marginLeft:"7px", } const actions = [ <FlatButton label="Cancel" style={button} onTouchTap={this.handleClose} />, ]; const button={ } const logIn={ height:"700px", width:"100%", display:"flex", flexDirection:"column", margin:"0 auto", } const email={ width:"80%", height:"40px", border:"1px solid #FFDC00", borderRadius:"3px", margin:"30px", } const name={ width:"80%", height:"40px", border:"1px solid #FFDC00", borderRadius:"3px", margin:"30px", } const password={ width:"80%", height:"40px", border:"1px solid #FFDC00", borderRadius:"3px", margin:"30px", } const submit={ width:"100px", height:"30px", border:"1px solid #FFDC00", borderRadius:"3px", margin:"10px", color:"#000000" } const pescBuy={ height:"100px", width:"10%", borderRadius:"3px", background:"rgba(72,127,60, 0.8)", margin:"0 auto", marginTop:"40px", display:"flex", flexDirection:"column", padding:"10px", fontSize:"1.4em", textAlign:"center", color:"#ffffff", } const trekBuy={ height:"120px", width:"10%", borderRadius:"3px", background:"rgba(18,12,133, 0.8)", margin:"0 auto", marginTop:"40px", display:"flex", flexDirection:"column", padding:"10px", fontSize:"1.4em", textAlign:"center", color:"#ffffff", } const homeBuy={ height:"120px", width:"10%", borderRadius:"3px", background:"rgba(120,69,26, 0.8)", margin:"0 auto", marginTop:"40px", display:"flex", flexDirection:"column", padding:"10px", fontSize:"1.4em", textAlign:"center", color:"#ffffff", } const logo={ height:"450px" } return ( <div> <Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/> <Responsive minDeviceWidth={1024}> <header style={headerStyle}> <nav style={navBar}> <div style={logoStyle}><img style={logo} src="http://localhost:8000/swashnew.png"/> </div> <div style={signIn} onTouchTap={this.handleOpen}> Please Log In <img src="http://localhost:8000/icons/002-log.png"/> <br/> Sign Up <img src="http://localhost:8000/icons/001-rope.png"/> </div> </nav> <div style={boxOne}> <div style={heading}></div> <div style={parStyle1}> <h1 style={h1}>Premium outdoor clothing for The modern day Swashbuckler</h1> <p style={paragraphStyle}>All types.<br/> <br/> </p> <div style={fullPage}> <img style={tentFPR} src="http://localhost:8000/icons/001-tent.png" onTouchTap={()=>this.scrollDown(2600)}/> <img style={packFPR} src="http://localhost:8000/icons/002-backpack.png" onTouchTap={()=>this.scrollDown(1800)}/> <img style={poleFPR} src="http://localhost:8000/icons/003-spinning.png" onTouchTap={()=>this.scrollDown(800)}/> </div> </div> </div> </header> <div style={mainStyle}> <div style={pescatarian}> <div style={overlay}> <div style={text}> FisherFit <div style={copy}>&copy;</div> </div> </div> </div> <span style={pescText}> </span> </div> <div style={parallax}> <div style={pescBox}> <span style={pescText}> This subscription will send, to your door, FISHING clothes fresher than a brown trout caught straight out the Chatahoochee River, every stinkin month.<br/> <span style={brands}> Features brands like Cloumbia PFG, Simms, Patagonia and more..</span> </span> </div> <div style={pescBuy}> BUY NOW <img style={poleFPR2} src="http://localhost:8000/icons/003-spinning.png" onTouchTap={()=>this.scrollDown(1000)}/> </div> </div> <div style={mainStyle}> <div style={trekker}> <div style={overlayT}> <div style={textT}> WildStride <div style={copy}>&copy;</div> </div> </div> </div> </div> <div style={parallaxTrek}> <div style={trekBox}> <span style={trekText}> So, you like taking in nature on your stroll through the wild. We're betting you'll like it even more wearing one of these hand picked selection of comfy, hi-tech mountain garb we send to your door monthly.<br/> <span style={brands}> Featuring Brands such as Mountain Khaki, Kavu, NorthFace and more...</span> </span> </div> <div style={trekBuy}>BUY NOW <img style={packFPR2} src="http://localhost:8000/icons/002-backpack.png" onTouchTap={()=>this.scrollDown(1680)}/> </div> </div> <div style={mainStyle}> <div style={homeBase}> <div style={overlayH}> <div style={textH}> SedgeStud <div style={copy}>&copy;</div> </div> </div> </div> </div> <div style={parallaxHome}> <div style={homeBox}> <span style={homeText}> Our premium selection of the most functional, comfortable, practicle packables on the market makes you king of hanging by the fire with the buds, And might just soften the blow when you get a lil dirt in your oatmeal.<br/> <span style={brands}> Features brands: NorthFace, Marmot, Patagonia, Moutain Hardware and even more... </span> </span> </div> <div style={homeBuy}>BUY NOW <img style={tentFPR2} src="http://localhost:8000/icons/001-tent.png" /> </div> </div> <div style={cont}> <div style={logoStyle}> <img src="http://localhost:8000/unnamed.png"/> </div> <Link style={contin}> Continue to site... </Link> </div> </Responsive> <Responsive maxDeviceWidth={1023}> <header style={headerStyle}> <nav style={navBar}> <div style={logoStyle}><img src="http://localhost:8000/unnamed.png"/></div> </nav> <div style={boxOne}> <div style={heading}></div> <div style={parStyle1}> <h1 style={h1}>Premium outdoor clothing for The modern day Swashbuckler</h1> <p style={paragraphStyle}>All types.<br/> <br/> </p> <div style={fullPage}> <img style={tentFPR} src="http://localhost:8000/icons/001-tent.png" onTouchTap={()=>this.scrollDown(2600)}/> <img style={packFPR} src="http://localhost:8000/icons/002-backpack.png" onTouchTap={()=>this.scrollDown(1800)}/> <img style={poleFPR} src="http://localhost:8000/icons/003-spinning.png" onTouchTap={()=>this.scrollDown(800)}/> </div> </div> </div> </header> <div style={mainStyle}> <div style={pescatarian}> <div style={overlay}> <div style={text}> Pescatarian </div> </div> </div> <span style={pescText}> for our fisherman </span> </div> <div style={parallax}> <div style={pescBox}> <span style={pescText}> Our premium selection of the most functional, comfortable, practicle packables on the market makes you king of hanging by the fire with the buds, And might just soften the blow when you get a lil dirt in your oatmeal.<br/> <span style={brands}> Features brands: NorthFace, Marmot, Patagonia, Moutain Hardware and even more... </span> </span> </div> <img style={poleFPR2} src="http://localhost:8000/icons/003-spinning.png" onTouchTap={()=>this.scrollDown(1000)}/> </div> <div style={mainStyle}> <div style={trekker}> <div style={overlayT}> <div style={textT}> WildStride </div> </div> </div> </div> <div style={parallaxTrek}> <div style={trekBox}> <span style={trekText}> "The one who wonders, finds a new path"<br/> -Norwegian Proverb </span> </div> <img style={packFPR2} src="http://localhost:8000/icons/002-backpack.png" onTouchTap={()=>this.scrollDown(1680)}/> </div> <div style={mainStyle}> <div style={homeBase}> <div style={overlayH}> <div style={textH}> SedgeStud </div> </div> </div> </div> <div style={parallaxHome}> <div style={homeBox}> <span style={homeText}> There's no wifi in the forest, but we promise you'll find a better connection. </span> </div> <img style={tentFPR2} src="http://localhost:8000/icons/001-tent.png" /> </div> <div style={cont}> <div style={logoStyle}> <img src="http://localhost:8000/unnamed.png"/> </div> <Link style={contin}> Continue to site... </Link> </div> </Responsive> <Dialog title="Log In" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} style={logIn} > <input style={email} onChange={this.handleEmail} value={this.state.email} type="text" placeholder="Email" /><br/> <input style={password} onChange={this.handlePassword} value={this.state.password} type="password" placeholder="Password" /><br/> <input style={submit} type="submit" onTouchTap={this.signUp}/> <h3>Sign Up</h3> <input style={name} onChange={this.handleSignUpName} value={this.state.name} type="text" placeholder="Name" /><br/> <input style={email} onChange={this.handleSignUpEmail} value={this.state.email} type="text" placeholder="Email" /><br/> <input style={password} onChange={this.handleSignUpPassword} value={this.state.password} type="password" placeholder="Password" /><br/> <input style={submit} type="submit" onTouchTap={this.signUp}/> </Dialog> </div> ); } }
src/index.js
tableflip/landexplorer
import React from 'react' import { render } from 'react-dom' import Routes from './routes.jsx' import { browserHistory } from 'react-router' render( <Routes history={browserHistory} />, document.getElementById('react-root') )
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js
RobzDoom/frame_trap
/** * 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. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function* load(limit) { let i = 1; while (i <= limit) { yield { id: i, name: i }; i++; } } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { const users = []; for (let user of load(4)) { users.push(user); } this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-generators"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/svg-icons/action/info-outline.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionInfoOutline = (props) => ( <SvgIcon {...props}> <path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/> </SvgIcon> ); ActionInfoOutline = pure(ActionInfoOutline); ActionInfoOutline.displayName = 'ActionInfoOutline'; ActionInfoOutline.muiName = 'SvgIcon'; export default ActionInfoOutline;
frontend/src/DiscoverMovie/Table/DiscoverMovieTableOptions.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import { inputTypes } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; class DiscoverMovieTableOptions extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { includeRecommendations: props.includeRecommendations }; } componentDidUpdate(prevProps) { const { includeRecommendations } = this.props; if (includeRecommendations !== prevProps.includeRecommendations) { this.setState({ includeRecommendations }); } } // // Listeners onChangeOption = ({ name, value }) => { this.setState({ [name]: value }, () => { this.props.onChangeOption({ [name]: value }); }); }; // // Render render() { const { includeRecommendations } = this.state; return ( <FormGroup> <FormLabel>{translate('IncludeRadarrRecommendations')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="includeRecommendations" value={includeRecommendations} helpText={translate('IncludeRecommendationsHelpText')} onChange={this.onChangeOption} /> </FormGroup> ); } } DiscoverMovieTableOptions.propTypes = { includeRecommendations: PropTypes.bool.isRequired, onChangeOption: PropTypes.func.isRequired }; export default DiscoverMovieTableOptions;
src/routes/home/index.js
jackinf/skynda.me
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import fetch from '../../core/fetch'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,contentSnippet}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Home news={data.news} />, }; }, };
src/addons/link/__tests__/LinkedStateMixin-test.js
Jericho25/react
/** * 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. * * @emails react-core */ 'use strict'; /*jshint evil:true */ describe('LinkedStateMixin', function() { var LinkedStateMixin; var React; var ReactLink; var ReactTestUtils; beforeEach(function() { LinkedStateMixin = require('LinkedStateMixin'); React = require('React'); ReactLink = require('ReactLink'); ReactTestUtils = require('ReactTestUtils'); }); it('should create a ReactLink for state', function() { var Component = React.createClass({ mixins: [LinkedStateMixin], getInitialState: function() { return {value: 'initial value'}; }, render: function() { return <span>value is {this.state.value}</span>; } }); var component = ReactTestUtils.renderIntoDocument(<Component />); var link = component.linkState('value'); expect(component.state.value).toBe('initial value'); expect(link.value).toBe('initial value'); link.requestChange('new value'); expect(component.state.value).toBe('new value'); expect(component.linkState('value').value).toBe('new value'); }); });
ajax/libs/angular.js/1.1.3/angular-scenario.js
andersem/cdnjs
/*! * jQuery JavaScript Library v1.8.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) */ (function( window, undefined ) { 'use strict'; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.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 detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // 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) 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*\.|)\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 and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; 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; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // 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: $(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 current version of jQuery being used jquery: "1.8.2", // 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, name, selector ) { // 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; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // 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; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, 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 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; 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, 1 ); } // 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 ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, 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 // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( 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 && core_rnotwhite.test( 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 name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === 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 type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( 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, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // 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 ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.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 = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, 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, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } 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, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // 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 ); } // 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".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // 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.split( core_rspace ), 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" && ( !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; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // 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 = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = 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 === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); 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 ] = list.fire deferred[ tuple[0] ] = list.fire; 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, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; support = { // 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, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // 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, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // 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 submitBubbles: true, changeBubbles: true, focusinBubbles: false, 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; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", 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 = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // 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). // (only IE 8 fails this test) 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"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) 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 ); // NOTE: To any future maintainer, we've 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. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + 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, 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 = jQuery.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; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, 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(" "); } } } 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; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { 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 parts, part, attr, name, l, 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" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(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 ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, 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--; } 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", true ); jQuery.removeData( elem, key, true ); }) }); } }); 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, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; 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 classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } 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.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className 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 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, 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, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } 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; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { 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 ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else 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 it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = 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 ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // 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; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? 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 ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // 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; } } }); }); // 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 ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE 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; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || 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 = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { 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 events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = 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 !== "undefined" && (!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 = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[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: tns[1], 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 handlers = events[ type ]; if ( !handlers ) { 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; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, 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 = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // 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; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.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 ( eventType.length === 0 && origCount !== eventType.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", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // 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 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // 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 ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( 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) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery 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) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { 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 ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // 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 that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( 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; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement 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 eventDoc, doc, body, 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; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, 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(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; 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 ] === "undefined" ) { 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; }; function returnFalse() { return false; } function returnTrue() { return 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 = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // 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, selector = handleObj.selector; // 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, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", 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, "_change_attached" ) ) { 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, "_change_attached", 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 origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( 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 ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, 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 ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); 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 ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } return (cache[ key ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // 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 not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // 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 ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, 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 ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = 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 assertUsableClassName = 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 assertUsableName = 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 = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { 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]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // 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 ( 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 } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; 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; }; // Element contains another contains = Sizzle.contains = 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) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { 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] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( 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 unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className ]; if ( !pattern ) { pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { return function( elem, context ) { 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.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "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: { "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; }; }), "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; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "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 "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, 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" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ 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 ) { soFar = soFar.slice( match[0].length ); } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[ type ]( match, document, true ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } 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 addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } 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 ) { // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if ( seed && postFinder ) { return; } var i, elem, postFilterIn, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), // 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 ) { postFilterIn = condense( matcherOut, postMap ); postFilter( postFilterIn, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while ( i-- ) { if ( (elem = postFilterIn[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } // Keep seed and results synchronized if ( seed ) { // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); } } } 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 { // The concatenated values are (context, xml) for backCompat 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 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } 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, 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 ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // 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 ) { for ( j = 0; (matcher = setMatchers[j]); 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; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ 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, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; 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 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); 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, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"], // matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active", ":focus" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // 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 (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.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 ( context.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 + groups[i].join(""); } 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"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !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 || 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, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // 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, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } 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), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, 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; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // 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.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( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } 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, name, core_slice.call( arguments ).join(",") ); }; }); 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, i ) { 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, i ) { 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, 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, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, 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; // 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. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } 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.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // 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 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { 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( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } 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( elem.getElementsByTagName( "*" ) ); 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 ) { if ( !isDisconnected( this[0] ) ) { // 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 ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } 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 cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. 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" && 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.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; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; 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 ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; 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) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, 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 ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, 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 = {}, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // 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 ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.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 { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", 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 ) { 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, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } 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: { "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"; } // 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, numeric, extra ) { 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 ); } //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 ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || 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 ) { 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.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; 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 ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], 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; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { 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" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "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 ); 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 ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; 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 if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 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 >= 1 && 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 there is no filter style applied in a css rule, we are done if ( 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 ) { // 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" }, function() { if ( computed ) { return 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 ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( 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, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; 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, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ 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 { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. 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 ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, 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 = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, 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 = ["*/"] + ["*"]; // #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, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // 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 ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, 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"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); 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({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // 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 ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type 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: { context: true, url: true } }, 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 // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // 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 // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof 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, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // 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 === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) 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[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } 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 ( !statusText || status ) { 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( "ajax" + ( isSuccess ? "Success" : "Error" ), [ 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" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // 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() ) || false; s.crossDomain = parts && ( parts.join(":") + ( parts[ 3 ] ? "" : parts[ 1 ] === "http:" ? 80 : 443 ) ) !== ( ajaxLocParts.join(":") + ( 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; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // 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; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* 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 ct, type, finalDataType, firstDataType, 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 conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 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 }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // 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, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( 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 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"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, 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 || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; 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 ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // 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 (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { 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( _ ) {} // 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, statusText, responseHeaders, responses, xml; // 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 { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // 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, 0 ); } 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(0,1); } } }; } }); } 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; }, 0 ); 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, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), percent = 1 - ( remaining / animation.duration || 0 ), 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, easing ) { 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; 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, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // 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 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; } } } 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 ) { var index, prop, value, length, dataShow, 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.done(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 ]; 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 ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); 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 any value as a 4th 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, false, "" ); // 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" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? 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 ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; 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 ); } }); } }); // 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; 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(); } }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; 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; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } 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 !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, 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 elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract 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 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // 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, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // 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 ); /** * @license AngularJS v1.1.3 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) {return String.fromCharCode(code);} var /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.noConflict * @function * * @description * Restores the previous global value of angular and returns the current instance. Other libraries may already use the * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to * restore the previous namespace and keep a reference to angular. * * @return {Object} The current angular namespace */ function noConflict() { var a = window.angular; window.angular = _angular; return a; } /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...) */ function isArrayLike(obj) { if (!obj || (typeof obj.length !== 'number')) return false; // We have on object which has length property. Should we treat it as array? if (typeof obj.hasOwnProperty != 'function' && typeof obj.constructor != 'function') { // This is here for IE8: it is a bogus object treat it as array; return true; } else { return obj instanceof JQLite || // JQLite (jQuery && obj instanceof jQuery) || // jQuery toString.call(obj) !== '[object Object]' || // some browser native object typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj) } } function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isArrayLike(obj)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only be identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ 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 ((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)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(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[key] && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} // As Per DOM Standards var TEXT_NODE = 3; var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch(e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name ng.directive:ngApp * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap on application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * at the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { element = jqLite(element); modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); injector.invoke( ['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){ scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configuration information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.1.3', // all of these placeholder strings will be replaced by rake's major: 1, // compile task minor: 1, dot: 3, codeName: 'radioactive-gargle' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, 'noConflict': noConflict }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name. * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) * - [parent()](http://api.jquery.com/parent/) * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers. * - [unbind()](http://api.jquery.com/unbind/) * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { element.triggerHandler('$destroy'); } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(events[type || event.type], function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var counter = 0; events.mouseenter = []; events.mouseleave = []; bindFn(element, 'mouseover', function(event) { counter++; if (counter == 1) { handle(event, 'mouseenter'); } }); bindFn(element, 'mouseout', function(event) { counter --; if (counter == 0) { handle(event, 'mouseleave'); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeType === 1) children.push(element); }); return children; }, contents: function(element) { return element.childNodes || []; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); } }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { if (element.nextElementSibling) { return element.nextElementSibling; } // IE8 doesn't have nextElementSibling var elm = element.nextSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.nextSibling; } return elm; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone, triggerHandler: function(element, eventName) { var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; forEach(eventFns, function(fn) { fn.call(element, null); }); } }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } }, /** * return the first item without deleting it */ peek: function(key) { var array = this[hashKey(key)]; if (array) { return array[0]; } } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name AUTO * @description * * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn') $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc object * @name AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following ways are all valid way of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $inject.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $inject.invoke(explicit); * * // inline * $inject.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name AUTO.$injector#get * @methodOf AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name AUTO.$injector#invoke * @methodOf AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name AUTO.$injector#instantiate * @methodOf AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name AUTO.$injector#annotate * @methodOf AUTO.$injector * * @description * Returns an array of service names which the function is requesting for injection. This API is used by the injector * to determine which services need to be injected into the function when the function is invoked. There are three * ways in which the function can be annotated with the needed dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting * the function into a string using `toString()` method and extracting the argument names. * <pre> * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of * services to be injected into the function. * <pre> * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController.$inject = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives * minification is a better choice: * * <pre> * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tempFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * </pre> * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described * above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with the `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * }); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * )}; * * }); * </pre> */ /** * @ngdoc method * @name AUTO.$provide#provider * @methodOf AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#factory * @methodOf AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#service * @methodOf AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#value * @methodOf AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#constant * @methodOf AUTO.$provide * @description * * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name AUTO.$provide#decorator * @methodOf AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instanciated. The function is called using the {@link AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate }; } } /** * @ngdoc function * @name ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * ! This is a private undocumented service ! * * @name ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name ng.$browser#addPollFn * @methodOf ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @name ng.$browser#url * @methodOf ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { if (lastBrowserUrl == url) return; lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name ng.$browser#onUrlChange * @methodOf ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name ng.$browser#cookies * @methodOf ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @name ng.$browser#defer * @methodOf ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name ng.$browser#defer.cancel * @methodOf ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; /** * @ngdoc function * @name ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link ng.$compileProvider#directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link ng.directive:ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name ng.$compileProvider * @function * * @description */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ', urlSanitizationWhitelist = /^\s*(https?|ftp|mailto):/; /** * @ngdoc function * @name ng.$compileProvider#directive * @methodOf ng.$compileProvider * @function * * @description * Register a new directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more * info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc function * @name ng.$compileProvider#urlSanitizationWhitelist * @methodOf ng.$compileProvider * @function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular * expression. If a match is found the original url is written into the dom. Otherwise the * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.urlSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { urlSanitizationWhitelist = regexp; return this; } return urlSanitizationWhitelist; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', '$document', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope, $document) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = getBooleanAttrName(this.$$element[0], key), $$observers = this.$$observers, normalizedVal; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } // sanitize a[href] values if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { urlSanitizationNode.setAttribute('href', value); // href property always returns normalized absolute url, so we can match against that normalizedVal = urlSanitizationNode.href; if (!normalizedVal.match(urlSanitizationWhitelist)) { this[key] = value = 'unsafe:' + normalizedVal; } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers $$observers && forEach($$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return fn; } }; var urlSanitizationNode = $document[0].createElement('a'), startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, where as we need to preserve the original selector so that we can modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); return function publicLinkFn(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! : $compileNodes; // Attach scope only to non-text nodes. for(var i = 0, ii = $linkNode.length; i<ii; i++) { var node = $linkNode[i]; if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) { $linkNode.eq(i).data('$scope', scope); } } safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes.length) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n; // copy nodeList so that linking doesn't break due to live list updates. var stableNodeList = []; for (i = 0, ii = nodeList.length; i < ii; i++) { stableNodeList.push(nodeList[i]); } for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = stableNodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); transcludeScope.$$transcluded = true; return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected their compile functions is executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached.. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace widgets on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolateScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolateScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith($rootElement, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if ((directiveValue = directive.template)) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith($rootElement, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newIsolateScopeDirective) { var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) { var match = definiton.match(LOCAL_REGEXP) || [], attrName = match[2]|| scopeName, mode = match[1], // @, =, or & lastValue, parentGet, parentSet; scope.$$isolateBindings[scopeName] = mode + attrName; switch (mode) { case '@': { attrs.$observe(attrName, function(value) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; if( attrs[attrName] ) { // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn scope[scopeName] = $interpolate(attrs[attrName])(parentScope); } break; } case '=': { parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + ' (directive: ' + newIsolateScopeDirective.name + ')'); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function parentValueWatch() { var parentValue = parentGet(parentScope); if (parentValue !== scope[scopeName]) { // we are out of sync and need to copy if (parentValue !== lastValue) { // parent changed and it has precedence lastValue = scope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(parentScope, parentValue = lastValue = scope[scopeName]); } } return parentValue; }); break; } case '&': { parentGet = $parse(attrs[attrName]); scope[scopeName] = function(locals) { return parentGet(parentScope, locals); } break; } default: { throw Error('Invalid isolate scope definition for directive ' + newIsolateScopeDirective.name + ': ' + definiton); } } }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null, scope: null }); $compileNode.html(''); $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; content = denormalizeTemplate(content); if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn); while(linkQueue.length) { var controller = linkQueue.pop(), linkRootElement = linkQueue.pop(), beforeTemplateLinkNode = linkQueue.pop(), scope = linkQueue.pop(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function textInterpolateLinkFn(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (name === 'class') { // we need to interpolate classes again, in the case the element was replaced // and therefore the two class attrs got merged - we want to interpolate the result interpolateFn = $interpolate(attr[name], true); } attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc object * @name ng.$compile.directive.Attributes * @description * * A shared object between directive compile / linking functions which contains normalized DOM element * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed * since all of these are treated as equivalent in Angular: * * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> */ /** * @ngdoc property * @name ng.$compile.directive.Attributes#$attr * @propertyOf ng.$compile.directive.Attributes * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc function * @name ng.$compile.directive.Attributes#$set * @methodOf ng.$compile.directive.Attributes * @function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name ng.$controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}; /** * @ngdoc function * @name ng.$controllerProvider#register * @methodOf ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just simple call to {@link AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(constructor, locals) { if(isString(constructor)) { var name = constructor; constructor = controllers.hasOwnProperty(name) ? controllers[name] : getter(locals.$scope, name, true) || getter($window, name, true); assertArgFn(constructor, name, true); } return $injector.instantiate(constructor, locals); }; }]; } /** * @ngdoc object * @name ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc object * @name ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name ng.$interpolateProvider#startSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name ng.$interpolateProvider#endSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ function $interpolate(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { try { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); } catch(err) { var newErr = new Error('Error while interpolating: ' + text + '\n' + err.toString()); $exceptionHandler(newErr); } }; fn.exp = text; fn.parts = parts; return fn; } } /** * @ngdoc method * @name ng.$interpolate#startSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; } /** * @ngdoc method * @name ng.$interpolate#endSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.endSymbol = function() { return endSymbol; } return $interpolate; }]; } var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function stripHash(url) { return url.split('#')[0]; } function matchUrl(url, obj) { var match = URL_MATCH.exec(url); match = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) !== 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'); } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix, appBaseUrl) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(newAbsoluteUrl) { var match = matchUrl(newAbsoluteUrl, this); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !'); } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix, appBaseUrl) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'); } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } LocationUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name ng.$location#absUrl * @methodOf ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name ng.$location#url * @methodOf ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name ng.$location#protocol * @methodOf ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name ng.$location#host * @methodOf ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name ng.$location#port * @methodOf ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name ng.$location#path * @methodOf ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name ng.$location#search * @methodOf ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} search */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name ng.$location#hash * @methodOf ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name ng.$location#replace * @methodOf ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) { LocationHashbangUrl.apply(this, arguments); this.$$rewriteAppUrl = function(absoluteLinkUrl) { if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length); } } } LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name ng.$location * * @requires $browser * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular * Services: Using $location} */ /** * @ngdoc object * @name ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name ng.$locationProvider#hashPrefix * @methodOf ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name ng.$locationProvider#html5Mode * @methodOf ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, basePath, pathPrefix, initUrl = $browser.url(), initUrlParts = matchUrl(initUrl), appBaseUrl; if (html5Mode) { basePath = $browser.baseHref() || '/'; pathPrefix = pathPrefixFromBase(basePath); appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + pathPrefix + '/'; if ($sniffer.history) { $location = new LocationUrl( convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix, appBaseUrl); } else { $location = new LocationHashbangInHtml5Url( convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1)); } } else { appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + (initUrlParts.path || '') + (initUrlParts.search ? ('?' + initUrlParts.search) : '') + '#' + hashPrefix + '/'; $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl); } $rootElement.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'), rewrittenUrl = $location.$$rewriteAppUrl(absHref); if (absHref && !elm.attr('target') && rewrittenUrl) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); afterLocationChange(oldUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); var currentReplace = $location.$$replace; if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), currentReplace); afterLocationChange(oldUrl); } }); } $location.$$replace = false; return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc object * @name ng.$logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider(){ var debug = true, self = this; /** * @ngdoc property * @name ng.$logProvider#debugEnabled * @methodOf ng.$logProvider * @description * @param {string=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name ng.$log#debug * @methodOf ng.$log * * @description * Write a debug message */ debug: (function () { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } } }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){ a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b)?b:undefined;}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), ch3 = ch2 + peek(2), fn = OPERATORS[ch], fn2 = OPERATORS[ch2], fn3 = OPERATORS[ch3]; if (fn3) { tokens.push({index:index, text:ch3, fn:fn3}); index += 3; } else if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek(i) { var num = i || 1; return index + num < text.length ? text.charAt(index + num) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { var ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return extend(function(self, locals) { return fn(self, locals, right); }, { constant:right.constant }); } function binaryFn(left, fn, right) { return extend(function(self, locals) { return fn(self, locals, left, right); }, { constant:left.constant && right.constant }); } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self, locals){ return left.assign(self, right(self, locals), locals); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!=','===','!=='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } if (token.json) { primary.constant = primary.literal = true; } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(self, locals) { return getter(object(self, locals), locals); }, { assign:function(self, value, locals) { return setter(object(self, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self, locals){ var args = [], context = contextGetter ? contextGetter(self, locals) : self; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } var fnPtr = fn(self, locals) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; var allConstant = true; if (peekToken().text != ']') { do { var elementFn = expression(); elementFns.push(elementFn); if (!elementFn.constant) { allConstant = false; } } while (expect(',')); } consume(']'); return extend(function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal:true, constant:allConstant }); } function object () { var keyValues = []; var allConstant = true; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); if (!value.constant) { allConstant = false; } } while (expect(',')); } consume('}'); return extend(function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self, locals); object[keyValue.key] = value; } return object; }, { literal:true, constant:allConstant }); } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; }; function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// /** * @ngdoc function * @name ng.$parse * @function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * <pre> * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * </pre> * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (tipically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * <pre> * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * }); * </pre> */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name ng.$q#defer * @methodOf ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#reject * @methodOf ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#when * @methodOf ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value corresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name ng.$q#all * @methodOf ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>} promises An array of promises. * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value corresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = promises.length, results = []; if (counter) { forEach(promises, function(promise, index) { ref(promise).then(function(value) { if (index in results) return; results[index] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (index in results) return; deferred.reject(reason); }); }); } else { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name ng.$routeProvider#when * @methodOf ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon (`:name`). All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a star (`*name`). All characters are * eagerly stored in `$routeParams` under the given `name` when the route matches. * * For example, routes like `/color/:color/largecode/*largecode/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly * created scope or the name of a {@link angular.Module#controller registered controller} * if passed as a string. * - `template` – `{string=|function()=}` – html template as a string or function that returns * an html template as a string which should be used by {@link ng.directive:ngView ngView} or * {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ng.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, they will be * resolved and converted to a value before the controller is instantiated and the * `$routeChangeSuccess` event is fired. The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is resolved * before its value is injected into the controller. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name ng.$routeProvider#otherwise * @methodOf ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { /** * @ngdoc object * @name ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} * directive and the {@link ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); sleep(2); // promises are not part of scenario waiting content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.$route#$routeChangeStart * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occurs. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeSuccess * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ng.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeError * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ng.$route#$routeUpdate * @eventOf ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ng.$route#reload * @methodOf ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ng.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param when {string} route when template to match the url against * @return {?Object} */ function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it // Escape regexp special characters. when = '^' + when.replace(/[-\/\\^$:*+?.()|[\]{}]/g, "\\$&") + '$'; var regex = '', params = [], dst = {}; var re = /\\([:*])(\w+)/g, paramMatch, lastMatchedIndex = 0; while ((paramMatch = re.exec(when)) !== null) { // Find each :param in `when` and replace it with a capturing group. // Append all other sections of when unchanged. regex += when.slice(lastMatchedIndex, paramMatch.index); switch(paramMatch[1]) { case ':': regex += '([^\\/]*)'; break; case '*': regex += '(.*)'; break; } params.push(paramMatch[2]); lastMatchedIndex = re.lastIndex; } // Append trailing path part. regex += when.substr(lastMatchedIndex); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var keys = [], values = [], template; forEach(next.resolve || {}, function(value, key) { keys.push(key); values.push(isString(value) ? $injector.get(value) : $injector.invoke(value)); }); if (isDefined(template = next.template)) { if (isFunction(template)) { template = template(next.params); } } else if (isDefined(template = next.templateUrl)) { if (isFunction(template)) { template = template(next.params); } if (isDefined(template)) { next.loadedTemplateUrl = template; template = $http.get(template, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (isDefined(template)) { keys.push('$template'); values.push(template); } return $q.all(values).then(function(values) { var locals = {}; forEach(values, function(value, index) { locals[keys[index]] = value; }); return locals; }); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name ng.$rootScopeProvider#digestTtl * @methodOf ng.$rootScopeProvider * @description * * Sets the number of digest iteration the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name ng.$rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link AUTO.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> angular.injector(['ng']).invoke(function($rootScope) { var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { scope.greeting = scope.salutation + ' ' + scope.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); }); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$destroyed = false; this.$$asyncQueue = []; this.$$listeners = {}; this.$$isolateBindings = {}; } /** * @ngdoc property * @name ng.$rootScope.Scope#$id * @propertyOf ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name ng.$rootScope.Scope#$new * @methodOf ng.$rootScope.Scope * @function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {boolean} isolate if true then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets it is useful for the widget to not accidentally read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watch * @methodOf ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison, the * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example * <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather than for reference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (typeof watchExp == 'string' && get.constant) { var originalFn = watcher.fn; watcher.fn = function(newVal, oldVal, scope) { originalFn.call(this, newVal, oldVal, scope); arrayRemove(array, watcher); }; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$digest * @methodOf ng.$rootScope.Scope * @function * * @description * Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. * * Usually you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example * <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue = this.$$asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { // "while dirty" loop dirty = false; current = target; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name ng.$rootScope.Scope#$destroy * @eventOf ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name ng.$rootScope.Scope#$destroy * @methodOf ng.$rootScope.Scope * @function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if ($rootScope == this || this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // This is bogus code that works around Chrome's GC leak // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$eval * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating Angular expressions. * * # Example * <pre> var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$evalAsync * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$apply * @methodOf ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * <pre> function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * </pre> * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name ng.$rootScope.Scope#$on * @methodOf ng.$rootScope.Scope * @function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - `{Scope}`: the current scope which is handling the event. * - `name` - `{string}`: Name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event * propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, args...)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { namedListeners[indexOf(namedListeners, listener)] = null; }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$emit * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$broadcast * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; listeners = current.$$listeners[name] || []; for (i=0, length = listeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name ng.$sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]), document = $document[0]; return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!document.documentMode || document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: document.securityPolicy ? document.securityPolicy.isActive : false }; }]; } /** * @ngdoc object * @name ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } var IS_SAME_DOMAIN_URL_MATCH = /^(([^:]+):)?\/\/(\w+:{0,1}\w*@)?([\w\.-]*)?(:([0-9]+))?(.*)$/; /** * Parse a request and location URL and determine whether this is a same-domain request. * * @param {string} requestUrl The url of the request. * @param {string} locationUrl The current browser location url. * @returns {boolean} Whether the request is for the same domain. */ function isSameDomain(requestUrl, locationUrl) { var match = IS_SAME_DOMAIN_URL_MATCH.exec(requestUrl); // if requestUrl is relative, the regex does not match. if (match == null) return true; var domain1 = { protocol: match[2], host: match[4], port: int(match[6]) || DEFAULT_PORTS[match[2]] || null, // IE8 sets unmatched groups to '' instead of undefined. relativeProtocol: match[2] === undefined || match[2] === '' }; match = URL_MATCH.exec(locationUrl); var domain2 = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null }; return (domain1.protocol == domain2.protocol || domain1.relativeProtocol) && domain1.host == domain2.host && (domain1.port == domain2.port || (domain1.relativeProtocol && domain2.port == DEFAULT_PORTS[domain2.protocol])); } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/; var defaults = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: {'Content-Type': 'application/json;charset=utf-8'}, put: {'Content-Type': 'application/json;charset=utf-8'} }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; var providerResponseInterceptors = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'), responseInterceptors = []; forEach(providerResponseInterceptors, function(interceptor) { responseInterceptors.push( isString(interceptor) ? $injector.get(interceptor) : $injector.invoke(interceptor) ); }); /** * @ngdoc function * @name ng.$http * @requires $httpBackend * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, * it is important to familiarize yourself with these apis and guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an http request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * </pre> * * Since the returned value of calling the $http function is a Promise object, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the api signature and type info below for more * details. * * A response status code that falls in the [200, 300) range is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * # Shortcut methods * * Since all invocation of the $http service require definition of the http method and url and * POST and PUT requests require response body/data to be provided as well, shortcut methods * were created to simplify using the api: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain http headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from this configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with name equal to the lower-cased http method name, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar * fassion as described above. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - if the `data` property of the request config object contains an object, serialize it into * JSON format. * * Response transformations: * * - if XSRF prefix is detected, strip it (see Security Considerations section below) * - if json response is detected, deserialize it using a JSON parser * * To override these transformation locally, specify transform functions as `transformRequest` * and/or `transformResponse` properties of the config object. To globally override the default * transforms, override the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. * * * # Caching * * To enable caching set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same url that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response for the first request. * * * # Response interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides following mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have read the token. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults, or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number}` – timeout in milliseconds. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * - **responseType** - `{string}` - see {@link * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(config) { config.method = uppercase(config.method); var xsrfHeader = {}, xsrfCookieName = config.xsrfCookieName || defaults.xsrfCookieName, xsrfHeaderName = config.xsrfHeaderName || defaults.xsrfHeaderName, xsrfToken = isSameDomain(config.url, $browser.url()) ? $browser.cookies()[xsrfCookieName] : undefined; xsrfHeader[xsrfHeaderName] = xsrfToken; var reqTransformFn = config.transformRequest || defaults.transformRequest, respTransformFn = config.transformResponse || defaults.transformResponse, defHeaders = defaults.headers, reqHeaders = extend(xsrfHeader, defHeaders.common, defHeaders[lowercase(config.method)], config.headers), reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), promise; // strip content-type if data is undefined if (isUndefined(config.data)) { delete reqHeaders['Content-Type']; } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request promise = sendReq(config, reqData, reqHeaders); // transform future response promise = promise.then(transformResponse, transformResponse); // apply interceptors forEach(responseInterceptors, function(interceptor) { promise = interceptor(promise); }); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, respTransformFn) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name ng.$http#get * @methodOf ng.$http * * @description * Shortcut method to perform `GET` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#delete * @methodOf ng.$http * * @description * Shortcut method to perform `DELETE` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#head * @methodOf ng.$http * * @description * Shortcut method to perform `HEAD` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#jsonp * @methodOf ng.$http * * @description * Shortcut method to perform `JSONP` request * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name ng.$http#post * @methodOf ng.$http * * @description * Shortcut method to perform `POST` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#put * @methodOf ng.$http * * @description * Shortcut method to perform `PUT` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name ng.$http#defaults * @propertyOf ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if (config.cache && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { v = toJson(v); } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); var status; // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var responseHeaders = xhr.getAllResponseHeaders(); // TODO(vojta): remove once Firefox 21 gets released. // begin: workaround to overcome Firefox CORS http response headers bug // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 // Firefox already patched in nightly. Should land in Firefox 21. // CORS "simple response headers" http://www.w3.org/TR/cors/ var value, simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]; if (!responseHeaders) { responseHeaders = ""; forEach(simpleHeaders, function (header) { var value = xhr.getResponseHeader(header); if (value) { responseHeaders += header + ": " + value + "\n"; } }); } // end of the workaround. completeRequest(callback, status || xhr.status, xhr.response || xhr.responseText, responseHeaders); } }; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { xhr.responseType = responseType; } xhr.send(post || ''); if (timeout > 0) { $browserDefer(function() { status = -1; xhr.abort(); }, timeout); } } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); } } /** * @ngdoc object * @name ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a the timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name ng.$timeout#cancel * @methodOf ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a the filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name ng.$filterProvider#register * @methodOf ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name ng.filter:filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(expected, actual)`: * The function will be given the object value and the predicate value to compare and * should return true if the item should be included in filtered result. * * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`. * this is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"å><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:search:strict"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); }); it('should use a equal comparison when comparator is true', function() { input('search.name').enter('Julie'); input('strict').check(); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression, comperator) { if (!isArray(array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; switch(typeof comperator) { case "function": break; case "boolean": if(comperator == true) { comperator = function(obj, text) { return angular.equals(obj, text); } break; } default: comperator = function(obj, text) { text = (''+text).toLowerCase(); return (''+obj).toLowerCase().indexOf(text) > -1 }; } var search = function(obj, text){ if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return comperator(obj, text); case "object": switch (typeof text) { case "object": return comperator(obj, text); break; default: for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { if (!expression[key]) return; var path = key predicates.push(function(value) { return search(value, expression[path]); }); })(); } else { (function() { if (!expression[key]) return; var path = key; predicates.push(function(value) { return search(getter(value,path), expression[path]); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name ng.filter:currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name ng.filter:number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(zone / 60, 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name ng.filter:date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); timeSetter.call(date, int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name ng.filter:json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name ng.filter:lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name ng.filter:uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </doc:source> <doc:scenario> it('should limit the number array to first three items', function() { expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); }); it('should update the output when -3 is entered', function() { input('numLimit').enter(-3); input('letterLimit').enter(-3); expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); }); it('should not exceed the maximum size of input array', function() { input('numLimit').enter(100); input('letterLimit').enter(100); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; } } /** * @ngdoc function * @name ng.filter:orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!isArray(array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name ng.directive:a * @restrict E * * @description * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="model.$save()">Save</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (msie <= 8) { // turn <a href ng-click="..">link</a> into a stylable link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href && !attr.name) { attr.$set('href', ''); } // add a comment node to anchors to workaround IE bug that causes element content to be reset // to new attribute content if attribute is updated with value containing @ and element also // contains value with @ // see issue #1949 element.append(document.createComment('IE fix')); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name ng.directive:ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngOpen * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as open. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngOpen` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </doc:source> <doc:scenario> it('should toggle open', function() { expect(element('#details').prop('open')).toBeFalsy(); input('open').check(); expect(element('#details').prop('open')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element DETAILS * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-href are interpolated forEach(['src', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { attr.$observe(normalized, function(value) { if (!value) return; attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie) element.prop(attrName, attr[attrName]); }); } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop }; /** * @ngdoc object * @name ng.directive:form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `required`, `url` or `email`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}, controls = []; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { controls.push(control); if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); arrayRemove(controls, control); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc function * @name ng.directive:form.FormController#$setPristine * @methodOf ng.directive:form.FormController * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function () { element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); form.$dirty = false; form.$pristine = true; forEach(controls, function(control) { control.$setPristine(); }); }; } /** * @ngdoc directive * @name ng.directive:ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name ng.directive:form * @restrict E * * @description * Directive that instantiates * {@link ng.directive:form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link ng.directive:ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var preventDefaultListener = function(event) { event.preventDefault ? event.preventDefault() : event.returnValue = false; // IE }; addEventListenerFn(formElement[0], 'submit', preventDefaultListener); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.bind('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name ng.directive:input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the * input. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\s*\w*\s*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should not be trimmed', function() { input('text').enter('untrimmed '); expect(binding('text')).toEqual('untrimmed '); expect(binding('myForm.input.$valid')).toEqual('true'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name ng.directive:input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name ng.directive:input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name ng.directive:input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = '[email protected]'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('[email protected]'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name ng.directive:input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name ng.directive:input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = element.val(); // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // e.g. <input ng-model="foo" ng-trim="false"> if (toBoolean(attr.ngTrim || 'T')) { value = trim(value); } if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name ng.directive:textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name ng.directive:input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name ng.directive:ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An bject hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS update, value formatting and parsing. It * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * <example module="customControl"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', []). directive('contenteditable', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html(ngModel.$viewValue || ''); }; // Listen for change events to enable binding element.bind('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { ngModel.$setViewValue(element.html()); } } }; }); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="scenario.js"> it('should data-bind and become invalid', function() { var contentEditable = element('[contenteditable]'); expect(contentEditable.text()).toEqual('Change me!'); input('userContent').enter(''); expect(contentEditable.text()).toEqual(''); expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); }); </file> * </example> * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', function($scope, $exceptionHandler, $attr, $element, $parse) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign; if (!ngModelSet) { throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + ' (' + startingTag($element) + ')'); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$render * @methodOf ng.directive:ngModel.NgModelController * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setValidity * @methodOf ng.directive:ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setPristine * @methodOf ng.directive:ngModel.NgModelController * * @description * Sets the control to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the control to its pristine * state (ng-pristine class). */ this.$setPristine = function () { this.$dirty = false; this.$pristine = true; $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setViewValue * @methodOf ng.directive:ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * * It internally calls all `formatters` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModelSet($scope, value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(function ngModelWatch() { var value = ngModelGet($scope); // if scope model value and ngModel value are out of sync if (ctrl.$modelValue !== value) { var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } } }); }]; /** * @ngdoc directive * @name ng.directive:ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link ng.directive:input.text text} * - {@link ng.directive:input.checkbox checkbox} * - {@link ng.directive:input.radio radio} * - {@link ng.directive:input.number number} * - {@link ng.directive:input.email email} * - {@link ng.directive:input.url url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * */ var ngModelDirective = function() { return { require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngList * * @description * Text input that converts between comma-separated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value, false); }); }; } } }; }; /** * @ngdoc directive * @name ng.directive:ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function ngBindWatchAction(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name ng.directive:ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name ng.directive:ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { var oldVal = undefined; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { var ngClass = scope.$eval(attr[name]); ngClassWatchAction(ngClass, ngClass); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { var mod = $index % 2; if (mod !== old$index % 2) { if (mod == selector) { addClass(scope.$eval(attr[name])); } else { removeClass(scope.$eval(attr[name])); } } }); } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && (newVal !== oldVal)) { removeClass(oldVal); } addClass(newVal); } oldVal = newVal; } function removeClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal); } function addClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } if (classVal) { element.addClass(isArray(classVal) ? classVal.join(' ') : classVal); } } }); } /** * @ngdoc directive * @name ng.directive:ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ng.directive:ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ng.directive:ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` works exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ng.directive:ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ng.directive:ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link ng.$route}` * service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'[email protected]'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'[email protected]'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('[email protected]'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('[email protected]'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name ng.directive:ngCsp * @priority 1000 * * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * This directive should be used on the root element of the application (typically the `<html>` * element or other element with the {@link ng.directive:ngApp ngApp} * directive). * * If enabled the performance of template expression evaluator will suffer slightly, so don't enable * this mode unless you need it. * * @element html */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name ng.directive:ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div ng-include src="template.url"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded * @eventOf ng.directive:ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', function($http, $templateCache, $anchorScroll, $compile) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element) { var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } element.html(''); }; scope.$watch(srcExp, function ngIncludeWatchAction(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); element.html(response); $compile(element.contents())(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); } else clearContent(); }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name ng.directive:ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ng.directive:ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + offset + endSymbol)); }); scope.$watch(function ngPluralizeWatch() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function ngPluralizeWatchAction(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ng.directive:ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <doc:example> <doc:source> <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng-repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng-repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ var ngRepeatDirective = ngDirective({ transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function(scope, iterStartElement, attr){ var expression = attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); scope.$watch(function ngRepeatWatch(scope){ var index, length, collection = scope.$eval(rhs), cursor = iterStartElement, // current position of the node // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), arrayLength, childScope, key, value, // key/value of iteration array, last; // last object information {scope, element, index} if (!isArray(collection)) { // if object, extract keys, sort them and use to determine order of iteration over obj props array = []; for(key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { array.push(key); } } array.sort(); } else { array = collection || []; } arrayLength = array.length; // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = array.length; index < length; index++) { key = (collection === array) ? index : array[index]; value = collection[key]; last = lastOrder.shift(value); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = scope.$new(); } childScope[valueIdent] = value; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (arrayLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; } }); /** * @ngdoc directive * @name ng.directive:ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngShow, function ngShowWatchAction(value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }); /** * @ngdoc directive * @name ng.directive:ngHide * * @description * The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngHide, function ngHideWatchAction(value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }); /** * @ngdoc directive * @name ng.directive:ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ctrl) { var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes, selectedElements, selectedScopes = []; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { for (var i= 0, ii=selectedScopes.length; i<ii; i++) { selectedScopes[i].$destroy(); selectedElements[i].remove(); } selectedElements = []; selectedScopes = []; if ((selectedTranscludes = ctrl.cases['!' + value] || ctrl.cases['?'])) { scope.$eval(attr.change); forEach(selectedTranscludes, function(selectedTransclude) { var selectedScope = scope.$new(); selectedScopes.push(selectedScope); selectedTransclude(selectedScope, function(caseElement) { selectedElements.push(caseElement); element.append(caseElement); }); }); } }); } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push(transclude); }; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push(transclude); }; } }); /** * @ngdoc directive * @name ng.directive:ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name ng.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * @scope * @example <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngView#$viewContentLoaded * @eventOf ng.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', function($http, $templateCache, $route, $anchorScroll, $compile, $controller) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var lastScope, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function clearContent() { element.html(''); destroyLastScope(); } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { element.html(template); destroyLastScope(); var link = $compile(element.contents()), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { locals.$scope = lastScope; controller = $controller(current.controller, locals); element.children().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name ng.directive:script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name ng.directive:select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; locals[valueName] = collection[key]; value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element, label; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(scope, locals)) != undefined; } else { selected = modelValue === valueFn(scope, locals); selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: label, selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (selectCtrl && selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} type Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') */ function browserTrigger(element, type, keys) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[lowercase(element.type)] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, iframe = _jQuery('#application iframe')[0], appWindow = iframe ? iframe.contentWindow : window, fakeProcessDefault = true, finalProcessDefault, angular = appWindow.angular || {}; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete angular['ff-684208-preventDefault']; return finalProcessDefault; } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.remove(); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); var $element = _jQuery(element); $element.injector = function() { return $injector; }; $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, $element); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerBegin', function() { self.emit('RunnerBegin'); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index){ result = result.add(selector.replace(NG, value), $document); }); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see ng.$location#url * browser().location().path() see ng.$location#path * browser().location().search() see ng.$location#search * browser().location().hash() see ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $document.injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $document.injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $document.injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $document.injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div') && msie != 9; chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || (supportInputEvent ? 'input' : 'change')); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } else { return done("option '" + value + "' not found"); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).mouseover() mouseover an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.dblclick = function() { return this.addFutureAction("element '" + this.label + "' dblclick", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('dblclick')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.mouseover = function() { return this.addFutureAction("element '" + this.label + "' mouseover", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mouseover'); done(); }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(step.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
app/js/components/ActionItem.js
blockstack/blockstack-portal
import PropTypes from 'prop-types' import React from 'react' const ActionItem = props => ( <div> {props.completed ? null : <div className="action-item"> <div>{props.action}</div> <div><small>{props.detail}</small></div> <a className="tooltip-link" href={props.destinationUrl}> › Go to {props.destinationName} </a> </div> } </div> ) ActionItem.propTypes = { action: PropTypes.string.isRequired, destinationUrl: PropTypes.string.isRequired, destinationName: PropTypes.string.isRequired, completed: PropTypes.bool.isRequired, detail: PropTypes.string.isRequired } export default ActionItem
docs/app/Examples/elements/Label/Types/LabelExamplePointing.js
shengnian/shengnian-ui-react
import React from 'react' import { Divider, Form, Label } from 'shengnian-ui-react' const LabelExamplePointing = () => ( <Form> <Form.Field> <input type='text' placeholder='First name' /> <Label pointing>Please enter a value</Label> </Form.Field> <Divider /> <Form.Field> <Label pointing='below'>Please enter a value</Label> <input type='text' placeholder='Last Name' /> </Form.Field> <Divider /> <Form.Field inline> <input type='text' placeholder='Username' /> <Label pointing='left'>That name is taken!</Label> </Form.Field> <Divider /> <Form.Field inline> <Label pointing='right'>Your password must be 6 characters or more</Label> <input type='password' placeholder='Password' /> </Form.Field> </Form> ) export default LabelExamplePointing
src/app/components/layout/AspectRatio.js
meedan/check-web
import React from 'react'; import { FormattedMessage, FormattedHTMLMessage, injectIntl, defineMessages } from 'react-intl'; import PropTypes from 'prop-types'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import FullscreenIcon from '@material-ui/icons/Fullscreen'; import VisibilityOffIcon from '@material-ui/icons/VisibilityOff'; import { opaqueBlack87, black32, checkBlue, opaqueBlack38, units, white } from '../../styles/js/shared.js'; const useStyles = makeStyles(theme => ({ container: { width: '100%', height: 0, paddingBottom: '56.25%', position: 'relative', backgroundColor: opaqueBlack38, }, innerWrapper: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, '& img': { width: '100%', height: '100%', objectFit: 'contain', }, '& div.aspect-ratio__overlay': { width: '100%', height: '100%', position: 'absolute', top: 0, zIndex: 10, }, }, sensitiveScreen: props => ({ pointerEvents: 'none', position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, width: '100%', height: '100%', backgroundColor: props.contentWarning ? opaqueBlack87 : 'transparent', zIndex: 100, color: 'white', }), icon: props => ({ fontSize: '40px', visibility: props.contentWarning ? 'visible' : 'hidden', }), button: props => ({ pointerEvents: 'auto', bottom: 0, color: 'white', minWidth: theme.spacing(22), backgroundColor: props.contentWarning ? 'black' : checkBlue, border: '2px solid white', '& :hover': { backgroundColor: 'unset', }, }), })); const messages = defineMessages({ adult: { id: 'contentScreen.adult', defaultMessage: 'Adult', description: 'Content warning type: Adult', }, medical: { id: 'contentScreen.medical', defaultMessage: 'Medical', description: 'Content warning type: Medical', }, violence: { id: 'contentScreen.violence', defaultMessage: 'Violence', description: 'Content warning type: Violence', }, }); const AspectRatioComponent = ({ contentWarning, warningCreator, warningCategory, onClickExpand, children, intl, }) => { const [maskContent, setMaskContent] = React.useState(contentWarning); const classes = useStyles({ contentWarning: contentWarning && maskContent }); return ( <div className={classes.container}> <div className={classes.innerWrapper}> { onClickExpand ? <IconButton onClick={onClickExpand} style={{ color: white, backgroundColor: black32, position: 'absolute', right: '0', top: '0', margin: units(2), zIndex: contentWarning && maskContent ? 15 : 150, }} > <FullscreenIcon style={{ width: units(4), height: units(4) }} /> </IconButton> : null } { !maskContent ? children : null } { contentWarning ? <div className={classes.sensitiveScreen}> <Box display="flex" flexDirection="column" justifyContent="space-between" height="100%" alignItems="center" pt={8} pb={4} > <VisibilityOffIcon className={classes.icon} /> <div style={{ visibility: contentWarning && maskContent ? 'visible' : 'hidden' }}> <Typography variant="body1"> <FormattedHTMLMessage id="contentScreen.warning" defaultMessage="<strong>{user_name}</strong> has detected this content as <strong>{warning_category}</strong>" description="Content warning displayed over sensitive content" values={{ user_name: warningCreator, warning_category: ( (messages[warningCategory] && intl.formatMessage(messages[warningCategory])) || warningCategory ), }} /> </Typography> </div> { contentWarning ? ( <Button className={classes.button} onClick={() => setMaskContent(!maskContent)} color="primary" variant="contained" > { maskContent ? ( <FormattedMessage id="contentScreen.viewContentButton" defaultMessage="Temporarily view content" description="Button to enable view of sensitive content" /> ) : ( <FormattedMessage id="contentScreen.hideContentButton" defaultMessage="Hide content" description="Button to disable view of sensitive content" /> )} </Button> ) : null } </Box> </div> : null } </div> </div> ); }; AspectRatioComponent.propTypes = { children: PropTypes.node.isRequired, }; export default injectIntl(AspectRatioComponent);
examples/todomvc/test/components/Footer.spec.js
ellbee/redux
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Footer from '../../components/Footer' import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters' function setup(propOverrides) { const props = Object.assign({ completedCount: 0, activeCount: 0, filter: SHOW_ALL, onClearCompleted: expect.createSpy(), onShow: expect.createSpy() }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render(<Footer {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output } } function getTextContent(elem) { const children = Array.isArray(elem.props.children) ? elem.props.children : [ elem.props.children ] return children.reduce(function concatText(out, child) { // Children are either elements or text strings return out + (child.props ? getTextContent(child) : child) }, '') } describe('components', () => { describe('Footer', () => { it('should render container', () => { const { output } = setup() expect(output.type).toBe('footer') expect(output.props.className).toBe('footer') }) it('should display active count when 0', () => { const { output } = setup({ activeCount: 0 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('No items left') }) it('should display active count when above 0', () => { const { output } = setup({ activeCount: 1 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('1 item left') }) it('should render filters', () => { const { output } = setup() const [ , filters ] = output.props.children expect(filters.type).toBe('ul') expect(filters.props.className).toBe('filters') expect(filters.props.children.length).toBe(3) filters.props.children.forEach(function checkFilter(filter, i) { expect(filter.type).toBe('li') const a = filter.props.children expect(a.props.className).toBe(i === 0 ? 'selected' : '') expect(a.props.children).toBe({ 0: 'All', 1: 'Active', 2: 'Completed' }[i]) }) }) it('should call onShow when a filter is clicked', () => { const { output, props } = setup() const [ , filters ] = output.props.children const filterLink = filters.props.children[1].props.children filterLink.props.onClick({}) expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE) }) it('shouldnt show clear button when no completed todos', () => { const { output } = setup({ completedCount: 0 }) const [ , , clear ] = output.props.children expect(clear).toBe(undefined) }) it('should render clear button when completed todos', () => { const { output } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children expect(clear.type).toBe('button') expect(clear.props.children).toBe('Clear completed') }) it('should call onClearCompleted on clear button click', () => { const { output, props } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children clear.props.onClick({}) expect(props.onClearCompleted).toHaveBeenCalled() }) }) })
src/common/Popover/Popover.js
Syncano/syncano-dashboard
import React from 'react'; import { Popover } from 'material-ui'; export default React.createClass({ displayName: 'Popover', getDefaultProps() { return { anchorOrigin: { horizontal: 'left', vertical: 'bottom' }, targetOrigin: { horizontal: 'right', vertical: 'top' } }; }, getInitialState() { return { open: false }; }, hide() { this.setState({ open: false }); }, toggle(event) { this.setState({ open: !this.state.open, anchorElement: event.currentTarget }); }, render() { const { open, anchorElement } = this.state; const { children, ...other } = this.props; return ( <Popover {...other} onRequestClose={this.hide} open={open} anchorEl={anchorElement} > {children} </Popover> ); } });
spa/pages/create-layer.js
chadwilcomb/routemap2
import React from 'react'; import app from 'ampersand-app' import ampersandMixin from 'ampersand-react-mixin'; import geojsonValidate from 'geojson-validation'; import MessagePage from './message'; export default React.createClass({ mixins: [ampersandMixin], displayName: 'LayerCreatePage', onSubmitForm (event) { event.preventDefault(); const _this = this; const {layer} = this.props; geojsonValidate.valid(this.state.features, function (valid, errors) { if (!valid) { const errMsg = errors.map((error) => { return error.mesage + ' '; }); _this.setState({ error: 'Invalid GeoJSON: ' + errMsg }); } else { app.router.renderPage(<MessagePage title='Saving layer details...' />); layer.save(_this.state, { success: function () { app.router.redirectTo('/layers'); }, error: function (model, response) { console.log(response); app.router.renderPage(<MessagePage title='Error saving layer.' />); }, }); } }); }, onPropChange (event) { const {name, value, type} = event.target; let state = {}; if (value && name === 'features') { try { state[name] = JSON.parse(value); this.setState({ error: ''}); } catch (err) { this.setState({ error: 'Invalid GeoJSON: ' + err.message }); } } else { state[name] = value; } this.setState(state); }, getInitialState () { return { title: '', description: '', features: '', error: '' }; }, render () { const {title,description,features,error} = this.state; return ( <div> <h1>Add a layer</h1> <form name='createLayerForm' onSubmit={this.onSubmitForm}> <fieldset> <legend>Layer Info</legend> <div className={error ? 'message message-error' : 'hidden'}>{error}</div> <div className='form-element'> <label htmlFor='title'>Title</label> <input onChange={this.onPropChange} id='title' name='title' type='text' placeholder='Title' className='form-input' required/> </div> <div className='form-element'> <label htmlFor='description'>Description</label> <input onChange={this.onPropChange} id='description' name='description' type='text' placeholder='Description' className='form-input' required/> </div> <div className='form-element'> <label htmlFor='features'>Features</label> <textarea rows='8' onChange={this.onPropChange} id='features' name='features' type='text' placeholder='Copy/Paste GeoJSON here' className='form-input' required/> </div> <button type='submit' className='button button-primary'>Add!</button> </fieldset> </form> </div> ) } })
ajax/libs/react-virtualized/7.24.0/react-virtualized.js
sashberd/cdnjs
!function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : "function" == typeof define && define.amd ? define([ "React", "React.addons.shallowCompare", "ReactDOM" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : root.ReactVirtualized = factory(root.React, root["React.addons.shallowCompare"], root.ReactDOM); }(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_10__) { /******/ return function(modules) { /******/ /******/ // 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: !1 }; /******/ /******/ // Return the exports of the module /******/ /******/ /******/ // Execute the module function /******/ /******/ /******/ // Flag the module as loaded /******/ return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), module.loaded = !0, module.exports; } // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // Load entry module and return exports /******/ /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ /******/ /******/ // expose the module cache /******/ /******/ /******/ // __webpack_public_path__ /******/ return __webpack_require__.m = modules, __webpack_require__.c = installedModules, __webpack_require__.p = "", __webpack_require__(0); }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _ArrowKeyStepper = __webpack_require__(1); Object.defineProperty(exports, "ArrowKeyStepper", { enumerable: !0, get: function() { return _ArrowKeyStepper.ArrowKeyStepper; } }); var _AutoSizer = __webpack_require__(5); Object.defineProperty(exports, "AutoSizer", { enumerable: !0, get: function() { return _AutoSizer.AutoSizer; } }); var _CellMeasurer = __webpack_require__(8); Object.defineProperty(exports, "CellMeasurer", { enumerable: !0, get: function() { return _CellMeasurer.CellMeasurer; } }), Object.defineProperty(exports, "defaultCellMeasurerCellSizeCache", { enumerable: !0, get: function() { return _CellMeasurer.defaultCellSizeCache; } }), Object.defineProperty(exports, "uniformSizeCellMeasurerCellSizeCache", { enumerable: !0, get: function() { return _CellMeasurer.defaultCellSizeCache; } }); var _Collection = __webpack_require__(12); Object.defineProperty(exports, "Collection", { enumerable: !0, get: function() { return _Collection.Collection; } }); var _ColumnSizer = __webpack_require__(26); Object.defineProperty(exports, "ColumnSizer", { enumerable: !0, get: function() { return _ColumnSizer.ColumnSizer; } }); var _FlexTable = __webpack_require__(36); Object.defineProperty(exports, "defaultFlexTableCellDataGetter", { enumerable: !0, get: function() { return _FlexTable.defaultCellDataGetter; } }), Object.defineProperty(exports, "defaultFlexTableCellRenderer", { enumerable: !0, get: function() { return _FlexTable.defaultCellRenderer; } }), Object.defineProperty(exports, "defaultFlexTableHeaderRenderer", { enumerable: !0, get: function() { return _FlexTable.defaultHeaderRenderer; } }), Object.defineProperty(exports, "defaultFlexTableRowRenderer", { enumerable: !0, get: function() { return _FlexTable.defaultRowRenderer; } }), Object.defineProperty(exports, "FlexTable", { enumerable: !0, get: function() { return _FlexTable.FlexTable; } }), Object.defineProperty(exports, "FlexColumn", { enumerable: !0, get: function() { return _FlexTable.FlexColumn; } }), Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable.SortIndicator; } }); var _Grid = __webpack_require__(28); Object.defineProperty(exports, "defaultCellRangeRenderer", { enumerable: !0, get: function() { return _Grid.defaultCellRangeRenderer; } }), Object.defineProperty(exports, "Grid", { enumerable: !0, get: function() { return _Grid.Grid; } }); var _InfiniteLoader = __webpack_require__(45); Object.defineProperty(exports, "InfiniteLoader", { enumerable: !0, get: function() { return _InfiniteLoader.InfiniteLoader; } }); var _ScrollSync = __webpack_require__(47); Object.defineProperty(exports, "ScrollSync", { enumerable: !0, get: function() { return _ScrollSync.ScrollSync; } }); var _VirtualScroll = __webpack_require__(49); Object.defineProperty(exports, "VirtualScroll", { enumerable: !0, get: function() { return _VirtualScroll.VirtualScroll; } }); var _WindowScroller = __webpack_require__(51); Object.defineProperty(exports, "WindowScroller", { enumerable: !0, get: function() { return _WindowScroller.WindowScroller; } }); }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ArrowKeyStepper = exports["default"] = void 0; var _ArrowKeyStepper2 = __webpack_require__(2), _ArrowKeyStepper3 = _interopRequireDefault(_ArrowKeyStepper2); exports["default"] = _ArrowKeyStepper3["default"], exports.ArrowKeyStepper = _ArrowKeyStepper3["default"]; }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ArrowKeyStepper = function(_Component) { function ArrowKeyStepper(props, context) { _classCallCheck(this, ArrowKeyStepper); var _this = _possibleConstructorReturn(this, (ArrowKeyStepper.__proto__ || Object.getPrototypeOf(ArrowKeyStepper)).call(this, props, context)); return _this.state = { scrollToColumn: 0, scrollToRow: 0 }, _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0, _this._rowStopIndex = 0, _this._onKeyDown = _this._onKeyDown.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(ArrowKeyStepper, _Component), _createClass(ArrowKeyStepper, [ { key: "render", value: function() { var _props = this.props, className = _props.className, children = _props.children, _state = this.state, scrollToColumn = _state.scrollToColumn, scrollToRow = _state.scrollToRow; return _react2["default"].createElement("div", { className: className, onKeyDown: this._onKeyDown }, children({ onSectionRendered: this._onSectionRendered, scrollToColumn: scrollToColumn, scrollToRow: scrollToRow })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onKeyDown", value: function(event) { var _props2 = this.props, columnCount = _props2.columnCount, rowCount = _props2.rowCount; switch (event.key) { case "ArrowDown": event.preventDefault(), this.setState({ scrollToRow: Math.min(this._rowStopIndex + 1, rowCount - 1) }); break; case "ArrowLeft": event.preventDefault(), this.setState({ scrollToColumn: Math.max(this._columnStartIndex - 1, 0) }); break; case "ArrowRight": event.preventDefault(), this.setState({ scrollToColumn: Math.min(this._columnStopIndex + 1, columnCount - 1) }); break; case "ArrowUp": event.preventDefault(), this.setState({ scrollToRow: Math.max(this._rowStartIndex - 1, 0) }); } } }, { key: "_onSectionRendered", value: function(_ref) { var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex; this._columnStartIndex = columnStartIndex, this._columnStopIndex = columnStopIndex, this._rowStartIndex = rowStartIndex, this._rowStopIndex = rowStopIndex; } } ]), ArrowKeyStepper; }(_react.Component); ArrowKeyStepper.propTypes = { children: _react.PropTypes.func.isRequired, className: _react.PropTypes.string, columnCount: _react.PropTypes.number.isRequired, rowCount: _react.PropTypes.number.isRequired }, exports["default"] = ArrowKeyStepper; }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; }, /* 4 */ /***/ function(module, exports) { module.exports = React.addons.shallowCompare; }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.AutoSizer = exports["default"] = void 0; var _AutoSizer2 = __webpack_require__(6), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); exports["default"] = _AutoSizer3["default"], exports.AutoSizer = _AutoSizer3["default"]; }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), AutoSizer = function(_Component) { function AutoSizer(props) { _classCallCheck(this, AutoSizer); var _this = _possibleConstructorReturn(this, (AutoSizer.__proto__ || Object.getPrototypeOf(AutoSizer)).call(this, props)); return _this.state = { height: 0, width: 0 }, _this._onResize = _this._onResize.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._setRef = _this._setRef.bind(_this), _this; } return _inherits(AutoSizer, _Component), _createClass(AutoSizer, [ { key: "componentDidMount", value: function() { this._detectElementResize = __webpack_require__(7), this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); } }, { key: "componentWillUnmount", value: function() { this._detectElementResize && this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); } }, { key: "render", value: function() { var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = { overflow: "visible" }; return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0), _react2["default"].createElement("div", { ref: this._setRef, onScroll: this._onScroll, style: outerStyle }, children({ height: height, width: width })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onResize", value: function() { var onResize = this.props.onResize, boundingRect = this._parentNode.getBoundingClientRect(), height = boundingRect.height || 0, width = boundingRect.width || 0, style = getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10) || 0, paddingRight = parseInt(style.paddingRight, 10) || 0, paddingTop = parseInt(style.paddingTop, 10) || 0, paddingBottom = parseInt(style.paddingBottom, 10) || 0; this.setState({ height: height - paddingTop - paddingBottom, width: width - paddingLeft - paddingRight }), onResize({ height: height, width: width }); } }, { key: "_onScroll", value: function(event) { event.stopPropagation(); } }, { key: "_setRef", value: function(autoSizer) { this._parentNode = autoSizer && autoSizer.parentNode; } } ]), AutoSizer; }(_react.Component); AutoSizer.propTypes = { children: _react.PropTypes.func.isRequired, disableHeight: _react.PropTypes.bool, disableWidth: _react.PropTypes.bool, onResize: _react.PropTypes.func.isRequired }, AutoSizer.defaultProps = { onResize: function() {} }, exports["default"] = AutoSizer; }, /* 7 */ /***/ function(module, exports) { "use strict"; var _window; _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0; var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; if (!attachEvent) { var requestFrame = function() { var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { return _window.setTimeout(fn, 20); }; return function(fn) { return raf(fn); }; }(), cancelFrame = function() { var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; return function(id) { return cancel(id); }; }(), resetTriggers = function(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; }, checkTriggers = function(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; }, scrollListener = function(e) { var element = this; resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, element.__resizeListeners__.forEach(function(fn) { fn.call(element, e); })); }); }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement"); if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i], animation = !0; break; } var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; } var createStyles = function() { if (!stylesCreated) { var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style"); style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), head.appendChild(style), stylesCreated = !0; } }, addResizeListener = function(element, fn) { attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"), createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers", element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) { e.animationName == animationName && resetTriggers(element); })), element.__resizeListeners__.push(fn)); }, removeResizeListener = function(element, fn) { attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener, !0), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); }; module.exports = { addResizeListener: addResizeListener, removeResizeListener: removeResizeListener }; }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.defaultCellSizeCache = exports.CellMeasurer = exports["default"] = void 0; var _CellMeasurer2 = __webpack_require__(9), _CellMeasurer3 = _interopRequireDefault(_CellMeasurer2), _defaultCellSizeCache2 = __webpack_require__(11), _defaultCellSizeCache3 = _interopRequireDefault(_defaultCellSizeCache2); exports["default"] = _CellMeasurer3["default"], exports.CellMeasurer = _CellMeasurer3["default"], exports.defaultCellSizeCache = _defaultCellSizeCache3["default"]; }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _defaultCellSizeCache = __webpack_require__(11), _defaultCellSizeCache2 = _interopRequireDefault(_defaultCellSizeCache), CellMeasurer = function(_Component) { function CellMeasurer(props, state) { _classCallCheck(this, CellMeasurer); var _this = _possibleConstructorReturn(this, (CellMeasurer.__proto__ || Object.getPrototypeOf(CellMeasurer)).call(this, props, state)); return _this._cellSizeCache = props.cellSizeCache || new _defaultCellSizeCache2["default"](), _this.getColumnWidth = _this.getColumnWidth.bind(_this), _this.getRowHeight = _this.getRowHeight.bind(_this), _this.resetMeasurements = _this.resetMeasurements.bind(_this), _this.resetMeasurementForColumn = _this.resetMeasurementForColumn.bind(_this), _this.resetMeasurementForRow = _this.resetMeasurementForRow.bind(_this), _this; } return _inherits(CellMeasurer, _Component), _createClass(CellMeasurer, [ { key: "getColumnWidth", value: function(_ref) { var index = _ref.index; if (this._cellSizeCache.hasColumnWidth(index)) return this._cellSizeCache.getColumnWidth(index); for (var rowCount = this.props.rowCount, maxWidth = 0, rowIndex = 0; rowIndex < rowCount; rowIndex++) { var _measureCell2 = this._measureCell({ clientWidth: !0, columnIndex: index, rowIndex: rowIndex }), width = _measureCell2.width; maxWidth = Math.max(maxWidth, width); } return this._cellSizeCache.setColumnWidth(index, maxWidth), maxWidth; } }, { key: "getRowHeight", value: function(_ref2) { var index = _ref2.index; if (this._cellSizeCache.hasRowHeight(index)) return this._cellSizeCache.getRowHeight(index); for (var columnCount = this.props.columnCount, maxHeight = 0, columnIndex = 0; columnIndex < columnCount; columnIndex++) { var _measureCell3 = this._measureCell({ clientHeight: !0, columnIndex: columnIndex, rowIndex: index }), height = _measureCell3.height; maxHeight = Math.max(maxHeight, height); } return this._cellSizeCache.setRowHeight(index, maxHeight), maxHeight; } }, { key: "resetMeasurementForColumn", value: function(columnIndex) { this._cellSizeCache.clearColumnWidth(columnIndex); } }, { key: "resetMeasurementForRow", value: function(rowIndex) { this._cellSizeCache.clearRowHeight(rowIndex); } }, { key: "resetMeasurements", value: function() { this._cellSizeCache.clearAllColumnWidths(), this._cellSizeCache.clearAllRowHeights(); } }, { key: "componentDidMount", value: function() { this._renderAndMount(); } }, { key: "componentWillReceiveProps", value: function(nextProps) { var cellSizeCache = this.props.cellSizeCache; cellSizeCache !== nextProps.cellSizeCache && (this._cellSizeCache = nextProps.cellSizeCache), this._updateDivDimensions(nextProps); } }, { key: "componentWillUnmount", value: function() { this._unmountContainer(); } }, { key: "render", value: function() { var children = this.props.children; return children({ getColumnWidth: this.getColumnWidth, getRowHeight: this.getRowHeight, resetMeasurements: this.resetMeasurements, resetMeasurementForColumn: this.resetMeasurementForColumn, resetMeasurementForRow: this.resetMeasurementForRow }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_getContainerNode", value: function(props) { var container = props.container; return container ? _reactDom2["default"].findDOMNode("function" == typeof container ? container() : container) : document.body; } }, { key: "_measureCell", value: function(_ref3) { var _ref3$clientHeight = _ref3.clientHeight, clientHeight = void 0 !== _ref3$clientHeight && _ref3$clientHeight, _ref3$clientWidth = _ref3.clientWidth, clientWidth = void 0 === _ref3$clientWidth || _ref3$clientWidth, columnIndex = _ref3.columnIndex, rowIndex = _ref3.rowIndex, cellRenderer = this.props.cellRenderer, rendered = cellRenderer({ columnIndex: columnIndex, rowIndex: rowIndex }); this._renderAndMount(), _reactDom2["default"].unstable_renderSubtreeIntoContainer(this, rendered, this._div); var measurements = { height: clientHeight && this._div.clientHeight, width: clientWidth && this._div.clientWidth }; return _reactDom2["default"].unmountComponentAtNode(this._div), measurements; } }, { key: "_renderAndMount", value: function() { this._div || (this._div = document.createElement("div"), this._div.style.display = "inline-block", this._div.style.position = "absolute", this._div.style.visibility = "hidden", this._div.style.zIndex = -1, this._updateDivDimensions(this.props), this._containerNode = this._getContainerNode(this.props), this._containerNode.appendChild(this._div)); } }, { key: "_unmountContainer", value: function() { this._div && (this._containerNode.removeChild(this._div), this._div = null), this._containerNode = null; } }, { key: "_updateDivDimensions", value: function(props) { var height = props.height, width = props.width; height && height !== this._divHeight && (this._divHeight = height, this._div.style.height = height + "px"), width && width !== this._divWidth && (this._divWidth = width, this._div.style.width = width + "px"); } } ]), CellMeasurer; }(_react.Component); CellMeasurer.propTypes = { cellRenderer: _react.PropTypes.func.isRequired, cellSizeCache: _react.PropTypes.object, children: _react.PropTypes.func.isRequired, columnCount: _react.PropTypes.number.isRequired, container: _react2["default"].PropTypes.oneOfType([ _react2["default"].PropTypes.func, _react2["default"].PropTypes.node ]), height: _react.PropTypes.number, rowCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number }, exports["default"] = CellMeasurer; }, /* 10 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_10__; }, /* 11 */ /***/ function(module, exports) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), CellSizeCache = function() { function CellSizeCache() { var _ref = arguments.length <= 0 || void 0 === arguments[0] ? {} : arguments[0], _ref$uniformRowHeight = _ref.uniformRowHeight, uniformRowHeight = void 0 !== _ref$uniformRowHeight && _ref$uniformRowHeight, _ref$uniformColumnWid = _ref.uniformColumnWidth, uniformColumnWidth = void 0 !== _ref$uniformColumnWid && _ref$uniformColumnWid; _classCallCheck(this, CellSizeCache), this._uniformRowHeight = uniformRowHeight, this._uniformColumnWidth = uniformColumnWidth, this._cachedColumnWidths = {}, this._cachedRowHeights = {}; } return _createClass(CellSizeCache, [ { key: "clearAllColumnWidths", value: function() { this._cachedColumnWidth = void 0, this._cachedColumnWidths = {}; } }, { key: "clearAllRowHeights", value: function() { this._cachedRowHeight = void 0, this._cachedRowHeights = {}; } }, { key: "clearColumnWidth", value: function(index) { this._cachedColumnWidth = void 0, delete this._cachedColumnWidths[index]; } }, { key: "clearRowHeight", value: function(index) { this._cachedRowHeight = void 0, delete this._cachedRowHeights[index]; } }, { key: "getColumnWidth", value: function(index) { return this._uniformColumnWidth ? this._cachedColumnWidth : this._cachedColumnWidths[index]; } }, { key: "getRowHeight", value: function(index) { return this._uniformRowHeight ? this._cachedRowHeight : this._cachedRowHeights[index]; } }, { key: "hasColumnWidth", value: function(index) { return this._uniformColumnWidth ? !!this._cachedColumnWidth : !!this._cachedColumnWidths[index]; } }, { key: "hasRowHeight", value: function(index) { return this._uniformRowHeight ? !!this._cachedRowHeight : !!this._cachedRowHeights[index]; } }, { key: "setColumnWidth", value: function(index, width) { this._cachedColumnWidth = width, this._cachedColumnWidths[index] = width; } }, { key: "setRowHeight", value: function(index, height) { this._cachedRowHeight = height, this._cachedRowHeights[index] = height; } } ]), CellSizeCache; }(); exports["default"] = CellSizeCache; }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.Collection = exports["default"] = void 0; var _Collection2 = __webpack_require__(13), _Collection3 = _interopRequireDefault(_Collection2); exports["default"] = _Collection3["default"], exports.Collection = _Collection3["default"]; }, /* 13 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function defaultCellGroupRenderer(_ref5) { var cellCache = _ref5.cellCache, cellRenderer = _ref5.cellRenderer, cellSizeAndPositionGetter = _ref5.cellSizeAndPositionGetter, indices = _ref5.indices, isScrolling = _ref5.isScrolling; return indices.map(function(index) { var cellMetadata = cellSizeAndPositionGetter({ index: index }), renderedCell = void 0; return isScrolling ? (index in cellCache || (cellCache[index] = cellRenderer({ index: index, isScrolling: isScrolling })), renderedCell = cellCache[index]) : renderedCell = cellRenderer({ index: index, isScrolling: isScrolling }), null == renderedCell || renderedCell === !1 ? null : _react2["default"].createElement("div", { className: "Collection__cell", key: index, style: { height: cellMetadata.height, left: cellMetadata.x, top: cellMetadata.y, width: cellMetadata.width } }, renderedCell); }).filter(function(renderedCell) { return !!renderedCell; }); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _CollectionView = __webpack_require__(14), _CollectionView2 = _interopRequireDefault(_CollectionView), _calculateSizeAndPositionData2 = __webpack_require__(22), _calculateSizeAndPositionData3 = _interopRequireDefault(_calculateSizeAndPositionData2), _getUpdatedOffsetForIndex = __webpack_require__(25), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), Collection = function(_Component) { function Collection(props, context) { _classCallCheck(this, Collection); var _this = _possibleConstructorReturn(this, (Collection.__proto__ || Object.getPrototypeOf(Collection)).call(this, props, context)); return _this._cellMetadata = [], _this._lastRenderedCellIndices = [], _this._cellCache = [], _this._isScrollingChange = _this._isScrollingChange.bind(_this), _this; } return _inherits(Collection, _Component), _createClass(Collection, [ { key: "recomputeCellSizesAndPositions", value: function() { this._cellCache = [], this._collectionView.recomputeCellSizesAndPositions(); } }, { key: "render", value: function() { var _this2 = this, props = _objectWithoutProperties(this.props, []); return _react2["default"].createElement(_CollectionView2["default"], _extends({ cellLayoutManager: this, isScrollingChange: this._isScrollingChange, ref: function(_ref) { _this2._collectionView = _ref; } }, props)); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "calculateSizeAndPositionData", value: function() { var _props = this.props, cellCount = _props.cellCount, cellSizeAndPositionGetter = _props.cellSizeAndPositionGetter, sectionSize = _props.sectionSize, data = (0, _calculateSizeAndPositionData3["default"])({ cellCount: cellCount, cellSizeAndPositionGetter: cellSizeAndPositionGetter, sectionSize: sectionSize }); this._cellMetadata = data.cellMetadata, this._sectionManager = data.sectionManager, this._height = data.height, this._width = data.width; } }, { key: "getLastRenderedIndices", value: function() { return this._lastRenderedCellIndices; } }, { key: "getScrollPositionForCell", value: function(_ref2) { var align = _ref2.align, cellIndex = _ref2.cellIndex, height = _ref2.height, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, width = _ref2.width, cellCount = this.props.cellCount; if (cellIndex >= 0 && cellIndex < cellCount) { var cellMetadata = this._cellMetadata[cellIndex]; scrollLeft = (0, _getUpdatedOffsetForIndex2["default"])({ align: align, cellOffset: cellMetadata.x, cellSize: cellMetadata.width, containerSize: width, currentOffset: scrollLeft, targetIndex: cellIndex }), scrollTop = (0, _getUpdatedOffsetForIndex2["default"])({ align: align, cellOffset: cellMetadata.y, cellSize: cellMetadata.height, containerSize: height, currentOffset: scrollTop, targetIndex: cellIndex }); } return { scrollLeft: scrollLeft, scrollTop: scrollTop }; } }, { key: "getTotalSize", value: function() { return { height: this._height, width: this._width }; } }, { key: "cellRenderers", value: function(_ref3) { var _this3 = this, height = _ref3.height, isScrolling = _ref3.isScrolling, width = _ref3.width, x = _ref3.x, y = _ref3.y, _props2 = this.props, cellGroupRenderer = _props2.cellGroupRenderer, cellRenderer = _props2.cellRenderer; return this._lastRenderedCellIndices = this._sectionManager.getCellIndices({ height: height, width: width, x: x, y: y }), cellGroupRenderer({ cellCache: this._cellCache, cellRenderer: cellRenderer, cellSizeAndPositionGetter: function(_ref4) { var index = _ref4.index; return _this3._sectionManager.getCellMetadata({ index: index }); }, indices: this._lastRenderedCellIndices, isScrolling: isScrolling }); } }, { key: "_isScrollingChange", value: function(isScrolling) { isScrolling || (this._cellCache = []); } } ]), Collection; }(_react.Component); Collection.propTypes = { "aria-label": _react.PropTypes.string, cellCount: _react.PropTypes.number.isRequired, cellGroupRenderer: _react.PropTypes.func.isRequired, cellRenderer: _react.PropTypes.func.isRequired, cellSizeAndPositionGetter: _react.PropTypes.func.isRequired, sectionSize: _react.PropTypes.number }, Collection.defaultProps = { "aria-label": "grid", cellGroupRenderer: defaultCellGroupRenderer }, exports["default"] = Collection; }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _createCallbackMemoizer = __webpack_require__(16), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _scrollbarSize = __webpack_require__(17), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(19), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, CollectionView = function(_Component) { function CollectionView(props, context) { _classCallCheck(this, CollectionView); var _this = _possibleConstructorReturn(this, (CollectionView.__proto__ || Object.getPrototypeOf(CollectionView)).call(this, props, context)); return _this.state = { calculateSizeAndPositionDataOnNextUpdate: !1, isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, _this._onSectionRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onScrollMemoizer = (0, _createCallbackMemoizer2["default"])(!1), _this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this), _this; } return _inherits(CollectionView, _Component), _createClass(CollectionView, [ { key: "recomputeCellSizesAndPositions", value: function() { this.setState({ calculateSizeAndPositionDataOnNextUpdate: !0 }); } }, { key: "componentDidMount", value: function() { var _props = this.props, cellLayoutManager = _props.cellLayoutManager, scrollLeft = _props.scrollLeft, scrollToCell = _props.scrollToCell, scrollTop = _props.scrollTop; this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(), this._scrollbarSizeMeasured = !0, this.setState({})), scrollToCell >= 0 ? this._updateScrollPositionForScrollToCell() : (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), this._invokeOnSectionRenderedHelper(); var _cellLayoutManager$ge = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge.height, totalWidth = _cellLayoutManager$ge.width; this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft || 0, scrollTop: scrollTop || 0, totalHeight: totalHeight, totalWidth: totalWidth }); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props2 = this.props, height = _props2.height, scrollToCell = _props2.scrollToCell, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollToAlignment = _state.scrollToAlignment, scrollTop = _state.scrollTop; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft && (this._scrollingContainer.scrollLeft = scrollLeft), scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop && (this._scrollingContainer.scrollTop = scrollTop)), height === prevProps.height && scrollToAlignment === prevProps.scrollToAlignment && scrollToCell === prevProps.scrollToCell && width === prevProps.width || this._updateScrollPositionForScrollToCell(), this._invokeOnSectionRenderedHelper(); } }, { key: "componentWillMount", value: function() { var cellLayoutManager = this.props.cellLayoutManager; cellLayoutManager.calculateSizeAndPositionData(), this._scrollbarSize = (0, _scrollbarSize2["default"])(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0; } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 !== nextProps.cellCount || 0 === nextState.scrollLeft && 0 === nextState.scrollTop ? nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop }) : this._setScrollPosition({ scrollLeft: 0, scrollTop: 0 }), (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || nextState.calculateSizeAndPositionDataOnNextUpdate) && nextProps.cellLayoutManager.calculateSizeAndPositionData(), nextState.calculateSizeAndPositionDataOnNextUpdate && this.setState({ calculateSizeAndPositionDataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, cellCount = _props3.cellCount, cellLayoutManager = _props3.cellLayoutManager, className = _props3.className, height = _props3.height, horizontalOverscanSize = _props3.horizontalOverscanSize, noContentRenderer = _props3.noContentRenderer, style = _props3.style, verticalOverscanSize = _props3.verticalOverscanSize, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge2.height, totalWidth = _cellLayoutManager$ge2.width, left = Math.max(0, scrollLeft - horizontalOverscanSize), top = Math.max(0, scrollTop - verticalOverscanSize), right = Math.min(totalWidth, scrollLeft + width + horizontalOverscanSize), bottom = Math.min(totalHeight, scrollTop + height + verticalOverscanSize), childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.cellRenderers({ height: bottom - top, isScrolling: isScrolling, width: right - left, x: left, y: top }) : [], collectionStyle = { height: autoHeight ? "auto" : height, width: width }, verticalScrollBarSize = totalHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalWidth > width ? this._scrollbarSize : 0; return totalWidth + verticalScrollBarSize <= width && (collectionStyle.overflowX = "hidden"), totalHeight + horizontalScrollBarSize <= height && (collectionStyle.overflowY = "hidden"), _react2["default"].createElement("div", { ref: function(_ref) { _this2._scrollingContainer = _ref; }, "aria-label": this.props["aria-label"], className: (0, _classnames2["default"])("Collection", className), onScroll: this._onScroll, role: "grid", style: _extends({}, collectionStyle, style), tabIndex: 0 }, cellCount > 0 && _react2["default"].createElement("div", { className: "Collection__innerScrollContainer", style: { height: totalHeight, maxHeight: totalHeight, maxWidth: totalWidth, pointerEvents: isScrolling ? "none" : "auto", width: totalWidth } }, childrenToDisplay), 0 === cellCount && noContentRenderer()); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_enablePointerEventsAfterDelay", value: function() { var _this3 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { var isScrollingChange = _this3.props.isScrollingChange; isScrollingChange(!1), _this3._disablePointerEventsTimeoutId = null, _this3.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_invokeOnSectionRenderedHelper", value: function() { var _props4 = this.props, cellLayoutManager = _props4.cellLayoutManager, onSectionRendered = _props4.onSectionRendered; this._onSectionRenderedMemoizer({ callback: onSectionRendered, indices: { indices: cellLayoutManager.getLastRenderedIndices() } }); } }, { key: "_invokeOnScrollMemoizer", value: function(_ref2) { var _this4 = this, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, totalHeight = _ref2.totalHeight, totalWidth = _ref2.totalWidth; this._onScrollMemoizer({ callback: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, _props5 = _this4.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } }, { key: "_setNextState", value: function(state) { var _this5 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this5._setNextStateAnimationFrameId = null, _this5.setState(state); }); } }, { key: "_setScrollPosition", value: function(_ref4) { var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "_updateScrollPositionForScrollToCell", value: function() { var _props6 = this.props, cellLayoutManager = _props6.cellLayoutManager, height = _props6.height, scrollToAlignment = _props6.scrollToAlignment, scrollToCell = _props6.scrollToCell, width = _props6.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop; if (scrollToCell >= 0) { var scrollPosition = cellLayoutManager.getScrollPositionForCell({ align: scrollToAlignment, cellIndex: scrollToCell, height: height, scrollLeft: scrollLeft, scrollTop: scrollTop, width: width }); scrollPosition.scrollLeft === scrollLeft && scrollPosition.scrollTop === scrollTop || this._setScrollPosition(scrollPosition); } } }, { key: "_onScroll", value: function(event) { if (event.target === this._scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props7 = this.props, cellLayoutManager = _props7.cellLayoutManager, height = _props7.height, isScrollingChange = _props7.isScrollingChange, width = _props7.width, scrollbarSize = this._scrollbarSize, _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge3.height, totalWidth = _cellLayoutManager$ge3.width, scrollLeft = Math.max(0, Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft)), scrollTop = Math.max(0, Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop)); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; this.state.isScrolling || (isScrollingChange(!0), this.setState({ isScrolling: !0 })), this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft, scrollTop: scrollTop, totalWidth: totalWidth, totalHeight: totalHeight }); } } } ]), CollectionView; }(_react.Component); CollectionView.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, cellCount: _react.PropTypes.number.isRequired, cellLayoutManager: _react.PropTypes.object.isRequired, className: _react.PropTypes.string, height: _react.PropTypes.number.isRequired, horizontalOverscanSize: _react.PropTypes.number.isRequired, isScrollingChange: _react.PropTypes.func, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, scrollLeft: _react.PropTypes.number, scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToCell: _react.PropTypes.number, scrollTop: _react.PropTypes.number, style: _react.PropTypes.object, verticalOverscanSize: _react.PropTypes.number.isRequired, width: _react.PropTypes.number.isRequired }, CollectionView.defaultProps = { "aria-label": "grid", horizontalOverscanSize: 0, noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, scrollToAlignment: "auto", style: {}, verticalOverscanSize: 0 }, exports["default"] = CollectionView; }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ !function() { "use strict"; function classNames() { for (var classes = [], i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { var argType = typeof arg; if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); } } return classes.join(" "); } var hasOwn = {}.hasOwnProperty; "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), // register as 'classnames', consistent with npm package name !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); }(); }, /* 16 */ /***/ function(module, exports) { "use strict"; function createCallbackMemoizer() { var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] || arguments[0], cachedIndices = {}; return function(_ref) { var callback = _ref.callback, indices = _ref.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) { var value = indices[key]; return Array.isArray(value) ? value.length > 0 : value >= 0; }), indexChanged = keys.length !== Object.keys(cachedIndices).length || keys.some(function(key) { var cachedValue = cachedIndices[key], value = indices[key]; return Array.isArray(value) ? cachedValue.join(",") !== value.join(",") : cachedValue !== value; }); cachedIndices = indices, allInitialized && indexChanged && callback(indices); }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = createCallbackMemoizer; }, /* 17 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var size, canUseDOM = __webpack_require__(18); module.exports = function(recalc) { if ((!size || recalc) && canUseDOM) { var scrollDiv = document.createElement("div"); scrollDiv.style.position = "absolute", scrollDiv.style.top = "-9999px", scrollDiv.style.width = "50px", scrollDiv.style.height = "50px", scrollDiv.style.overflow = "scroll", document.body.appendChild(scrollDiv), size = scrollDiv.offsetWidth - scrollDiv.clientWidth, document.body.removeChild(scrollDiv); } return size; }; }, /* 18 */ /***/ function(module, exports) { "use strict"; module.exports = !("undefined" == typeof window || !window.document || !window.document.createElement); }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(global) { for (var now = __webpack_require__(20), root = "undefined" == typeof window ? global : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = root["request" + suffix], caf = root["cancel" + suffix] || root["cancelRequest" + suffix], i = 0; !raf && i < vendors.length; i++) raf = root[vendors[i] + "Request" + suffix], caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix]; // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60; raf = function(callback) { if (0 === queue.length) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now, setTimeout(function() { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try { cp[i].callback(last); } catch (e) { setTimeout(function() { throw e; }, 0); } }, Math.round(next)); } return queue.push({ handle: ++id, callback: callback, cancelled: !1 }), id; }, caf = function(handle) { for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0); }; } module.exports = function(fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(root, fn); }, module.exports.cancel = function() { caf.apply(root, arguments); }, module.exports.polyfill = function() { root.requestAnimationFrame = raf, root.cancelAnimationFrame = caf; }; }).call(exports, function() { return this; }()); }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { // Generated by CoffeeScript 1.7.1 (function() { var getNanoSeconds, hrtime, loadTime; "undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() { return performance.now(); } : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() { return (getNanoSeconds() - loadTime) / 1e6; }, hrtime = process.hrtime, getNanoSeconds = function() { var hr; return hr = hrtime(), 1e9 * hr[0] + hr[1]; }, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() { return Date.now() - loadTime; }, loadTime = Date.now()) : (module.exports = function() { return new Date().getTime() - loadTime; }, loadTime = new Date().getTime()); }).call(this); }).call(exports, __webpack_require__(21)); }, /* 21 */ /***/ function(module, exports) { function runTimeout(fun) { if (cachedSetTimeout === setTimeout) //normal enviroments in sane situations return setTimeout(fun, 0); try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) //normal enviroments in sane situations return clearTimeout(marker); try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } function cleanUpNextTick() { draining && currentQueue && (draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue()); } function drainQueue() { if (!draining) { var timeout = runTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, runClearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var cachedSetTimeout, cachedClearTimeout, process = module.exports = {}; !function() { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function() { throw new Error("setTimeout is not defined"); }; } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function() { throw new Error("clearTimeout is not defined"); }; } }(); var currentQueue, queue = [], draining = !1, queueIndex = -1; 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)), 1 !== queue.length || draining || runTimeout(drainQueue); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, 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; }; }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function calculateSizeAndPositionData(_ref) { for (var cellCount = _ref.cellCount, cellSizeAndPositionGetter = _ref.cellSizeAndPositionGetter, sectionSize = _ref.sectionSize, cellMetadata = [], sectionManager = new _SectionManager2["default"](sectionSize), height = 0, width = 0, index = 0; index < cellCount; index++) { var cellMetadatum = cellSizeAndPositionGetter({ index: index }); if (null == cellMetadatum.height || isNaN(cellMetadatum.height) || null == cellMetadatum.width || isNaN(cellMetadatum.width) || null == cellMetadatum.x || isNaN(cellMetadatum.x) || null == cellMetadatum.y || isNaN(cellMetadatum.y)) throw Error("Invalid metadata returned for cell " + index + ":\n x:" + cellMetadatum.x + ", y:" + cellMetadatum.y + ", width:" + cellMetadatum.width + ", height:" + cellMetadatum.height); height = Math.max(height, cellMetadatum.y + cellMetadatum.height), width = Math.max(width, cellMetadatum.x + cellMetadatum.width), cellMetadata[index] = cellMetadatum, sectionManager.registerCell({ cellMetadatum: cellMetadatum, index: index }); } return { cellMetadata: cellMetadata, height: height, sectionManager: sectionManager, width: width }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = calculateSizeAndPositionData; var _SectionManager = __webpack_require__(23), _SectionManager2 = _interopRequireDefault(_SectionManager); }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Section = __webpack_require__(24), _Section2 = _interopRequireDefault(_Section), SECTION_SIZE = 100, SectionManager = function() { function SectionManager() { var sectionSize = arguments.length <= 0 || void 0 === arguments[0] ? SECTION_SIZE : arguments[0]; _classCallCheck(this, SectionManager), this._sectionSize = sectionSize, this._cellMetadata = [], this._sections = {}; } return _createClass(SectionManager, [ { key: "getCellIndices", value: function(_ref) { var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y, indices = {}; return this.getSections({ height: height, width: width, x: x, y: y }).forEach(function(section) { return section.getCellIndices().forEach(function(index) { indices[index] = index; }); }), Object.keys(indices).map(function(index) { return indices[index]; }); } }, { key: "getCellMetadata", value: function(_ref2) { var index = _ref2.index; return this._cellMetadata[index]; } }, { key: "getSections", value: function(_ref3) { for (var height = _ref3.height, width = _ref3.width, x = _ref3.x, y = _ref3.y, sectionXStart = Math.floor(x / this._sectionSize), sectionXStop = Math.floor((x + width - 1) / this._sectionSize), sectionYStart = Math.floor(y / this._sectionSize), sectionYStop = Math.floor((y + height - 1) / this._sectionSize), sections = [], sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) for (var sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) { var key = sectionX + "." + sectionY; this._sections[key] || (this._sections[key] = new _Section2["default"]({ height: this._sectionSize, width: this._sectionSize, x: sectionX * this._sectionSize, y: sectionY * this._sectionSize })), sections.push(this._sections[key]); } return sections; } }, { key: "getTotalSectionCount", value: function() { return Object.keys(this._sections).length; } }, { key: "toString", value: function() { var _this = this; return Object.keys(this._sections).map(function(index) { return _this._sections[index].toString(); }); } }, { key: "registerCell", value: function(_ref4) { var cellMetadatum = _ref4.cellMetadatum, index = _ref4.index; this._cellMetadata[index] = cellMetadatum, this.getSections(cellMetadatum).forEach(function(section) { return section.addCellIndex({ index: index }); }); } } ]), SectionManager; }(); exports["default"] = SectionManager; }, /* 24 */ /***/ function(module, exports) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), Section = function() { function Section(_ref) { var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y; _classCallCheck(this, Section), this.height = height, this.width = width, this.x = x, this.y = y, this._indexMap = {}, this._indices = []; } return _createClass(Section, [ { key: "addCellIndex", value: function(_ref2) { var index = _ref2.index; this._indexMap[index] || (this._indexMap[index] = !0, this._indices.push(index)); } }, { key: "getCellIndices", value: function() { return this._indices; } }, { key: "toString", value: function() { return this.x + "," + this.y + " " + this.width + "x" + this.height; } } ]), Section; }(); exports["default"] = Section; }, /* 25 */ /***/ function(module, exports) { "use strict"; function getUpdatedOffsetForIndex(_ref) { var _ref$align = _ref.align, align = void 0 === _ref$align ? "auto" : _ref$align, cellOffset = _ref.cellOffset, cellSize = _ref.cellSize, containerSize = _ref.containerSize, currentOffset = _ref.currentOffset, maxOffset = cellOffset, minOffset = maxOffset - containerSize + cellSize; switch (align) { case "start": return maxOffset; case "end": return minOffset; case "center": return maxOffset - (containerSize - cellSize) / 2; default: return Math.max(minOffset, Math.min(maxOffset, currentOffset)); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = getUpdatedOffsetForIndex; }, /* 26 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ColumnSizer = exports["default"] = void 0; var _ColumnSizer2 = __webpack_require__(27), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2); exports["default"] = _ColumnSizer3["default"], exports.ColumnSizer = _ColumnSizer3["default"]; }, /* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(28), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) { function ColumnSizer(props, context) { _classCallCheck(this, ColumnSizer); var _this = _possibleConstructorReturn(this, (ColumnSizer.__proto__ || Object.getPrototypeOf(ColumnSizer)).call(this, props, context)); return _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(ColumnSizer, _Component), _createClass(ColumnSizer, [ { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnCount = _props.columnCount, width = _props.width; columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnCount === prevProps.columnCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize(); } }, { key: "render", value: function() { var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnCount = _props2.columnCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnCount; columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth), columnWidth = Math.floor(columnWidth); var adjustedWidth = Math.min(width, columnWidth * columnCount); return children({ adjustedWidth: adjustedWidth, getColumnWidth: function() { return columnWidth; }, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_registerChild", value: function(child) { if (null !== child && !(child instanceof _Grid2["default"])) throw Error("Unexpected child type registered; only Grid children are supported."); this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize(); } } ]), ColumnSizer; }(_react.Component); ColumnSizer.propTypes = { children: _react.PropTypes.func.isRequired, columnMaxWidth: _react.PropTypes.number, columnMinWidth: _react.PropTypes.number, columnCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number.isRequired }, exports["default"] = ColumnSizer; }, /* 28 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.defaultCellRangeRenderer = exports.Grid = exports["default"] = void 0; var _Grid2 = __webpack_require__(29), _Grid3 = _interopRequireDefault(_Grid2), _defaultCellRangeRenderer2 = __webpack_require__(35), _defaultCellRangeRenderer3 = _interopRequireDefault(_defaultCellRangeRenderer2); exports["default"] = _Grid3["default"], exports.Grid = _Grid3["default"], exports.defaultCellRangeRenderer = _defaultCellRangeRenderer3["default"]; }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = void 0; var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _calculateSizeAndPositionDataAndUpdateScrollOffset = __webpack_require__(30), _calculateSizeAndPositionDataAndUpdateScrollOffset2 = _interopRequireDefault(_calculateSizeAndPositionDataAndUpdateScrollOffset), _ScalingCellSizeAndPositionManager = __webpack_require__(31), _ScalingCellSizeAndPositionManager2 = _interopRequireDefault(_ScalingCellSizeAndPositionManager), _createCallbackMemoizer = __webpack_require__(16), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _getOverscanIndices = __webpack_require__(33), _getOverscanIndices2 = _interopRequireDefault(_getOverscanIndices), _scrollbarSize = __webpack_require__(17), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(19), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _updateScrollIndexHelper = __webpack_require__(34), _updateScrollIndexHelper2 = _interopRequireDefault(_updateScrollIndexHelper), _defaultCellRangeRenderer = __webpack_require__(35), _defaultCellRangeRenderer2 = _interopRequireDefault(_defaultCellRangeRenderer), DEFAULT_SCROLLING_RESET_TIME_INTERVAL = exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, Grid = function(_Component) { function Grid(props, context) { _classCallCheck(this, Grid); var _this = _possibleConstructorReturn(this, (Grid.__proto__ || Object.getPrototypeOf(Grid)).call(this, props, context)); return _this.state = { isScrolling: !1, scrollDirectionHorizontal: _getOverscanIndices.SCROLL_DIRECTION_FIXED, scrollDirectionVertical: _getOverscanIndices.SCROLL_DIRECTION_FIXED, scrollLeft: 0, scrollTop: 0 }, _this._onGridRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onScrollMemoizer = (0, _createCallbackMemoizer2["default"])(!1), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), _this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._setNextStateCallback = _this._setNextStateCallback.bind(_this), _this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this), _this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this), _this._columnWidthGetter = _this._wrapSizeGetter(props.columnWidth), _this._rowHeightGetter = _this._wrapSizeGetter(props.rowHeight), _this._columnSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({ cellCount: props.columnCount, cellSizeGetter: function(index) { return _this._columnWidthGetter(index); }, estimatedCellSize: _this._getEstimatedColumnSize(props) }), _this._rowSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({ cellCount: props.rowCount, cellSizeGetter: function(index) { return _this._rowHeightGetter(index); }, estimatedCellSize: _this._getEstimatedRowSize(props) }), _this._cellCache = {}, _this; } return _inherits(Grid, _Component), _createClass(Grid, [ { key: "measureAllCells", value: function() { var _props = this.props, columnCount = _props.columnCount, rowCount = _props.rowCount; this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1), this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1); } }, { key: "recomputeGridSize", value: function() { var _ref = arguments.length <= 0 || void 0 === arguments[0] ? {} : arguments[0], _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? 0 : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? 0 : _ref$rowIndex; this._columnSizeAndPositionManager.resetCell(columnIndex), this._rowSizeAndPositionManager.resetCell(rowIndex), this._cellCache = {}, this.forceUpdate(); } }, { key: "componentDidMount", value: function() { var _props2 = this.props, scrollLeft = _props2.scrollLeft, scrollToColumn = _props2.scrollToColumn, scrollTop = _props2.scrollTop, scrollToRow = _props2.scrollToRow; this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(), this._scrollbarSizeMeasured = !0, this.setState({})), (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._updateScrollLeftForScrollToColumn(), this._updateScrollTopForScrollToRow()), this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft || 0, scrollTop: scrollTop || 0, totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize() }); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, columnCount = _props3.columnCount, height = _props3.height, rowCount = _props3.rowCount, scrollToAlignment = _props3.scrollToAlignment, scrollToColumn = _props3.scrollToColumn, scrollToRow = _props3.scrollToRow, width = _props3.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop, columnOrRowCountJustIncreasedFromZero = columnCount > 0 && 0 === prevProps.columnCount || rowCount > 0 && 0 === prevProps.rowCount; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && (scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollLeft = scrollLeft), !autoHeight && scrollTop >= 0 && (scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollTop = scrollTop)), (0, _updateScrollIndexHelper2["default"])({ cellSizeAndPositionManager: this._columnSizeAndPositionManager, previousCellsCount: prevProps.columnCount, previousCellSize: prevProps.columnWidth, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToAlignment: scrollToAlignment, scrollToIndex: scrollToColumn, size: width, updateScrollIndexCallback: function(scrollToColumn) { return _this2._updateScrollLeftForScrollToColumn(_extends({}, _this2.props, { scrollToColumn: scrollToColumn })); } }), (0, _updateScrollIndexHelper2["default"])({ cellSizeAndPositionManager: this._rowSizeAndPositionManager, previousCellsCount: prevProps.rowCount, previousCellSize: prevProps.rowHeight, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToAlignment: scrollToAlignment, scrollToIndex: scrollToRow, size: height, updateScrollIndexCallback: function(scrollToRow) { return _this2._updateScrollTopForScrollToRow(_extends({}, _this2.props, { scrollToRow: scrollToRow })); } }), this._invokeOnGridRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._scrollbarSize = (0, _scrollbarSize2["default"])(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0, this._calculateChildrenToRender(); } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { var _this3 = this; 0 === nextProps.columnCount && 0 !== nextState.scrollLeft || 0 === nextProps.rowCount && 0 !== nextState.scrollTop ? this._setScrollPosition({ scrollLeft: 0, scrollTop: 0 }) : nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop }), this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth), this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight), this._columnSizeAndPositionManager.configure({ cellCount: nextProps.columnCount, estimatedCellSize: this._getEstimatedColumnSize(nextProps) }), this._rowSizeAndPositionManager.configure({ cellCount: nextProps.rowCount, estimatedCellSize: this._getEstimatedRowSize(nextProps) }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({ cellCount: this.props.columnCount, cellSize: this.props.columnWidth, computeMetadataCallback: function() { return _this3._columnSizeAndPositionManager.resetCell(0); }, computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.columnCount, nextCellSize: nextProps.columnWidth, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: this.props.scrollToColumn, updateScrollOffsetForScrollToIndex: function() { return _this3._updateScrollLeftForScrollToColumn(nextProps, nextState); } }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({ cellCount: this.props.rowCount, cellSize: this.props.rowHeight, computeMetadataCallback: function() { return _this3._rowSizeAndPositionManager.resetCell(0); }, computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.rowCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: this.props.scrollToRow, updateScrollOffsetForScrollToIndex: function() { return _this3._updateScrollTopForScrollToRow(nextProps, nextState); } }), this._calculateChildrenToRender(nextProps, nextState); } }, { key: "render", value: function() { var _this4 = this, _props4 = this.props, autoContainerWidth = _props4.autoContainerWidth, autoHeight = _props4.autoHeight, className = _props4.className, height = _props4.height, noContentRenderer = _props4.noContentRenderer, style = _props4.style, tabIndex = _props4.tabIndex, width = _props4.width, isScrolling = this.state.isScrolling, gridStyle = { height: autoHeight ? "auto" : height, width: width }, totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0; gridStyle.overflowX = totalColumnsWidth + verticalScrollBarSize <= width ? "hidden" : "auto", gridStyle.overflowY = totalRowsHeight + horizontalScrollBarSize <= height ? "hidden" : "auto"; var childrenToDisplay = this._childrenToDisplay, showNoContentRenderer = 0 === childrenToDisplay.length && height > 0 && width > 0; return _react2["default"].createElement("div", { ref: function(_ref2) { _this4._scrollingContainer = _ref2; }, "aria-label": this.props["aria-label"], className: (0, _classnames2["default"])("Grid", className), onScroll: this._onScroll, role: "grid", style: _extends({}, gridStyle, style), tabIndex: tabIndex }, childrenToDisplay.length > 0 && _react2["default"].createElement("div", { className: "Grid__innerScrollContainer", style: { width: autoContainerWidth ? "auto" : totalColumnsWidth, height: totalRowsHeight, maxWidth: totalColumnsWidth, maxHeight: totalRowsHeight, pointerEvents: isScrolling ? "none" : "auto" } }, childrenToDisplay), showNoContentRenderer && noContentRenderer()); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_calculateChildrenToRender", value: function() { var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], cellClassName = props.cellClassName, cellRenderer = props.cellRenderer, cellRangeRenderer = props.cellRangeRenderer, cellStyle = props.cellStyle, columnCount = props.columnCount, height = props.height, overscanColumnCount = props.overscanColumnCount, overscanRowCount = props.overscanRowCount, rowCount = props.rowCount, width = props.width, isScrolling = state.isScrolling, scrollDirectionHorizontal = state.scrollDirectionHorizontal, scrollDirectionVertical = state.scrollDirectionVertical, scrollLeft = state.scrollLeft, scrollTop = state.scrollTop; if (this._childrenToDisplay = [], height > 0 && width > 0) { var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({ containerSize: width, offset: scrollLeft }), visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({ containerSize: height, offset: scrollTop }), horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({ containerSize: width, offset: scrollLeft }), verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({ containerSize: height, offset: scrollTop }); this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop, this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop; var overscanColumnIndices = (0, _getOverscanIndices2["default"])({ cellCount: columnCount, overscanCellsCount: overscanColumnCount, scrollDirection: scrollDirectionHorizontal, startIndex: this._renderedColumnStartIndex, stopIndex: this._renderedColumnStopIndex }), overscanRowIndices = (0, _getOverscanIndices2["default"])({ cellCount: rowCount, overscanCellsCount: overscanRowCount, scrollDirection: scrollDirectionVertical, startIndex: this._renderedRowStartIndex, stopIndex: this._renderedRowStopIndex }); this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex, this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex, this._childrenToDisplay = cellRangeRenderer({ cellCache: this._cellCache, cellClassName: this._wrapCellClassNameGetter(cellClassName), cellRenderer: cellRenderer, cellStyle: this._wrapCellStyleGetter(cellStyle), columnSizeAndPositionManager: this._columnSizeAndPositionManager, columnStartIndex: this._columnStartIndex, columnStopIndex: this._columnStopIndex, horizontalOffsetAdjustment: horizontalOffsetAdjustment, isScrolling: isScrolling, rowSizeAndPositionManager: this._rowSizeAndPositionManager, rowStartIndex: this._rowStartIndex, rowStopIndex: this._rowStopIndex, scrollLeft: scrollLeft, scrollTop: scrollTop, verticalOffsetAdjustment: verticalOffsetAdjustment }); } } }, { key: "_enablePointerEventsAfterDelay", value: function() { var scrollingResetTimeInterval = this.props.scrollingResetTimeInterval; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, scrollingResetTimeInterval); } }, { key: "_enablePointerEventsAfterDelayCallback", value: function() { this._disablePointerEventsTimeoutId = null, this._cellCache = {}, this.setState({ isScrolling: !1, scrollDirectionHorizontal: _getOverscanIndices.SCROLL_DIRECTION_FIXED, scrollDirectionVertical: _getOverscanIndices.SCROLL_DIRECTION_FIXED }); } }, { key: "_getEstimatedColumnSize", value: function(props) { return "number" == typeof props.columnWidth ? props.columnWidth : props.estimatedColumnSize; } }, { key: "_getEstimatedRowSize", value: function(props) { return "number" == typeof props.rowHeight ? props.rowHeight : props.estimatedRowSize; } }, { key: "_invokeOnGridRenderedHelper", value: function() { var onSectionRendered = this.props.onSectionRendered; this._onGridRenderedMemoizer({ callback: onSectionRendered, indices: { columnOverscanStartIndex: this._columnStartIndex, columnOverscanStopIndex: this._columnStopIndex, columnStartIndex: this._renderedColumnStartIndex, columnStopIndex: this._renderedColumnStopIndex, rowOverscanStartIndex: this._rowStartIndex, rowOverscanStopIndex: this._rowStopIndex, rowStartIndex: this._renderedRowStartIndex, rowStopIndex: this._renderedRowStopIndex } }); } }, { key: "_invokeOnScrollMemoizer", value: function(_ref3) { var _this5 = this, scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, totalColumnsWidth = _ref3.totalColumnsWidth, totalRowsHeight = _ref3.totalRowsHeight; this._onScrollMemoizer({ callback: function(_ref4) { var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, _props5 = _this5.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalRowsHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalColumnsWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } }, { key: "_setNextState", value: function(state) { this._nextState = state, this._setNextStateAnimationFrameId || (this._setNextStateAnimationFrameId = (0, _raf2["default"])(this._setNextStateCallback)); } }, { key: "_setNextStateCallback", value: function() { var state = this._nextState; this._setNextStateAnimationFrameId = null, this._nextState = null, this.setState(state); } }, { key: "_setScrollPosition", value: function(_ref5) { var scrollLeft = _ref5.scrollLeft, scrollTop = _ref5.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "_wrapCellClassNameGetter", value: function(className) { return this._wrapPropertyGetter(className); } }, { key: "_wrapCellStyleGetter", value: function(style) { return this._wrapPropertyGetter(style); } }, { key: "_wrapPropertyGetter", value: function(value) { return value instanceof Function ? value : function() { return value; }; } }, { key: "_wrapSizeGetter", value: function(size) { return this._wrapPropertyGetter(size); } }, { key: "_updateScrollLeftForScrollToColumn", value: function() { var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], columnCount = props.columnCount, scrollToAlignment = props.scrollToAlignment, scrollToColumn = props.scrollToColumn, width = props.width, scrollLeft = state.scrollLeft; if (scrollToColumn >= 0 && columnCount > 0) { var targetIndex = Math.max(0, Math.min(columnCount - 1, scrollToColumn)), calculatedScrollLeft = this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({ align: scrollToAlignment, containerSize: width, currentOffset: scrollLeft, targetIndex: targetIndex }); scrollLeft !== calculatedScrollLeft && this._setScrollPosition({ scrollLeft: calculatedScrollLeft }); } } }, { key: "_updateScrollTopForScrollToRow", value: function() { var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], height = props.height, rowCount = props.rowCount, scrollToAlignment = props.scrollToAlignment, scrollToRow = props.scrollToRow, scrollTop = state.scrollTop; if (scrollToRow >= 0 && rowCount > 0) { var targetIndex = Math.max(0, Math.min(rowCount - 1, scrollToRow)), calculatedScrollTop = this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({ align: scrollToAlignment, containerSize: height, currentOffset: scrollTop, targetIndex: targetIndex }); scrollTop !== calculatedScrollTop && this._setScrollPosition({ scrollTop: calculatedScrollTop }); } } }, { key: "_onScroll", value: function(event) { if (event.target === this._scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props6 = this.props, height = _props6.height, width = _props6.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), event.target.scrollLeft), scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), event.target.scrollTop); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED, scrollDirectionVertical = scrollTop > this.state.scrollTop ? _getOverscanIndices.SCROLL_DIRECTION_FORWARD : _getOverscanIndices.SCROLL_DIRECTION_BACKWARD, scrollDirectionHorizontal = scrollLeft > this.state.scrollLeft ? _getOverscanIndices.SCROLL_DIRECTION_FORWARD : _getOverscanIndices.SCROLL_DIRECTION_BACKWARD; this.state.isScrolling || this.setState({ isScrolling: !0 }), this._setNextState({ isScrolling: !0, scrollDirectionHorizontal: scrollDirectionHorizontal, scrollDirectionVertical: scrollDirectionVertical, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft, scrollTop: scrollTop, totalColumnsWidth: totalColumnsWidth, totalRowsHeight: totalRowsHeight }); } } } ]), Grid; }(_react.Component); Grid.propTypes = { "aria-label": _react.PropTypes.string, autoContainerWidth: _react.PropTypes.bool, autoHeight: _react.PropTypes.bool, cellClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), cellStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), cellRenderer: _react.PropTypes.func.isRequired, cellRangeRenderer: _react.PropTypes.func.isRequired, className: _react.PropTypes.string, columnCount: _react.PropTypes.number.isRequired, columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, estimatedColumnSize: _react.PropTypes.number.isRequired, estimatedRowSize: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, overscanColumnCount: _react.PropTypes.number.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowCount: _react.PropTypes.number.isRequired, scrollingResetTimeInterval: _react.PropTypes.number, scrollLeft: _react.PropTypes.number, scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToColumn: _react.PropTypes.number, scrollTop: _react.PropTypes.number, scrollToRow: _react.PropTypes.number, style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, Grid.defaultProps = { "aria-label": "grid", cellStyle: {}, cellRangeRenderer: _defaultCellRangeRenderer2["default"], estimatedColumnSize: 100, estimatedRowSize: 30, noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, overscanColumnCount: 0, overscanRowCount: 10, scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL, scrollToAlignment: "auto", style: {}, tabIndex: 0 }, exports["default"] = Grid; }, /* 30 */ /***/ function(module, exports) { "use strict"; function calculateSizeAndPositionDataAndUpdateScrollOffset(_ref) { var cellCount = _ref.cellCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; cellCount === nextCellsCount && ("number" != typeof cellSize && "number" != typeof nextCellSize || cellSize === nextCellSize) || (computeMetadataCallback(computeMetadataCallbackProps), scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = calculateSizeAndPositionDataAndUpdateScrollOffset; }, /* 31 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.DEFAULT_MAX_SCROLL_SIZE = void 0; var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _CellSizeAndPositionManager = __webpack_require__(32), _CellSizeAndPositionManager2 = _interopRequireDefault(_CellSizeAndPositionManager), DEFAULT_MAX_SCROLL_SIZE = exports.DEFAULT_MAX_SCROLL_SIZE = 15e5, ScalingCellSizeAndPositionManager = function() { function ScalingCellSizeAndPositionManager(_ref) { var _ref$maxScrollSize = _ref.maxScrollSize, maxScrollSize = void 0 === _ref$maxScrollSize ? DEFAULT_MAX_SCROLL_SIZE : _ref$maxScrollSize, params = _objectWithoutProperties(_ref, [ "maxScrollSize" ]); _classCallCheck(this, ScalingCellSizeAndPositionManager), this._cellSizeAndPositionManager = new _CellSizeAndPositionManager2["default"](params), this._maxScrollSize = maxScrollSize; } return _createClass(ScalingCellSizeAndPositionManager, [ { key: "configure", value: function(params) { this._cellSizeAndPositionManager.configure(params); } }, { key: "getCellCount", value: function() { return this._cellSizeAndPositionManager.getCellCount(); } }, { key: "getEstimatedCellSize", value: function() { return this._cellSizeAndPositionManager.getEstimatedCellSize(); } }, { key: "getLastMeasuredIndex", value: function() { return this._cellSizeAndPositionManager.getLastMeasuredIndex(); } }, { key: "getOffsetAdjustment", value: function(_ref2) { var containerSize = _ref2.containerSize, offset = _ref2.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(), offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: safeTotalSize }); return Math.round(offsetPercentage * (safeTotalSize - totalSize)); } }, { key: "getSizeAndPositionOfCell", value: function(index) { return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index); } }, { key: "getSizeAndPositionOfLastMeasuredCell", value: function() { return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell(); } }, { key: "getTotalSize", value: function() { return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize()); } }, { key: "getUpdatedOffsetForIndex", value: function(_ref3) { var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex, totalSize = _ref3.totalSize; currentOffset = this._safeOffsetToOffset({ containerSize: containerSize, offset: currentOffset }); var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ align: align, containerSize: containerSize, currentOffset: currentOffset, targetIndex: targetIndex, totalSize: totalSize }); return this._offsetToSafeOffset({ containerSize: containerSize, offset: offset }); } }, { key: "getVisibleCellRange", value: function(_ref4) { var containerSize = _ref4.containerSize, offset = _ref4.offset; return offset = this._safeOffsetToOffset({ containerSize: containerSize, offset: offset }), this._cellSizeAndPositionManager.getVisibleCellRange({ containerSize: containerSize, offset: offset }); } }, { key: "resetCell", value: function(index) { this._cellSizeAndPositionManager.resetCell(index); } }, { key: "_getOffsetPercentage", value: function(_ref5) { var containerSize = _ref5.containerSize, offset = _ref5.offset, totalSize = _ref5.totalSize; return totalSize <= containerSize ? 0 : offset / (totalSize - containerSize); } }, { key: "_offsetToSafeOffset", value: function(_ref6) { var containerSize = _ref6.containerSize, offset = _ref6.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) return offset; var offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: totalSize }); return Math.round(offsetPercentage * (safeTotalSize - containerSize)); } }, { key: "_safeOffsetToOffset", value: function(_ref7) { var containerSize = _ref7.containerSize, offset = _ref7.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) return offset; var offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: safeTotalSize }); return Math.round(offsetPercentage * (totalSize - containerSize)); } } ]), ScalingCellSizeAndPositionManager; }(); exports["default"] = ScalingCellSizeAndPositionManager; }, /* 32 */ /***/ function(module, exports) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), CellSizeAndPositionManager = function() { function CellSizeAndPositionManager(_ref) { var cellCount = _ref.cellCount, cellSizeGetter = _ref.cellSizeGetter, estimatedCellSize = _ref.estimatedCellSize; _classCallCheck(this, CellSizeAndPositionManager), this._cellSizeGetter = cellSizeGetter, this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize, this._cellSizeAndPositionData = {}, this._lastMeasuredIndex = -1; } return _createClass(CellSizeAndPositionManager, [ { key: "configure", value: function(_ref2) { var cellCount = _ref2.cellCount, estimatedCellSize = _ref2.estimatedCellSize; this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize; } }, { key: "getCellCount", value: function() { return this._cellCount; } }, { key: "getEstimatedCellSize", value: function() { return this._estimatedCellSize; } }, { key: "getLastMeasuredIndex", value: function() { return this._lastMeasuredIndex; } }, { key: "getSizeAndPositionOfCell", value: function(index) { if (index < 0 || index >= this._cellCount) throw Error("Requested index " + index + " is outside of range 0.." + this._cellCount); if (index > this._lastMeasuredIndex) { for (var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), _offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, i = this._lastMeasuredIndex + 1; i <= index; i++) { var _size = this._cellSizeGetter({ index: i }); if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); this._cellSizeAndPositionData[i] = { offset: _offset, size: _size }, _offset += _size; } this._lastMeasuredIndex = index; } return this._cellSizeAndPositionData[index]; } }, { key: "getSizeAndPositionOfLastMeasuredCell", value: function() { return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : { offset: 0, size: 0 }; } }, { key: "getTotalSize", value: function() { var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize; } }, { key: "getUpdatedOffsetForIndex", value: function(_ref3) { var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex, datum = this.getSizeAndPositionOfCell(targetIndex), maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, idealOffset = void 0; switch (align) { case "start": idealOffset = maxOffset; break; case "end": idealOffset = minOffset; break; case "center": idealOffset = maxOffset - (containerSize - datum.size) / 2; break; default: idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); } var totalSize = this.getTotalSize(); return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); } }, { key: "getVisibleCellRange", value: function(_ref4) { var containerSize = _ref4.containerSize, offset = _ref4.offset, totalSize = this.getTotalSize(); if (0 === totalSize) return {}; var maxOffset = offset + containerSize, start = this._findNearestCell(offset), datum = this.getSizeAndPositionOfCell(start); offset = datum.offset + datum.size; for (var stop = start; offset < maxOffset && stop < this._cellCount - 1; ) stop++, offset += this.getSizeAndPositionOfCell(stop).size; return { start: start, stop: stop }; } }, { key: "resetCell", value: function(index) { this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); } }, { key: "_binarySearch", value: function(_ref5) { for (var high = _ref5.high, low = _ref5.low, offset = _ref5.offset, middle = void 0, currentOffset = void 0; low <= high; ) { if (middle = low + Math.floor((high - low) / 2), currentOffset = this.getSizeAndPositionOfCell(middle).offset, currentOffset === offset) return middle; currentOffset < offset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); } if (low > 0) return low - 1; } }, { key: "_exponentialSearch", value: function(_ref6) { for (var index = _ref6.index, offset = _ref6.offset, interval = 1; index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset; ) index += interval, interval *= 2; return this._binarySearch({ high: Math.min(index, this._cellCount - 1), low: Math.floor(index / 2), offset: offset }); } }, { key: "_findNearestCell", value: function(offset) { if (isNaN(offset)) throw Error("Invalid offset " + offset + " specified"); offset = Math.max(0, offset); var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); return lastMeasuredCellSizeAndPosition.offset >= offset ? this._binarySearch({ high: lastMeasuredIndex, low: 0, offset: offset }) : this._exponentialSearch({ index: lastMeasuredIndex, offset: offset }); } } ]), CellSizeAndPositionManager; }(); exports["default"] = CellSizeAndPositionManager; }, /* 33 */ /***/ function(module, exports) { "use strict"; function getOverscanIndices(_ref) { var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, scrollDirection = _ref.scrollDirection, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, overscanStartIndex = void 0, overscanStopIndex = void 0; return scrollDirection === SCROLL_DIRECTION_FORWARD ? (overscanStartIndex = startIndex, overscanStopIndex = stopIndex + 2 * overscanCellsCount) : scrollDirection === SCROLL_DIRECTION_BACKWARD ? (overscanStartIndex = startIndex - 2 * overscanCellsCount, overscanStopIndex = stopIndex) : (overscanStartIndex = startIndex - overscanCellsCount, overscanStopIndex = stopIndex + overscanCellsCount), { overscanStartIndex: Math.max(0, overscanStartIndex), overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex) }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = getOverscanIndices; var SCROLL_DIRECTION_BACKWARD = exports.SCROLL_DIRECTION_BACKWARD = -1, SCROLL_DIRECTION_FORWARD = (exports.SCROLL_DIRECTION_FIXED = 0, exports.SCROLL_DIRECTION_FORWARD = 1); }, /* 34 */ /***/ function(module, exports) { "use strict"; function updateScrollIndexHelper(_ref) { var cellSize = _ref.cellSize, cellSizeAndPositionManager = _ref.cellSizeAndPositionManager, previousCellsCount = _ref.previousCellsCount, previousCellSize = _ref.previousCellSize, previousScrollToAlignment = _ref.previousScrollToAlignment, previousScrollToIndex = _ref.previousScrollToIndex, previousSize = _ref.previousSize, scrollOffset = _ref.scrollOffset, scrollToAlignment = _ref.scrollToAlignment, scrollToIndex = _ref.scrollToIndex, size = _ref.size, updateScrollIndexCallback = _ref.updateScrollIndexCallback, cellCount = cellSizeAndPositionManager.getCellCount(), hasScrollToIndex = scrollToIndex >= 0 && scrollToIndex < cellCount, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; hasScrollToIndex && (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex) ? updateScrollIndexCallback(scrollToIndex) : !hasScrollToIndex && cellCount > 0 && (size < previousSize || cellCount < previousCellsCount) && scrollOffset > cellSizeAndPositionManager.getTotalSize() - size && updateScrollIndexCallback(cellCount - 1); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = updateScrollIndexHelper; }, /* 35 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function defaultCellRangeRenderer(_ref) { for (var cellCache = _ref.cellCache, cellClassName = _ref.cellClassName, cellRenderer = _ref.cellRenderer, cellStyle = _ref.cellStyle, columnSizeAndPositionManager = _ref.columnSizeAndPositionManager, columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, horizontalOffsetAdjustment = _ref.horizontalOffsetAdjustment, isScrolling = _ref.isScrolling, rowSizeAndPositionManager = _ref.rowSizeAndPositionManager, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex, verticalOffsetAdjustment = (_ref.scrollLeft, _ref.scrollTop, _ref.verticalOffsetAdjustment), renderedCells = [], rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) for (var rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex), columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { var columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex), key = rowIndex + "-" + columnIndex, cellStyleObject = cellStyle({ rowIndex: rowIndex, columnIndex: columnIndex }), renderedCell = void 0; if (isScrolling ? (cellCache[key] || (cellCache[key] = cellRenderer({ columnIndex: columnIndex, isScrolling: isScrolling, rowIndex: rowIndex })), renderedCell = cellCache[key]) : renderedCell = cellRenderer({ columnIndex: columnIndex, isScrolling: isScrolling, rowIndex: rowIndex }), null != renderedCell && renderedCell !== !1) { var className = cellClassName({ columnIndex: columnIndex, rowIndex: rowIndex }), child = _react2["default"].createElement("div", { key: key, className: (0, _classnames2["default"])("Grid__cell", className), style: _extends({ height: rowDatum.size, left: columnDatum.offset + horizontalOffsetAdjustment, top: rowDatum.offset + verticalOffsetAdjustment, width: columnDatum.size }, cellStyleObject) }, renderedCell); renderedCells.push(child); } } return renderedCells; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }; exports["default"] = defaultCellRangeRenderer; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames); }, /* 36 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.SortIndicator = exports.SortDirection = exports.FlexColumn = exports.FlexTable = exports.defaultRowRenderer = exports.defaultHeaderRenderer = exports.defaultCellRenderer = exports.defaultCellDataGetter = exports["default"] = void 0; var _FlexTable2 = __webpack_require__(37), _FlexTable3 = _interopRequireDefault(_FlexTable2), _defaultCellDataGetter2 = __webpack_require__(43), _defaultCellDataGetter3 = _interopRequireDefault(_defaultCellDataGetter2), _defaultCellRenderer2 = __webpack_require__(42), _defaultCellRenderer3 = _interopRequireDefault(_defaultCellRenderer2), _defaultHeaderRenderer2 = __webpack_require__(39), _defaultHeaderRenderer3 = _interopRequireDefault(_defaultHeaderRenderer2), _defaultRowRenderer2 = __webpack_require__(44), _defaultRowRenderer3 = _interopRequireDefault(_defaultRowRenderer2), _FlexColumn2 = __webpack_require__(38), _FlexColumn3 = _interopRequireDefault(_FlexColumn2), _SortDirection2 = __webpack_require__(41), _SortDirection3 = _interopRequireDefault(_SortDirection2), _SortIndicator2 = __webpack_require__(40), _SortIndicator3 = _interopRequireDefault(_SortIndicator2); exports["default"] = _FlexTable3["default"], exports.defaultCellDataGetter = _defaultCellDataGetter3["default"], exports.defaultCellRenderer = _defaultCellRenderer3["default"], exports.defaultHeaderRenderer = _defaultHeaderRenderer3["default"], exports.defaultRowRenderer = _defaultRowRenderer3["default"], exports.FlexTable = _FlexTable3["default"], exports.FlexColumn = _FlexColumn3["default"], exports.SortDirection = _SortDirection3["default"], exports.SortIndicator = _SortIndicator3["default"]; }, /* 37 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(38), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(28), _Grid2 = _interopRequireDefault(_Grid), _defaultRowRenderer = __webpack_require__(44), _defaultRowRenderer2 = _interopRequireDefault(_defaultRowRenderer), _SortDirection = __webpack_require__(41), _SortDirection2 = _interopRequireDefault(_SortDirection), FlexTable = function(_Component) { function FlexTable(props) { _classCallCheck(this, FlexTable); var _this = _possibleConstructorReturn(this, (FlexTable.__proto__ || Object.getPrototypeOf(FlexTable)).call(this, props)); return _this.state = { scrollbarWidth: 0 }, _this._cellClassName = _this._cellClassName.bind(_this), _this._cellStyle = _this._cellStyle.bind(_this), _this._createColumn = _this._createColumn.bind(_this), _this._createRow = _this._createRow.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(FlexTable, _Component), _createClass(FlexTable, [ { key: "forceUpdateGrid", value: function() { this.Grid.forceUpdate(); } }, { key: "measureAllRows", value: function() { this.Grid.measureAllCells(); } }, { key: "recomputeRowHeights", value: function() { var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0]; this.Grid.recomputeGridSize({ rowIndex: index }), this.forceUpdateGrid(); } }, { key: "componentDidMount", value: function() { this._setScrollbarWidth(); } }, { key: "componentDidUpdate", value: function() { this._setScrollbarWidth(); } }, { key: "render", value: function() { var _this2 = this, _props = this.props, children = _props.children, className = _props.className, disableHeader = _props.disableHeader, gridClassName = _props.gridClassName, gridStyle = _props.gridStyle, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, rowClassName = _props.rowClassName, rowStyle = _props.rowStyle, scrollToIndex = _props.scrollToIndex, style = _props.style, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowClass = rowClassName instanceof Function ? rowClassName({ index: -1 }) : rowClassName, rowStyleObject = rowStyle instanceof Function ? rowStyle({ index: -1 }) : rowStyle; return this._cachedColumnStyles = [], _react2["default"].Children.toArray(children).forEach(function(column, index) { _this2._cachedColumnStyles[index] = _this2._getFlexStyleForColumn(column, column.props.style); }), _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable", className), style: style }, !disableHeader && _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass), style: _extends({}, rowStyleObject, { height: headerHeight, paddingRight: scrollbarWidth, width: width }) }, this._getRenderedHeaderRow()), _react2["default"].createElement(_Grid2["default"], _extends({}, this.props, { autoContainerWidth: !0, className: (0, _classnames2["default"])("FlexTable__Grid", gridClassName), cellClassName: this._cellClassName, cellRenderer: this._createRow, cellStyle: this._cellStyle, columnWidth: width, columnCount: 1, height: availableRowsHeight, noContentRenderer: noRowsRenderer, onScroll: this._onScroll, onSectionRendered: this._onSectionRendered, ref: function(_ref) { _this2.Grid = _ref; }, scrollbarWidth: scrollbarWidth, scrollToRow: scrollToIndex, style: gridStyle }))); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_cellClassName", value: function(_ref2) { var rowIndex = _ref2.rowIndex, rowWrapperClassName = this.props.rowWrapperClassName; return rowWrapperClassName instanceof Function ? rowWrapperClassName({ index: rowIndex - 1 }) : rowWrapperClassName; } }, { key: "_cellStyle", value: function(_ref3) { var rowIndex = _ref3.rowIndex, rowWrapperStyle = this.props.rowWrapperStyle; return rowWrapperStyle instanceof Function ? rowWrapperStyle({ index: rowIndex - 1 }) : rowWrapperStyle; } }, { key: "_createColumn", value: function(_ref4) { var column = _ref4.column, columnIndex = _ref4.columnIndex, isScrolling = _ref4.isScrolling, rowData = _ref4.rowData, rowIndex = _ref4.rowIndex, _column$props = column.props, cellDataGetter = _column$props.cellDataGetter, cellRenderer = _column$props.cellRenderer, className = _column$props.className, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellData = cellDataGetter({ columnData: columnData, dataKey: dataKey, rowData: rowData }), renderedCell = cellRenderer({ cellData: cellData, columnData: columnData, dataKey: dataKey, isScrolling: isScrolling, rowData: rowData, rowIndex: rowIndex }), style = this._cachedColumnStyles[columnIndex], title = "string" == typeof renderedCell ? renderedCell : null; return _react2["default"].createElement("div", { key: "Row" + rowIndex + "-Col" + columnIndex, className: (0, _classnames2["default"])("FlexTable__rowColumn", className), style: style, title: title }, renderedCell); } }, { key: "_createHeader", value: function(_ref5) { var column = _ref5.column, index = _ref5.index, _props2 = this.props, headerClassName = _props2.headerClassName, headerStyle = _props2.headerStyle, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, label = _column$props2.label, columnData = _column$props2.columnData, sortEnabled = !disableSort && sort, classNames = (0, _classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, { FlexTable__sortableHeaderColumn: sortEnabled }), style = this._getFlexStyleForColumn(column, headerStyle), renderedHeader = headerRenderer({ columnData: columnData, dataKey: dataKey, disableSort: disableSort, label: label, sortBy: sortBy, sortDirection: sortDirection }), a11yProps = {}; return (sortEnabled || onHeaderClick) && !function() { var newSortDirection = sortBy !== dataKey || sortDirection === _SortDirection2["default"].DESC ? _SortDirection2["default"].ASC : _SortDirection2["default"].DESC, onClick = function() { sortEnabled && sort({ sortBy: dataKey, sortDirection: newSortDirection }), onHeaderClick && onHeaderClick({ columnData: columnData, dataKey: dataKey }); }, onKeyDown = function(event) { "Enter" !== event.key && " " !== event.key || onClick(); }; a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.role = "rowheader", a11yProps.tabIndex = 0, a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown; }(), _react2["default"].createElement("div", _extends({}, a11yProps, { key: "Header-Col" + index, className: classNames, style: style }), renderedHeader); } }, { key: "_createRow", value: function(_ref6) { var _this3 = this, index = _ref6.rowIndex, isScrolling = _ref6.isScrolling, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, onRowDoubleClick = _props3.onRowDoubleClick, onRowMouseOver = _props3.onRowMouseOver, onRowMouseOut = _props3.onRowMouseOut, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowRenderer = _props3.rowRenderer, rowStyle = _props3.rowStyle, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName({ index: index }) : rowClassName, rowStyleObject = rowStyle instanceof Function ? rowStyle({ index: index }) : rowStyle, rowData = rowGetter({ index: index }), columns = _react2["default"].Children.toArray(children).map(function(column, columnIndex) { return _this3._createColumn({ column: column, columnIndex: columnIndex, isScrolling: isScrolling, rowData: rowData, rowIndex: index, scrollbarWidth: scrollbarWidth }); }), className = (0, _classnames2["default"])("FlexTable__row", rowClass), style = _extends({}, rowStyleObject, { height: this._getRowHeight(index), paddingRight: scrollbarWidth }); return rowRenderer({ className: className, columns: columns, index: index, isScrolling: isScrolling, onRowClick: onRowClick, onRowDoubleClick: onRowDoubleClick, onRowMouseOver: onRowMouseOver, onRowMouseOut: onRowMouseOut, rowData: rowData, style: style }); } }, { key: "_getFlexStyleForColumn", value: function(column) { var customStyle = arguments.length <= 1 || void 0 === arguments[1] ? {} : arguments[1], flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = _extends({}, customStyle, { flex: flexValue, msFlex: flexValue, WebkitFlex: flexValue }); return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth), style; } }, { key: "_getRenderedHeaderRow", value: function() { var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : _react2["default"].Children.toArray(children); return items.map(function(column, index) { return _this4._createHeader({ column: column, index: index }); }); } }, { key: "_getRowHeight", value: function(rowIndex) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight({ index: rowIndex }) : rowHeight; } }, { key: "_onScroll", value: function(_ref7) { var clientHeight = _ref7.clientHeight, scrollHeight = _ref7.scrollHeight, scrollTop = _ref7.scrollTop, onScroll = this.props.onScroll; onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); } }, { key: "_onSectionRendered", value: function(_ref8) { var rowOverscanStartIndex = _ref8.rowOverscanStartIndex, rowOverscanStopIndex = _ref8.rowOverscanStopIndex, rowStartIndex = _ref8.rowStartIndex, rowStopIndex = _ref8.rowStopIndex, onRowsRendered = this.props.onRowsRendered; onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); } }, { key: "_setScrollbarWidth", value: function() { var Grid = (0, _reactDom.findDOMNode)(this.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth; this.setState({ scrollbarWidth: scrollbarWidth }); } } ]), FlexTable; }(_react.Component); FlexTable.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, children: function children(props, propName, componentName) { for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn"); }, className: _react.PropTypes.string, disableHeader: _react.PropTypes.bool, estimatedRowSize: _react.PropTypes.number.isRequired, gridClassName: _react.PropTypes.string, gridStyle: _react.PropTypes.object, headerClassName: _react.PropTypes.string, headerHeight: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func, onHeaderClick: _react.PropTypes.func, headerStyle: _react.PropTypes.object, onRowClick: _react.PropTypes.func, onRowDoubleClick: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func, onRowsRendered: _react.PropTypes.func, onScroll: _react.PropTypes.func.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowGetter: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowCount: _react.PropTypes.number.isRequired, rowRenderer: _react.PropTypes.func, rowStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]).isRequired, rowWrapperClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowWrapperStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, sort: _react.PropTypes.func, sortBy: _react.PropTypes.string, sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]), style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, FlexTable.defaultProps = { disableHeader: !1, estimatedRowSize: 30, headerHeight: 0, headerStyle: {}, noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowCount: 10, rowRenderer: _defaultRowRenderer2["default"], rowStyle: {}, scrollToAlignment: "auto", style: {} }, exports["default"] = FlexTable; }, /* 38 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _react = __webpack_require__(3), _defaultHeaderRenderer = __webpack_require__(39), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultCellRenderer = __webpack_require__(42), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultCellDataGetter = __webpack_require__(43), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), Column = function(_Component) { function Column() { return _classCallCheck(this, Column), _possibleConstructorReturn(this, (Column.__proto__ || Object.getPrototypeOf(Column)).apply(this, arguments)); } return _inherits(Column, _Component), Column; }(_react.Component); Column.defaultProps = { cellDataGetter: _defaultCellDataGetter2["default"], cellRenderer: _defaultCellRenderer2["default"], flexGrow: 0, flexShrink: 1, headerRenderer: _defaultHeaderRenderer2["default"], style: {} }, Column.propTypes = { "aria-label": _react.PropTypes.string, cellDataGetter: _react.PropTypes.func, cellRenderer: _react.PropTypes.func, className: _react.PropTypes.string, columnData: _react.PropTypes.object, dataKey: _react.PropTypes.any.isRequired, disableSort: _react.PropTypes.bool, flexGrow: _react.PropTypes.number, flexShrink: _react.PropTypes.number, headerClassName: _react.PropTypes.string, headerRenderer: _react.PropTypes.func.isRequired, label: _react.PropTypes.string, maxWidth: _react.PropTypes.number, minWidth: _react.PropTypes.number, style: _react.PropTypes.object, width: _react.PropTypes.number.isRequired }, exports["default"] = Column; }, /* 39 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function defaultHeaderRenderer(_ref) { var dataKey = (_ref.columnData, _ref.dataKey), label = (_ref.disableSort, _ref.label), sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _react2["default"].createElement("span", { className: "FlexTable__headerTruncatedText", key: "label", title: label }, label) ]; return showSortIndicator && children.push(_react2["default"].createElement(_SortIndicator2["default"], { key: "SortIndicator", sortDirection: sortDirection })), children; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultHeaderRenderer; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _SortIndicator = __webpack_require__(40), _SortIndicator2 = _interopRequireDefault(_SortIndicator); }, /* 40 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function SortIndicator(_ref) { var sortDirection = _ref.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", { "FlexTable__sortableHeaderIcon--ASC": sortDirection === _SortDirection2["default"].ASC, "FlexTable__sortableHeaderIcon--DESC": sortDirection === _SortDirection2["default"].DESC }); return _react2["default"].createElement("svg", { className: classNames, width: 18, height: 18, viewBox: "0 0 24 24" }, sortDirection === _SortDirection2["default"].ASC ? _react2["default"].createElement("path", { d: "M7 14l5-5 5 5z" }) : _react2["default"].createElement("path", { d: "M7 10l5 5 5-5z" }), _react2["default"].createElement("path", { d: "M0 0h24v24H0z", fill: "none" })); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = SortIndicator; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _SortDirection = __webpack_require__(41), _SortDirection2 = _interopRequireDefault(_SortDirection); SortIndicator.propTypes = { sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]) }; }, /* 41 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var SortDirection = { ASC: "ASC", DESC: "DESC" }; exports["default"] = SortDirection; }, /* 42 */ /***/ function(module, exports) { "use strict"; function defaultCellRenderer(_ref) { var cellData = _ref.cellData; _ref.cellDataKey, _ref.columnData, _ref.rowData, _ref.rowIndex; return null == cellData ? "" : String(cellData); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultCellRenderer; }, /* 43 */ /***/ function(module, exports) { "use strict"; function defaultCellDataGetter(_ref) { var dataKey = (_ref.columnData, _ref.dataKey), rowData = _ref.rowData; return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultCellDataGetter; }, /* 44 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function defaultRowRenderer(_ref) { var className = _ref.className, columns = _ref.columns, index = _ref.index, onRowClick = (_ref.isScrolling, _ref.onRowClick), onRowDoubleClick = _ref.onRowDoubleClick, onRowMouseOver = _ref.onRowMouseOver, onRowMouseOut = _ref.onRowMouseOut, style = (_ref.rowData, _ref.style), a11yProps = {}; return (onRowClick || onRowDoubleClick || onRowMouseOver || onRowMouseOut) && (a11yProps["aria-label"] = "row", a11yProps.role = "row", a11yProps.tabIndex = 0, onRowClick && (a11yProps.onClick = function() { return onRowClick({ index: index }); }), onRowDoubleClick && (a11yProps.onDoubleClick = function() { return onRowDoubleClick({ index: index }); }), onRowMouseOut && (a11yProps.onMouseOut = function() { return onRowMouseOut({ index: index }); }), onRowMouseOver && (a11yProps.onMouseOver = function() { return onRowMouseOver({ index: index }); })), _react2["default"].createElement("div", _extends({}, a11yProps, { className: className, style: style }), columns); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }; exports["default"] = defaultRowRenderer; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react); }, /* 45 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.InfiniteLoader = exports["default"] = void 0; var _InfiniteLoader2 = __webpack_require__(46), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); exports["default"] = _InfiniteLoader3["default"], exports.InfiniteLoader = _InfiniteLoader3["default"]; }, /* 46 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function isRangeVisible(_ref2) { var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; return !(startIndex > lastRenderedStopIndex || stopIndex < lastRenderedStartIndex); } function scanForUnloadedRanges(_ref3) { for (var isRowLoaded = _ref3.isRowLoaded, minimumBatchSize = _ref3.minimumBatchSize, rowCount = _ref3.rowCount, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, index = startIndex; index <= stopIndex; index++) { var loaded = isRowLoaded({ index: index }); loaded ? null !== rangeStopIndex && (unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = index, null === rangeStartIndex && (rangeStartIndex = index)); } if (null !== rangeStopIndex) { for (var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), rowCount - 1), _index = rangeStopIndex + 1; _index <= potentialStopIndex && !isRowLoaded({ index: _index }); _index++) rangeStopIndex = _index; unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }); } if (unloadedRanges.length) for (var firstUnloadedRange = unloadedRanges[0]; firstUnloadedRange.stopIndex - firstUnloadedRange.startIndex + 1 < minimumBatchSize && firstUnloadedRange.startIndex > 0; ) { var _index2 = firstUnloadedRange.startIndex - 1; if (isRowLoaded({ index: _index2 })) break; firstUnloadedRange.startIndex = _index2; } return unloadedRanges; } function forceUpdateReactVirtualizedComponent(component) { "function" == typeof component.forceUpdateGrid ? component.forceUpdateGrid() : component.forceUpdate(); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(); exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges, exports.forceUpdateReactVirtualizedComponent = forceUpdateReactVirtualizedComponent; var _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _createCallbackMemoizer = __webpack_require__(16), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), InfiniteLoader = function(_Component) { function InfiniteLoader(props, context) { _classCallCheck(this, InfiniteLoader); var _this = _possibleConstructorReturn(this, (InfiniteLoader.__proto__ || Object.getPrototypeOf(InfiniteLoader)).call(this, props, context)); return _this._loadMoreRowsMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onRowsRendered = _this._onRowsRendered.bind(_this), _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, [ { key: "render", value: function() { var children = this.props.children; return children({ onRowsRendered: this._onRowsRendered, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_loadUnloadedRanges", value: function(unloadedRanges) { var _this2 = this, loadMoreRows = this.props.loadMoreRows; unloadedRanges.forEach(function(unloadedRange) { var promise = loadMoreRows(unloadedRange); promise && promise.then(function() { isRangeVisible({ lastRenderedStartIndex: _this2._lastRenderedStartIndex, lastRenderedStopIndex: _this2._lastRenderedStopIndex, startIndex: unloadedRange.startIndex, stopIndex: unloadedRange.stopIndex }) && _this2._registeredChild && forceUpdateReactVirtualizedComponent(_this2._registeredChild); }); }); } }, { key: "_onRowsRendered", value: function(_ref) { var _this3 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, minimumBatchSize = _props.minimumBatchSize, rowCount = _props.rowCount, threshold = _props.threshold; this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; var unloadedRanges = scanForUnloadedRanges({ isRowLoaded: isRowLoaded, minimumBatchSize: minimumBatchSize, rowCount: rowCount, startIndex: Math.max(0, startIndex - threshold), stopIndex: Math.min(rowCount - 1, stopIndex + threshold) }), squashedUnloadedRanges = unloadedRanges.reduce(function(reduced, unloadedRange) { return reduced.concat([ unloadedRange.startIndex, unloadedRange.stopIndex ]); }, []); this._loadMoreRowsMemoizer({ callback: function() { _this3._loadUnloadedRanges(unloadedRanges); }, indices: { squashedUnloadedRanges: squashedUnloadedRanges } }); } }, { key: "_registerChild", value: function(registeredChild) { this._registeredChild = registeredChild; } } ]), InfiniteLoader; }(_react.Component); InfiniteLoader.propTypes = { children: _react.PropTypes.func.isRequired, isRowLoaded: _react.PropTypes.func.isRequired, loadMoreRows: _react.PropTypes.func.isRequired, minimumBatchSize: _react.PropTypes.number.isRequired, rowCount: _react.PropTypes.number.isRequired, threshold: _react.PropTypes.number.isRequired }, InfiniteLoader.defaultProps = { minimumBatchSize: 10, rowCount: 0, threshold: 15 }, exports["default"] = InfiniteLoader; }, /* 47 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ScrollSync = exports["default"] = void 0; var _ScrollSync2 = __webpack_require__(48), _ScrollSync3 = _interopRequireDefault(_ScrollSync2); exports["default"] = _ScrollSync3["default"], exports.ScrollSync = _ScrollSync3["default"]; }, /* 48 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ScrollSync = function(_Component) { function ScrollSync(props, context) { _classCallCheck(this, ScrollSync); var _this = _possibleConstructorReturn(this, (ScrollSync.__proto__ || Object.getPrototypeOf(ScrollSync)).call(this, props, context)); return _this.state = { clientHeight: 0, clientWidth: 0, scrollHeight: 0, scrollLeft: 0, scrollTop: 0, scrollWidth: 0 }, _this._onScroll = _this._onScroll.bind(_this), _this; } return _inherits(ScrollSync, _Component), _createClass(ScrollSync, [ { key: "render", value: function() { var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth; return children({ clientHeight: clientHeight, clientWidth: clientWidth, onScroll: this._onScroll, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onScroll", value: function(_ref) { var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth; this.setState({ clientHeight: clientHeight, clientWidth: clientWidth, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } } ]), ScrollSync; }(_react.Component); ScrollSync.propTypes = { children: _react.PropTypes.func.isRequired }, exports["default"] = ScrollSync; }, /* 49 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.VirtualScroll = exports["default"] = void 0; var _VirtualScroll2 = __webpack_require__(50), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2); exports["default"] = _VirtualScroll3["default"], exports.VirtualScroll = _VirtualScroll3["default"]; }, /* 50 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Grid = __webpack_require__(28), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(15), _classnames2 = _interopRequireDefault(_classnames), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), VirtualScroll = function(_Component) { function VirtualScroll(props, context) { _classCallCheck(this, VirtualScroll); var _this = _possibleConstructorReturn(this, (VirtualScroll.__proto__ || Object.getPrototypeOf(VirtualScroll)).call(this, props, context)); return _this._cellRenderer = _this._cellRenderer.bind(_this), _this._createRowClassNameGetter = _this._createRowClassNameGetter.bind(_this), _this._createRowStyleGetter = _this._createRowStyleGetter.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, [ { key: "forceUpdateGrid", value: function() { this.Grid.forceUpdate(); } }, { key: "measureAllRows", value: function() { this.Grid.measureAllCells(); } }, { key: "recomputeRowHeights", value: function() { var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0]; this.Grid.recomputeGridSize({ rowIndex: index }), this.forceUpdateGrid(); } }, { key: "render", value: function() { var _this2 = this, _props = this.props, className = _props.className, noRowsRenderer = _props.noRowsRenderer, scrollToIndex = _props.scrollToIndex, width = _props.width, classNames = (0, _classnames2["default"])("VirtualScroll", className); return _react2["default"].createElement(_Grid2["default"], _extends({}, this.props, { autoContainerWidth: !0, cellRenderer: this._cellRenderer, cellClassName: this._createRowClassNameGetter(), cellStyle: this._createRowStyleGetter(), className: classNames, columnWidth: width, columnCount: 1, noContentRenderer: noRowsRenderer, onScroll: this._onScroll, onSectionRendered: this._onSectionRendered, ref: function(_ref) { _this2.Grid = _ref; }, scrollToRow: scrollToIndex })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_cellRenderer", value: function(_ref2) { var isScrolling = (_ref2.columnIndex, _ref2.isScrolling), rowIndex = _ref2.rowIndex, rowRenderer = this.props.rowRenderer; return rowRenderer({ index: rowIndex, isScrolling: isScrolling }); } }, { key: "_createRowClassNameGetter", value: function() { var rowClassName = this.props.rowClassName; return rowClassName instanceof Function ? function(_ref3) { var rowIndex = _ref3.rowIndex; return rowClassName({ index: rowIndex }); } : function() { return rowClassName; }; } }, { key: "_createRowStyleGetter", value: function() { var rowStyle = this.props.rowStyle, wrapped = rowStyle instanceof Function ? rowStyle : function() { return rowStyle; }; return function(_ref4) { var rowIndex = _ref4.rowIndex; return _extends({ width: "100%" }, wrapped({ index: rowIndex })); }; } }, { key: "_onScroll", value: function(_ref5) { var clientHeight = _ref5.clientHeight, scrollHeight = _ref5.scrollHeight, scrollTop = _ref5.scrollTop, onScroll = this.props.onScroll; onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); } }, { key: "_onSectionRendered", value: function(_ref6) { var rowOverscanStartIndex = _ref6.rowOverscanStartIndex, rowOverscanStopIndex = _ref6.rowOverscanStopIndex, rowStartIndex = _ref6.rowStartIndex, rowStopIndex = _ref6.rowStopIndex, onRowsRendered = this.props.onRowsRendered; onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); } } ]), VirtualScroll; }(_react.Component); VirtualScroll.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, className: _react.PropTypes.string, estimatedRowSize: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func.isRequired, onRowsRendered: _react.PropTypes.func.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, onScroll: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowRenderer: _react.PropTypes.func.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowCount: _react.PropTypes.number.isRequired, rowStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, VirtualScroll.defaultProps = { estimatedRowSize: 30, noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowCount: 10, scrollToAlignment: "auto", style: {} }, exports["default"] = VirtualScroll; }, /* 51 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.IS_SCROLLING_TIMEOUT = exports.WindowScroller = exports["default"] = void 0; var _WindowScroller2 = __webpack_require__(52), _WindowScroller3 = _interopRequireDefault(_WindowScroller2), _onScroll = __webpack_require__(53), _onScroll2 = _interopRequireDefault(_onScroll); exports["default"] = _WindowScroller3["default"], exports.WindowScroller = _WindowScroller3["default"], exports.IS_SCROLLING_TIMEOUT = _onScroll2["default"]; }, /* 52 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _raf = __webpack_require__(19), _raf2 = _interopRequireDefault(_raf), _onScroll = __webpack_require__(53), WindowScroller = function(_Component) { function WindowScroller(props) { _classCallCheck(this, WindowScroller); var _this = _possibleConstructorReturn(this, (WindowScroller.__proto__ || Object.getPrototypeOf(WindowScroller)).call(this, props)), height = "undefined" != typeof window ? window.innerHeight : 0; return _this.state = { isScrolling: !1, height: height, scrollTop: 0 }, _this._onScrollWindow = _this._onScrollWindow.bind(_this), _this._onResizeWindow = _this._onResizeWindow.bind(_this), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), _this; } return _inherits(WindowScroller, _Component), _createClass(WindowScroller, [ { key: "componentDidMount", value: function() { var height = this.state.height; this._positionFromTop = _reactDom2["default"].findDOMNode(this).getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top, height !== window.innerHeight && this.setState({ height: window.innerHeight }), (0, _onScroll.registerScrollListener)(this), window.addEventListener("resize", this._onResizeWindow, !1); } }, { key: "componentWillUnmount", value: function() { (0, _onScroll.unregisterScrollListener)(this), window.removeEventListener("resize", this._onResizeWindow, !1); } }, { key: "_setNextState", value: function(state) { var _this2 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this2._setNextStateAnimationFrameId = null, _this2.setState(state); }); } }, { key: "render", value: function() { var children = this.props.children, _state = this.state, isScrolling = _state.isScrolling, scrollTop = _state.scrollTop, height = _state.height; return _react2["default"].createElement("div", null, children({ height: height, isScrolling: isScrolling, scrollTop: scrollTop })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_enablePointerEventsAfterDelayCallback", value: function() { this.setState({ isScrolling: !1 }); } }, { key: "_onResizeWindow", value: function(event) { var onResize = this.props.onResize, height = window.innerHeight || 0; this.setState({ height: height }), onResize({ height: height }); } }, { key: "_onScrollWindow", value: function(event) { var onScroll = this.props.onScroll, scrollY = "scrollY" in window ? window.scrollY : document.documentElement.scrollTop, scrollTop = Math.max(0, scrollY - this._positionFromTop), state = { isScrolling: !0, scrollTop: scrollTop }; this.state.isScrolling ? this._setNextState(state) : this.setState(state), onScroll({ scrollTop: scrollTop }); } } ]), WindowScroller; }(_react.Component); WindowScroller.propTypes = { children: _react.PropTypes.func.isRequired, onResize: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired }, WindowScroller.defaultProps = { onResize: function() {}, onScroll: function() {} }, exports["default"] = WindowScroller; }, /* 53 */ /***/ function(module, exports) { "use strict"; function enablePointerEventsIfDisabled() { disablePointerEventsTimeoutId && (disablePointerEventsTimeoutId = null, document.body.style.pointerEvents = originalBodyPointerEvents, originalBodyPointerEvents = null); } function enablePointerEventsAfterDelayCallback() { enablePointerEventsIfDisabled(), mountedInstances.forEach(function(component) { return component._enablePointerEventsAfterDelayCallback(); }); } function enablePointerEventsAfterDelay() { disablePointerEventsTimeoutId && clearTimeout(disablePointerEventsTimeoutId), disablePointerEventsTimeoutId = setTimeout(enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT); } function onScrollWindow(event) { null == originalBodyPointerEvents && (originalBodyPointerEvents = document.body.style.pointerEvents, document.body.style.pointerEvents = "none", enablePointerEventsAfterDelay()), mountedInstances.forEach(function(component) { return component._onScrollWindow(event); }); } function registerScrollListener(component) { mountedInstances.length || window.addEventListener("scroll", onScrollWindow), mountedInstances.push(component); } function unregisterScrollListener(component) { mountedInstances = mountedInstances.filter(function(c) { return c !== component; }), mountedInstances.length || (window.removeEventListener("scroll", onScrollWindow), disablePointerEventsTimeoutId && (clearTimeout(disablePointerEventsTimeoutId), enablePointerEventsIfDisabled())); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.registerScrollListener = registerScrollListener, exports.unregisterScrollListener = unregisterScrollListener; var mountedInstances = [], originalBodyPointerEvents = null, disablePointerEventsTimeoutId = null, IS_SCROLLING_TIMEOUT = exports.IS_SCROLLING_TIMEOUT = 150; } ]); }); //# sourceMappingURL=react-virtualized.js.map
src/containers/ResetPasswordContainer.js
codefordenver/encorelink
import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import PropTypes from 'prop-types'; import React from 'react'; import ResetPassword from '../components/ResetPassword'; import { resetPasswordFromToken } from '../actions/userActions'; const ResetPasswordContainer = (props) => { function onResetPassword(formData) { props.resetPasswordFromToken(formData.password, props.location.query.id, props.location.query.token); } return ( <ResetPassword onSubmit={onResetPassword} /> ); }; ResetPasswordContainer.propTypes = { resetPasswordFromToken: PropTypes.func.isRequired, location: PropTypes.shape({ query: PropTypes.shape({ id: PropTypes.string, token: PropTypes.string }) }).isRequired }; const mapDispatchToProps = { resetPasswordFromToken }; export default withRouter(connect(null, mapDispatchToProps)(ResetPasswordContainer));
ajax/libs/material-ui/4.9.2/es/IconButton/IconButton.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes } from '@material-ui/utils'; import withStyles from '../styles/withStyles'; import { fade } from '../styles/colorManipulator'; import ButtonBase from '../ButtonBase'; import capitalize from '../utils/capitalize'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { textAlign: 'center', flex: '0 0 auto', fontSize: theme.typography.pxToRem(24), padding: 12, borderRadius: '50%', overflow: 'visible', // Explicitly set the default value to solve a bug on IE 11. color: theme.palette.action.active, transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shortest }), '&:hover': { backgroundColor: fade(theme.palette.action.active, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } }, '&$disabled': { backgroundColor: 'transparent', color: theme.palette.action.disabled } }, /* Styles applied to the root element if `edge="start"`. */ edgeStart: { marginLeft: -12, '$sizeSmall&': { marginLeft: -3 } }, /* Styles applied to the root element if `edge="end"`. */ edgeEnd: { marginRight: -12, '$sizeSmall&': { marginRight: -3 } }, /* Styles applied to the root element if `color="inherit"`. */ colorInherit: { color: 'inherit' }, /* Styles applied to the root element if `color="primary"`. */ colorPrimary: { color: theme.palette.primary.main, '&:hover': { backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `color="secondary"`. */ colorSecondary: { color: theme.palette.secondary.main, '&:hover': { backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `size="small"`. */ sizeSmall: { padding: 3, fontSize: theme.typography.pxToRem(18) }, /* Styles applied to the children container element. */ label: { width: '100%', display: 'flex', alignItems: 'inherit', justifyContent: 'inherit' } }); /** * Refer to the [Icons](/components/icons/) section of the documentation * regarding the available icon options. */ const IconButton = React.forwardRef(function IconButton(props, ref) { const { edge = false, children, classes, className, color = 'default', disabled = false, disableFocusRipple = false, size = 'medium' } = props, other = _objectWithoutPropertiesLoose(props, ["edge", "children", "classes", "className", "color", "disabled", "disableFocusRipple", "size"]); return React.createElement(ButtonBase, _extends({ className: clsx(classes.root, className, color !== 'default' && classes[`color${capitalize(color)}`], disabled && classes.disabled, { small: classes[`size${capitalize(size)}`] }[size], { start: classes.edgeStart, end: classes.edgeEnd }[edge]), centerRipple: true, focusRipple: !disableFocusRipple, disabled: disabled, ref: ref }, other), React.createElement("span", { className: classes.label }, children)); }); process.env.NODE_ENV !== "production" ? IconButton.propTypes = { /** * The icon element. */ children: chainPropTypes(PropTypes.node, props => { const found = React.Children.toArray(props.children).some(child => React.isValidElement(child) && child.props.onClick); if (found) { return new Error(['Material-UI: you are providing an onClick event listener ' + 'to a child of a button element.', 'Firefox will never trigger the event.', 'You should move the onClick listener to the parent button element.', 'https://github.com/mui-org/material-ui/issues/13957'].join('\n')); } return null; }), /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']), /** * If `true`, the button will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the keyboard focus ripple will be disabled. * `disableRipple` must also be true. */ disableFocusRipple: PropTypes.bool, /** * If `true`, the ripple effect will be disabled. */ disableRipple: PropTypes.bool, /** * If given, uses a negative margin to counteract the padding on one * side (this is often helpful for aligning the left or right * side of the icon with content above or below, without ruining the border * size and shape). */ edge: PropTypes.oneOf(['start', 'end', false]), /** * The size of the button. * `small` is equivalent to the dense button styling. */ size: PropTypes.oneOf(['small', 'medium']) } : void 0; export default withStyles(styles, { name: 'MuiIconButton' })(IconButton);
src/Sandbox/MLmodels/Housing/MapComponent.js
MLsandbox/MLsandbox
import React from 'react'; import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"; const MapComponent = withScriptjs(withGoogleMap((props) => <GoogleMap onClick={props.handleMapClick.bind(this)} options={{ mapTypeControl: false, panControl: false, streetViewControl: false, gestureHandling: 'cooperative', zoomControl: true, scrollwheel: false, draggable: true }} defaultZoom={14} defaultCenter={{ lat: 47.609343, lng: -122.334851 }} > <Marker position={{ lat: props.lat, lng: props.lng }} /> </GoogleMap> )) export default MapComponent;
ajax/libs/analytics.js/2.3.17/analytics.min.js
LeaYeh/cdnjs
(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"./version":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;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)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;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}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hublo"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/usercycle"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/awesm":13,"./lib/awesomatic":14,"./lib/bing-ads":15,"./lib/bronto":16,"./lib/bugherd":17,"./lib/bugsnag":18,"./lib/chartbeat":19,"./lib/churnbee":20,"./lib/clicktale":21,"./lib/clicky":22,"./lib/comscore":23,"./lib/crazy-egg":24,"./lib/curebit":25,"./lib/customerio":26,"./lib/drip":27,"./lib/errorception":28,"./lib/evergage":29,"./lib/facebook-conversion-tracking":30,"./lib/foxmetrics":31,"./lib/frontleaf":32,"./lib/gauges":33,"./lib/get-satisfaction":34,"./lib/google-analytics":35,"./lib/google-tag-manager":36,"./lib/gosquared":37,"./lib/heap":38,"./lib/hellobar":39,"./lib/hittail":40,"./lib/hublo":41,"./lib/hubspot":42,"./lib/improvely":43,"./lib/insidevault":44,"./lib/inspectlet":45,"./lib/intercom":46,"./lib/keen-io":47,"./lib/kenshoo":48,"./lib/kissmetrics":49,"./lib/klaviyo":50,"./lib/leadlander":51,"./lib/livechat":52,"./lib/lucky-orange":53,"./lib/lytics":54,"./lib/mixpanel":55,"./lib/mojn":56,"./lib/mouseflow":57,"./lib/mousestats":58,"./lib/navilytics":59,"./lib/olark":60,"./lib/optimizely":61,"./lib/perfect-audience":62,"./lib/pingdom":63,"./lib/piwik":64,"./lib/preact":65,"./lib/qualaroo":66,"./lib/quantcast":67,"./lib/rollbar":68,"./lib/saasquatch":69,"./lib/sentry":70,"./lib/snapengage":71,"./lib/spinnakr":72,"./lib/tapstream":73,"./lib/trakio":74,"./lib/twitter-ads":75,"./lib/usercycle":76,"./lib/uservoice":77,"./lib/vero":78,"./lib/visual-website-optimizer":79,"./lib/webengage":80,"./lib/woopra":81,"./lib/yandex-metrica":82}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":83,"to-snake-case":84,"use-https":85,each:4,is:86}],83:[function(require,module,exports){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");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}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.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};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}},{bind:87,callback:88,clone:89,debug:90,defaults:91,"./protos":92,slug:93,"./statics":94}],87:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;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}},{bind:95,"bind-all":96}],95:[function(require,module,exports){var slice=[].slice;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)))}}},{}],96:[function(require,module,exports){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}},{bind:95,type:7}],88:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":97}],97:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}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)}}},{}],89:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;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":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:return obj}}},{type:7}],90:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":98,"./debug":99}],98:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,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"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],99:[function(require,module,exports){module.exports=debug;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);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];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+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,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"};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};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],91:[function(require,module,exports){"use strict";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};module.exports=defaults},{}],92:[function(require,module,exports){var loadScript=require("segmentio/load-script");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var events=require("./events");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("yields/fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}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};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};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})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};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");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};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)}};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}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}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)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"segmentio/load-script":100,"to-no-case":101,callback:88,emitter:102,"./events":103,"next-tick":97,assert:104,after:105,"component/each":106,type:7,"yields/fmt":107}],100:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":108,"next-tick":97,type:7}],108:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};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)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],101:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],102:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};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};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};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};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:109}],109:[function(require,module,exports){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}},{}],103:[function(require,module,exports){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}},{}],104:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:110,fmt:107,stack:111}],110:[function(require,module,exports){var type=require("type");module.exports=equals;equals.compare=compare;function equals(){var i=arguments.length-1;while(i>0){if(!compare(arguments[i],arguments[--i]))return false}return true}function compare(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&compare(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!compare(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!compare(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}},{type:112}],112:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],107:[function(require,module,exports){module.exports=fmt;fmt.o=JSON.stringify;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],111:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],105:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],106:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:7,"component-type":7,"to-function":113}],113:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:114,"component-props":114}],114:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],93:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],94:[function(require,module,exports){var after=require("after");var domify=require("component/domify");var each=require("component/each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str) };return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:105,"component/domify":115,"component/each":106,emitter:102}],115:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[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>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],84:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":116}],116:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":117}],117:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;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()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],85:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],86:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":118,type:7,"component-type":7}],118:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;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}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();window.google_trackConversion({google_conversion_id:id,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":83,domify:119,each:4}],119:[function(require,module,exports){module.exports=parse;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>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}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;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":83}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');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(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};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)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}},{"analytics.js-integration":83}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":83,"load-script":120,is:86}],120:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":108,"next-tick":97,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":83,each:4}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();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.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"analytics.js-integration":83,is:86,"on-body":121}],121:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:106}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"analytics.js-integration":83,"on-body":121,domify:119,extend:122,bind:95,when:123,each:4}],122:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],123:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:88}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();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()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":83,facade:124,"load-pixel":125,querystring:126,each:4}],124:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":127,"./alias":128,"./group":129,"./identify":130,"./track":131,"./page":132,"./screen":133}],127:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();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)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};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||{}};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(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};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};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");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":134,"./is-enabled":135,"./utils":136,"./address":137,"obj-case":138,"new-date":139}],134:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}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}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}},{is:140,isodate:141,each:4}],140:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":118,type:7,"component-type":7}],141:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;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)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],135:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],136:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:142,clone:143,type:7}],142:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],143:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;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":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:return obj}}},{"component-type":7,type:7}],137:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)}}}},{"obj-case":138}],138:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};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)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}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}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}},{"case":144}],144:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":145}],145:[function(require,module,exports){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");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};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};exports.none=none},{"to-camel-case":146,"to-capital-case":147,"to-constant-case":148,"to-dot-case":149,"to-no-case":117,"to-pascal-case":150,"to-sentence-case":151,"to-slug-case":152,"to-snake-case":153,"to-space-case":154,"to-title-case":155}],146:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":154}],154:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":117}],147:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":117}],148:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":153}],153:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":154}],149:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":154}],150:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":154}],151:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":117}],152:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":154}],155:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":147,"escape-regexp":156,map:157,"title-case-minors":158}],156:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],157:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:106}],158:[function(require,module,exports){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"]},{}],139:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:159,isodate:141,"./milliseconds":160,"./seconds":161}],159:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":118,type:7}],160:[function(require,module,exports){var matcher=/\d{13}/; exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],161:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],128:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":136,"./facade":127}],129:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");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)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};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};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":136,"./address":137,"is-email":162,"new-date":139,"./facade":127}],162:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],130:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};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;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};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)};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]};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))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":137,"./facade":127,"is-email":162,"new-date":139,"./utils":136,"obj-case":138,trim:163}],163:[function(require,module,exports){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*$/,"")}},{}],131:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");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");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");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.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};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");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};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};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};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};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}},{"./utils":136,"./facade":127,"./identify":130,"is-email":162,"obj-case":138}],132:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");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};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":136,"./facade":127,"./track":131}],133:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":136,"./page":132,"./track":131}],125:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");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}};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)}}},{querystring:126,substitute:164}],126:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");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};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("&")}},{trim:163,type:7}],164:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":83,"next-tick":97}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');Bugsnag.prototype.initialize=function(page){var self=this;this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":83,is:86,extend:122,"on-error":165}],165:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":83,defaults:166,"on-body":121}],166:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":83,"global-queue":167,each:4}],167:[function(require,module,exports){module.exports=generate;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)}}},{}],21:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":168,domify:119,each:4,"analytics.js-integration":83,is:86,"use-https":85,"on-body":121}],168:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],22:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};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)};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())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:124,extend:122,"analytics.js-integration":83,is:86}],23:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"analytics.js-integration":83,"use-https":85}],24:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":83}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").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").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();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(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();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})}},{"analytics.js-integration":83,"global-queue":167,facade:124,throttle:169,"to-iso-string":170,clone:171,each:4,bind:95}],169:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],170:[function(require,module,exports){module.exports=toIsoString;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()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],171:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;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":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:return obj}}},{type:7}],26:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');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(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};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)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:172,"convert-dates":173,facade:124,"analytics.js-integration":83}],172:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:143}],173:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;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}},{is:86,clone:89}],27:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:172,"analytics.js-integration":83,is:86,"load-script":120,"global-queue":167}],28:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};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)}},{extend:122,"analytics.js-integration":83,"on-error":165,"global-queue":167}],29:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');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(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};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)};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")})};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")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":83,"global-queue":167}],30:[function(require,module,exports){var integration=require("analytics.js-integration"); var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"analytics.js-integration":83,"global-queue":167,each:4}],31:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":167,"analytics.js-integration":83,facade:124,each:4}],32:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');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);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};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())})}};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())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);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}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}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}},{"analytics.js-integration":83,bind:95,when:123,is:86}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":83,"global-queue":167}],34:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":83,"on-body":121}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};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",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;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,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});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,currency:track.currency()})});window.ga("ecommerce:send")};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)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};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));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};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)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}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=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}},{"analytics.js-integration":83,"global-queue":167,object:174,canonical:175,"use-https":85,facade:124,callback:88,"load-script":120,"obj-case":138,each:4,type:7,url:176,is:86}],174:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],175:[function(require,module,exports){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")}}},{}],176:[function(require,module,exports){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)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],36:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":167,"analytics.js-integration":83}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();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(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};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)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};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)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":83,facade:124,callback:88,"load-script":120,"on-body":121,each:4}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');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(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};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)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":83,alias:172}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":83}],40:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":83,is:86}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var Hublo=module.exports=integration("Hublo").assumesPageview().global("_hublo_").option("apiKey",null).tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">');Hublo.prototype.initialize=function(page){this.load(this.ready)};Hublo.prototype.loaded=function(){return!!(window._hublo_&&typeof window._hublo_.setup==="function")}},{"analytics.js-integration":83}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":83,"global-queue":167,"convert-dates":173}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');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(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":83,alias:172}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.options.events;var event=track.event();var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";if(!has.call(events,event))return;event=events[event];if(event!="sale"){push("trackEvent",event,value,eventId)}}},{"analytics.js-integration":83,"global-queue":167,facade:124,is:86}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"analytics.js-integration":83,"global-queue":167,alias:172,clone:171}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};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();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});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;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":83,"convert-dates":173,defaults:166,"is-email":162,"load-script":120,"is-empty":118,alias:172,each:4,when:123,is:86}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};var options=this.options;if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});props.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});props.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});props.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});props.referrer_url=document.referrer;props.page_url=document.location.href}props.keen={timestamp:identify.timestamp(),addons:addons};this.client.setGlobalProperties(function(){return props})};Keen.prototype.track=function(track){this.client.addEvent(track.event(),track.properties())}},{"analytics.js-integration":83}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":83,indexof:109,is:86}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">'); 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);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};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)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));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)})})};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}},{"analytics.js-integration":83,"global-queue":167,facade:124,alias:172,batch:177,each:4,is:86}],177:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=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])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};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;if(!fns.length)return cb(null,results);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)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:178}],178:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};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};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":83,"global-queue":167,"next-tick":97,alias:172}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"analytics.js-integration":83}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":83,clone:171,each:4,facade:124,when:123}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().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).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":83,facade:124,"use-https":85}],54:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};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(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":83,alias:172}],55:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").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).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};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(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};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();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}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)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};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}},{alias:172,clone:171,"convert-dates":173,"analytics.js-integration":83,is:86,"to-iso-string":170,indexof:109,"obj-case":138,some:179}],179:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],56:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};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};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}},{"analytics.js-integration":83,bind:95,when:123,is:86}],57:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":167,"analytics.js-integration":83,each:4}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":83,"use-https":85,each:4,is:86}],59:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":83,"global-queue":167}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");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);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};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();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":83,"use-https":85,"next-tick":97}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;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});this.analytics.identify(traits)}},{"analytics.js-integration":83,"global-queue":167,callback:88,"next-tick":97,bind:95,each:4}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"analytics.js-integration":83}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":83,"global-queue":167,"load-date":168}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"analytics.js-integration":83,"global-queue":167,each:4}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};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})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};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)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":83,"convert-dates":173,"global-queue":167,alias:172}],66:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};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)};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}))}},{"analytics.js-integration":83,"global-queue":167,facade:124,bind:95,when:123}],67:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};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};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};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};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};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",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};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(".")}},{"global-queue":167,"analytics.js-integration":83,"use-https":85}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);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(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;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}})}},{"analytics.js-integration":83,extend:122,is:86}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var 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()}},{"analytics.js-integration":83}],70:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":83,is:86}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":83,is:86}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":83,bind:95,when:123}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":83,slug:93,"global-queue":167}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){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(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};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);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};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)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};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)}}},{"analytics.js-integration":83,alias:172,clone:171}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":83,each:4}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_uc");var Usercycle=module.exports=integration("USERcycle").assumesPageview().global("_uc").option("key","").tag('<script src="//api.usercycle.com/javascripts/track.js">');Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load(this.ready)};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}},{"analytics.js-integration":83,"global-queue":167}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().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)").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).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});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(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};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"})}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"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":83,"global-queue":167,"convert-dates":173,"to-unix-timestamp":180,alias:172,clone:171}],180:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"analytics.js-integration":83,"global-queue":167,"component/cookie":181}],181:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;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()}};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}function all(){return parse(document.cookie)}function get(name){return all()[name]}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}},{}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}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}},{"analytics.js-integration":83,"next-tick":97,each:4}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":83,"use-https":85}],81:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');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(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":83,"to-snake-case":84,"is-email":162,extend:122,each:4,type:7}],82:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":83,"next-tick":97,bind:95,when:123}],3:[function(require,module,exports){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;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};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};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};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();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",message(Identify,{options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};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();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",message(Group,{options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};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",message(Track,{properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");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};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");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()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};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",message(Page,{properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};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",message(Alias,{options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};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};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};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};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){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};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}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)}function message(Type,msg){var ctx=msg.options||{};if(ctx.timestamp||ctx.integrations||ctx.context||ctx.anonymousId){msg=defaults(ctx,msg);delete msg.options}return new Type(msg)}},{after:105,bind:182,callback:88,canonical:175,clone:89,"./cookie":183,debug:184,defaults:91,each:4,emitter:102,"./group":185,is:86,"is-email":162,"is-meta":186,"new-date":139,event:187,prevent:188,querystring:189,object:174,"./store":190,url:176,"./user":191,facade:124}],182:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;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}},{bind:95,"bind-all":96}],183:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");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");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:184,bind:182,cookie:181,clone:89,defaults:91,json:192,"top-domain":193}],184:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":194,"./debug":195}],194:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,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"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],195:[function(require,module,exports){module.exports=debug;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);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];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+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,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"};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};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],192:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":196}],196:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){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){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){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}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{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}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={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}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){var j;function walk(holder,key){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)}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)})}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,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],193:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:176}],185:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:184,"./entity":197,inherit:198,bind:182}],197:[function(require,module,exports){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");module.exports=Entity;function Entity(options){this.protocol=window.location.protocol;this.options(options)}Entity.prototype.storage=function(){return"file:"==this.protocol||"chrome-extension:"==this.protocol?store:cookie};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var storage=this.storage();var ret=this._options.persist?storage.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){var storage=this.storage();if(this._options.persist){storage.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=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()};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};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"isodate-traverse":134,defaults:91,"./cookie":183,"./store":190,extend:122,clone:89}],190:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}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};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:182,defaults:91,"store.js":199}],199:[function(require,module,exports){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}};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;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){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}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},{json:192}],198:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],186:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;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}},{}],187:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],188:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],189:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");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};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("&")}},{trim:163,type:7}],191:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};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};module.exports=bind.all(new User);module.exports.User=User},{debug:184,"./entity":197,inherit:198,bind:182,"./cookie":183}],5:[function(require,module,exports){module.exports="2.3.17"},{}]},{},{1:"analytics"});
ajax/libs/forerunnerdb/1.3.769/fdb-core.js
menuka94/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'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[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":25,"./Shared":28}],3:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; 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; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = 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 }; module.exports = checksum; },{}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, 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, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; 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'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * 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. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ 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. * @param {Function=} callback A callback method to call once the * operation has completed. * @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._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, 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: 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 by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(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'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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 {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } 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 hash string jString = this.hash(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!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off 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.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * 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 * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @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.call(this); } 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, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } 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. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @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. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { 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) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); 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. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base 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 via 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.call(this, 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.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, 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.call(this, 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ 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); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ 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.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); 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'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([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, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, 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, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // 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), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * 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 {String} search The string to search for. Case sensitive. * @param {Object=} 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.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; 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 || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // 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); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } 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) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); 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'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // 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); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * 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); } };*/ /** * 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 }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @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); }; /** * 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 {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], 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 (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, 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) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), 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(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * 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) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } 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('Collection.prototype.collateAdd', { /** * 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.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } 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.dataSet); } 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('Db.prototype.collection', { /** * 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 * @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; },{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[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 (val) { 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; /** * 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":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, 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'); Checksum = _dereq_('./Checksum.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.Checksum = Checksum; /** * 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; },{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[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; },{}],8:[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); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ 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 lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/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; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[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; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[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; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":25,"./Shared":28}],11:[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":28}],12:[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":23,"./Shared":28}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[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 = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ 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); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ 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); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); 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, dataCopy[index], 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!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[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, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * 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 && data !== "") { 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 JSON.parse(data, serialiser.reviver()); }, /** * 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; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * 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 'ForerunnerDB ' + 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'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":24,"./Serialiser":27}],16:[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; },{}],17:[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":24}],18:[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; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } 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' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // 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' || sourceType === 'null' || testType === 'null') { // Number or null 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 { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } 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 { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } 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 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 || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } 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; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.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)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.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 (resultKeyName === '$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 = docArr[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 { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions 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 = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } 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] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],19:[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; },{}],20:[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; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * 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 {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} 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) { self.triggerStack = {}; // 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; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } 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._ignoreTriggers && 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, typeName, phaseName; if (!self._ignoreTriggers && 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 (self.debug()) { 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 "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // 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":24}],22:[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 + '" to val "' + val + '"'); } }, /** * 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; },{}],23:[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":25,"./Shared":28}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } 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, overloadName; // 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); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" 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 = ['array', '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; },{}],25:[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":28}],26:[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":28}],27:[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 () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],28:[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.769', modules: {}, plugins: {}, index: {}, _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]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @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. */ '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); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ '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":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
ajax/libs/mobx/4.9.3/mobx.umd.min.js
sufuf3/cdnjs
/** MobX - (c) Michel Weststrate 2015, 2016 - MIT Licensed */ !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.mobx=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||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,n){(function(e,t){"use strict";function r(e,t){function n(){this.constructor=e}fn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function o(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function i(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(o(arguments[t]));return e}function a(){return"undefined"!=typeof window?window:t}function s(){return++Hn.mobxGuid}function u(e){throw c(!1,e),"X"}function c(e,t){if(!e)throw new Error("[mobx] "+(t||hn))}function l(e,t){return!1}function f(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function p(e){var t=[];return e.forEach(function(e){-1===t.indexOf(e)&&t.push(e)}),t}function h(e){return null!==e&&"object"==typeof e}function d(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function v(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){}function m(e,t){var n="isMobX"+e;return t.prototype[n]=!0,function(e){return h(e)&&!0===e[n]}}function g(e,t){return"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t)}function w(e){return Array.isArray(e)||Wt(e)}function _(e){return void 0!==a().Map&&e instanceof a().Map}function O(e){return e instanceof Set}function S(e){return d(e)?Object.keys(e):Array.isArray(e)?e.map(function(e){return o(e,1)[0]}):_(e)||ur(e)?x(e.keys()):u("Cannot get keys from '"+e+"'")}function x(e){for(var t=[];;){var n=e.next();if(n.done)break;t.push(n.value)}return t}function A(){return"function"==typeof Symbol&&Symbol.toPrimitive||"@@toPrimitive"}function E(e){return null===e?null:"object"==typeof e?""+e:e}function D(){return"function"==typeof Symbol&&Symbol.iterator||"@@iterator"}function j(e,t){y(e,D(),t)}function T(e){return e[D()]=I,e}function k(){return"function"==typeof Symbol&&Symbol.toStringTag||"@@toStringTag"}function I(){return this}function C(e,t,n){void 0===t&&(t=yn),void 0===n&&(n=yn);var r=new bn(e);return Ye(r,t),Fe(r,n),r}function V(e,t){return e===t}function N(e,t){return an(e,t)}function R(e,t){return g(e,t)||V(e,t)}function L(e,t){var n=t?wn:_n;return n[e]||(n[e]={configurable:!0,enumerable:t,get:function(){return P(this),this[e]},set:function(t){P(this),this[e]=t}})}function P(e){if(!0!==e.__mobxDidRunLazyInitializers){var t=e.__mobxDecorators;if(t){v(e,"__mobxDidRunLazyInitializers",!0);for(var n in t){var r=t[n];r.propertyCreator(e,r.prop,r.descriptor,r.decoratorTarget,r.decoratorArguments)}}}}function B(e,t){return function(){var n,r=function(r,o,i,a){if(!0===a)return t(r,o,i,r,n),null;if(!Object.prototype.hasOwnProperty.call(r,"__mobxDecorators")){var s=r.__mobxDecorators;v(r,"__mobxDecorators",pn({},s))}return r.__mobxDecorators[o]={prop:o,propertyCreator:t,descriptor:i,decoratorTarget:r,decoratorArguments:n},L(o,e)};return $(arguments)?(n=dn,r.apply(null,arguments)):(n=Array.prototype.slice.call(arguments),r)}}function $(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]||4===e.length&&!0===e[3]}function M(e,t,n){return bt(e)?e:Array.isArray(e)?Tn.array(e,{name:n}):d(e)?Tn.object(e,void 0,{name:n}):_(e)?Tn.map(e,{name:n}):O(e)?Tn.set(e,{name:n}):e}function U(e,t,n){return void 0===e||null===e?e:tn(e)||Wt(e)||ur(e)||fr(e)?e:Array.isArray(e)?Tn.array(e,{name:n,deep:!1}):d(e)?Tn.object(e,void 0,{name:n,deep:!1}):_(e)?Tn.map(e,{name:n,deep:!1}):O(e)?Tn.set(e,{name:n,deep:!1}):u(!1)}function G(e){return e}function H(e,t,n){return an(e,t)?t:e}function q(t){var n=B(!0,function(e,n,r,o,i){Xt(e,n,r?r.initializer?r.initializer.call(e):r.value:void 0,t)}),r=(void 0!==e&&e.env,n);return r.enhancer=t,r}function z(e){return null===e||void 0===e?On:"string"==typeof e?{name:e,deep:!0}:e}function K(e){return e.defaultDecorator?e.defaultDecorator.enhancer:!1===e.deep?G:M}function W(e,t,n){if("string"==typeof arguments[1])return xn.apply(null,arguments);if(bt(e))return e;var r=d(e)?Tn.object(e,t,n):Array.isArray(e)?Tn.array(e,t):_(e)?Tn.map(e,t):O(e)?Tn.set(e,t):e;if(r!==e)return r;u(!1)}function J(e){u("Expected one or two arguments to observable."+e+". Did you accidentally try to use observable."+e+" as decorator?")}function X(e,t){var n=function(){return Y(e,t,this,arguments)};return n.isMobxAction=!0,n}function Y(e,t,n,r){var o=F(e,t,n,r),i=!0;try{var a=t.apply(n,r);return i=!1,a}finally{i?(Hn.suppressReactionErrors=i,Q(o),Hn.suppressReactionErrors=!1):Q(o)}}function F(e,t,n,r){var o=Ne()&&!!e,i=0;if(o){i=Date.now();var a=r&&r.length||0,s=new Array(a);if(a>0)for(var u=0;u<a;u++)s[u]=r[u];Le({type:"action",name:e,object:n,arguments:s})}var c=fe();return Oe(),{prevDerivation:c,prevAllowStateChanges:ee(!0),notifySpy:o,startTime:i}}function Q(e){te(e.prevAllowStateChanges),Se(),pe(e.prevDerivation),e.notifySpy&&Pe({time:Date.now()-e.startTime})}function Z(e,t){var n,r=ee(e);try{n=t()}finally{te(r)}return n}function ee(e){var t=Hn.allowStateChanges;return Hn.allowStateChanges=e,t}function te(e){Hn.allowStateChanges=e}function ne(e){var t=Hn.computationDepth;Hn.computationDepth=0;var n;try{n=e()}finally{Hn.computationDepth=t}return n}function re(e){return e instanceof Bn}function oe(e){switch(e.dependenciesState){case n.IDerivationState.UP_TO_DATE:return!1;case n.IDerivationState.NOT_TRACKING:case n.IDerivationState.STALE:return!0;case n.IDerivationState.POSSIBLY_STALE:for(var t=fe(),r=e.observing,o=r.length,i=0;i<o;i++){var a=r[i];if(Ln(a)){if(Hn.disableErrorBoundaries)a.get();else try{a.get()}catch(e){return pe(t),!0}if(e.dependenciesState===n.IDerivationState.STALE)return pe(t),!0}}return he(e),pe(t),!1}}function ie(){return null!==Hn.trackingDerivation}function ae(e){var t=e.observers.length>0;Hn.computationDepth>0&&t&&u(!1),Hn.allowStateChanges||!t&&"strict"!==Hn.enforceActions||u(!1)}function se(e,t,n){he(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++Hn.runId;var r=Hn.trackingDerivation;Hn.trackingDerivation=e;var o;if(!0===Hn.disableErrorBoundaries)o=t.call(n);else try{o=t.call(n)}catch(e){o=new Bn(e)}return Hn.trackingDerivation=r,ue(e),o}function ue(e){for(var t=e.observing,r=e.observing=e.newObserving,o=n.IDerivationState.UP_TO_DATE,i=0,a=e.unboundDepsCount,s=0;s<a;s++){var u=r[s];0===u.diffValue&&(u.diffValue=1,i!==s&&(r[i]=u),i++),u.dependenciesState>o&&(o=u.dependenciesState)}for(r.length=i,e.newObserving=null,a=t.length;a--;){var u=t[a];0===u.diffValue&&we(u,e),u.diffValue=0}for(;i--;){var u=r[i];1===u.diffValue&&(u.diffValue=0,ge(u,e))}o!==n.IDerivationState.UP_TO_DATE&&(e.dependenciesState=o,e.onBecomeStale())}function ce(e){var t=e.observing;e.observing=[];for(var r=t.length;r--;)we(t[r],e);e.dependenciesState=n.IDerivationState.NOT_TRACKING}function le(e){var t=fe(),n=e();return pe(t),n}function fe(){var e=Hn.trackingDerivation;return Hn.trackingDerivation=null,e}function pe(e){Hn.trackingDerivation=e}function he(e){if(e.dependenciesState!==n.IDerivationState.UP_TO_DATE){e.dependenciesState=n.IDerivationState.UP_TO_DATE;for(var t=e.observing,r=t.length;r--;)t[r].lowestObserverState=n.IDerivationState.UP_TO_DATE}}function de(){(Hn.pendingReactions.length||Hn.inBatch||Hn.isRunningReactions)&&u("isolateGlobalState should be called before MobX is running any reactions"),Gn=!0,Un&&(0==--a().__mobxInstanceCount&&(a().__mobxGlobals=void 0),Hn=new Mn)}function ve(){return Hn}function ye(){var e=new Mn;for(var t in e)-1===$n.indexOf(t)&&(Hn[t]=e[t]);Hn.allowStateChanges=!Hn.enforceActions}function be(e){return e.observers&&e.observers.length>0}function me(e){return e.observers}function ge(e,t){var n=e.observers.length;n&&(e.observersIndexes[t.__mapid]=n),e.observers[n]=t,e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function we(e,t){if(1===e.observers.length)e.observers.length=0,_e(e);else{var n=e.observers,r=e.observersIndexes,o=n.pop();if(o!==t){var i=r[t.__mapid]||0;i?r[o.__mapid]=i:delete r[o.__mapid],n[i]=o}delete r[t.__mapid]}}function _e(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,Hn.pendingUnobservations.push(e))}function Oe(){Hn.inBatch++}function Se(){if(0==--Hn.inBatch){Ie();for(var e=Hn.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,0===n.observers.length&&(n.isBeingObserved&&(n.isBeingObserved=!1,n.onBecomeUnobserved()),n instanceof Rn&&n.suspend())}Hn.pendingUnobservations=[]}}function xe(e){var t=Hn.trackingDerivation;return null!==t?(t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e,e.isBeingObserved||(e.isBeingObserved=!0,e.onBecomeObserved())),!0):(0===e.observers.length&&Hn.inBatch>0&&_e(e),!1)}function Ae(e){if(e.lowestObserverState!==n.IDerivationState.STALE){e.lowestObserverState=n.IDerivationState.STALE;for(var t=e.observers,r=t.length;r--;){var o=t[r];o.dependenciesState===n.IDerivationState.UP_TO_DATE&&(o.isTracing!==Pn.NONE&&je(o,e),o.onBecomeStale()),o.dependenciesState=n.IDerivationState.STALE}}}function Ee(e){if(e.lowestObserverState!==n.IDerivationState.STALE){e.lowestObserverState=n.IDerivationState.STALE;for(var t=e.observers,r=t.length;r--;){var o=t[r];o.dependenciesState===n.IDerivationState.POSSIBLY_STALE?o.dependenciesState=n.IDerivationState.STALE:o.dependenciesState===n.IDerivationState.UP_TO_DATE&&(e.lowestObserverState=n.IDerivationState.UP_TO_DATE)}}}function De(e){if(e.lowestObserverState===n.IDerivationState.UP_TO_DATE){e.lowestObserverState=n.IDerivationState.POSSIBLY_STALE;for(var t=e.observers,r=t.length;r--;){var o=t[r];o.dependenciesState===n.IDerivationState.UP_TO_DATE&&(o.dependenciesState=n.IDerivationState.POSSIBLY_STALE,o.isTracing!==Pn.NONE&&je(o,e),o.onBecomeStale())}}}function je(e,t){if(console.log("[mobx.trace] '"+e.name+"' is invalidated due to a change in: '"+t.name+"'"),e.isTracing===Pn.BREAK){var n=[];Te(rt(e),n,1),new Function("debugger;\n/*\nTracing '"+e.name+"'\n\nYou are entering this break point because derivation '"+e.name+"' is being traced and '"+t.name+"' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n"+(e instanceof Rn?e.derivation.toString().replace(/[*]\//g,"/"):"")+"\n\nThe dependencies for this derivation are:\n\n"+n.join("\n")+"\n*/\n ")()}}function Te(e,t,n){if(t.length>=1e3)return void t.push("(and many more)");t.push(""+new Array(n).join("\t")+e.name),e.dependencies&&e.dependencies.forEach(function(e){return Te(e,t,n+1)})}function ke(e){return Hn.globalReactionErrorHandlers.push(e),function(){var t=Hn.globalReactionErrorHandlers.indexOf(e);t>=0&&Hn.globalReactionErrorHandlers.splice(t,1)}}function Ie(){Hn.inBatch>0||Hn.isRunningReactions||Kn(Ce)}function Ce(){Hn.isRunningReactions=!0;for(var e=Hn.pendingReactions,t=0;e.length>0;){++t===zn&&(console.error("Reaction doesn't converge to a stable state after "+zn+" iterations. Probably there is a cycle in the reactive function: "+e[0]),e.splice(0));for(var n=e.splice(0),r=0,o=n.length;r<o;r++)n[r].runReaction()}Hn.isRunningReactions=!1}function Ve(e){var t=Kn;Kn=function(n){return e(function(){return t(n)})}}function Ne(){return!!Hn.spyListeners.length}function Re(e){if(Hn.spyListeners.length)for(var t=Hn.spyListeners,n=0,r=t.length;n<r;n++)t[n](e)}function Le(e){Re(pn({},e,{spyReportStart:!0}))}function Pe(e){Re(e?pn({},e,{spyReportEnd:!0}):Jn)}function Be(e){return Hn.spyListeners.push(e),f(function(){Hn.spyListeners=Hn.spyListeners.filter(function(t){return t!==e})})}function $e(){u(!1)}function Me(e){return function(t,n,r){if(r){if(r.value)return{value:X(e,r.value),enumerable:!1,configurable:!0,writable:!0};var o=r.initializer;return{enumerable:!1,configurable:!0,writable:!0,initializer:function(){return X(e,o.call(this))}}}return Ue(e).apply(this,arguments)}}function Ue(e){return function(t,n,r){Object.defineProperty(t,n,{configurable:!0,enumerable:!1,get:function(){},set:function(t){v(this,n,Xn(e,t))}})}}function Ge(e,t,n,r){return!0===r?(ze(e,t,n.value),null):n?{configurable:!0,enumerable:!1,get:function(){return ze(this,t,n.value||n.initializer.call(this)),this[t]},set:$e}:{enumerable:!1,configurable:!0,set:function(e){ze(this,t,e)},get:function(){}}}function He(e,t){var n="string"==typeof e?e:e.name||"<unnamed action>",r="function"==typeof e?e:t;return Y(n,r,this,void 0)}function qe(e){return"function"==typeof e&&!0===e.isMobxAction}function ze(e,t,n){v(e,t,X(t,n.bind(e)))}function Ke(e,t){function n(){e(r)}void 0===t&&(t=vn);var r,o=t&&t.name||e.name||"Autorun@"+s(),i=!t.scheduler&&!t.delay;if(i)r=new qn(o,function(){this.track(n)},t.onError);else{var a=We(t),u=!1;r=new qn(o,function(){u||(u=!0,a(function(){u=!1,r.isDisposed||r.track(n)}))},t.onError)}return r.schedule(),r.getDisposer()}function We(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:Yn}function Je(e,t,n){function r(){if(p=!1,!d.isDisposed){var t=!1;d.track(function(){var n=e(d);t=f||!h(o,n),o=n}),f&&n.fireImmediately&&a(o,d),f||!0!==t||a(o,d),f&&(f=!1)}}void 0===n&&(n=vn),"boolean"==typeof n&&(n={fireImmediately:n},l("Using fireImmediately as argument is deprecated. Use '{ fireImmediately: true }' instead"));var o,i=n.name||"Reaction@"+s(),a=Xn(i,n.onError?Xe(n.onError,t):t),u=!n.scheduler&&!n.delay,c=We(n),f=!0,p=!1,h=n.compareStructural?gn.structural:n.equals||gn.default,d=new qn(i,function(){f||u?r():p||(p=!0,c(r))},n.onError);return d.schedule(),d.getDisposer()}function Xe(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Ye(e,t,n){return Qe("onBecomeObserved",e,t,n)}function Fe(e,t,n){return Qe("onBecomeUnobserved",e,t,n)}function Qe(e,t,n,r){var o="string"==typeof n?nn(t,n):nn(t),i="string"==typeof n?r:n,a=o[e];return"function"!=typeof a?u(!1):(o[e]=function(){a.call(this),i.call(this)},function(){o[e]=a})}function Ze(e){var t=e.enforceActions,n=e.computedRequiresReaction,r=e.disableErrorBoundaries,o=e.arrayBuffer,i=e.reactionScheduler;if(!0===e.isolateGlobalState&&de(),void 0!==t){"boolean"!=typeof t&&"strict"!==t||l("Deprecated value for 'enforceActions', use 'false' => '\"never\"', 'true' => '\"observed\"', '\"strict\"' => \"'always'\" instead");var a=void 0;switch(t){case!0:case"observed":a=!0;break;case!1:case"never":a=!1;break;case"strict":case"always":a="strict";break;default:u("Invalid value for 'enforceActions': '"+t+"', expected 'never', 'always' or 'observed'")}Hn.enforceActions=a,Hn.allowStateChanges=!0!==a&&"strict"!==a}void 0!==n&&(Hn.computedRequiresReaction=!!n),void 0!==r&&(!0===r&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors if this is on."),Hn.disableErrorBoundaries=!!r),"number"==typeof o&&Kt(o),i&&Ve(i)}function et(e,t){var n="function"==typeof e?e.prototype:e;for(var r in t)!function(e){var r=t[e];Array.isArray(r)||(r=[r]);var o=Object.getOwnPropertyDescriptor(n,e),i=r.reduce(function(t,r){return r(n,e,t)},o);i&&Object.defineProperty(n,e,i)}(r);return e}function tt(e,t,n){return l("'extendShallowObservable' is deprecated, use 'extendObservable(target, props, { deep: false })' instead"),nt(e,t,n,Sn)}function nt(e,t,n,r){var o;r=z(r);var i=r.defaultDecorator||(!1===r.deep?En:xn);P(e),Jt(e,r.name,i.enhancer),Oe();try{for(var o in t){var a=Object.getOwnPropertyDescriptor(t,o),s=n&&o in n?n[o]:a.get?kn:i,u=s(e,o,a,!0);u&&Object.defineProperty(e,o,u)}}finally{Se()}return e}function rt(e,t){return ot(nn(e,t))}function ot(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=p(e.observing).map(ot)),t}function it(e,t){return at(nn(e,t))}function at(e){var t={name:e.name};return be(e)&&(t.observers=me(e).map(at)),t}function st(e){1!==arguments.length&&u("Flow expects one 1 argument and cannot be used as decorator");var t=e.name||"<unnamed flow>";return function(){var n,r=this,o=arguments,i=++Fn,a=Xn(t+" - runid: "+i+" - init",e).apply(r,o),s=void 0,u=new Promise(function(e,r){function o(e){s=void 0;var n;try{n=Xn(t+" - runid: "+i+" - yield "+l++,a.next).call(a,e)}catch(e){return r(e)}c(n)}function u(e){s=void 0;var n;try{n=Xn(t+" - runid: "+i+" - yield "+l++,a.throw).call(a,e)}catch(e){return r(e)}c(n)}function c(t){return t&&"function"==typeof t.then?void t.then(c,r):t.done?e(t.value):(s=Promise.resolve(t.value),s.then(o,u))}var l=0;n=r,o(void 0)});return u.cancel=Xn(t+" - runid: "+i+" - cancel",function(){try{s&&ut(s);var e=a.return(),t=Promise.resolve(e.value);t.then(yn,yn),ut(t),n(new Error("FLOW_CANCELLED"))}catch(e){n(e)}}),u}}function ut(e){"function"==typeof e.cancel&&e.cancel()}function ct(e,t,n){var r;if(ur(e)||Wt(e)||Nn(e))r=rn(e);else{if(!tn(e))return u(!1);if("string"!=typeof t)return u(!1);r=rn(e,t)}return void 0!==r.dehancer?u(!1):(r.dehancer="function"==typeof t?t:n,function(){r.dehancer=void 0})}function lt(e,t,n){return"function"==typeof n?pt(e,t,n):ft(e,t)}function ft(e,t){return rn(e).intercept(t)}function pt(e,t,n){return rn(e,t).intercept(n)}function ht(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(!1===tn(e))return!1;if(!e.$mobx.values[t])return!1;var n=nn(e,t);return Ln(n)}return Ln(e)}function dt(e){return arguments.length>1?u(!1):ht(e)}function vt(e,t){return"string"!=typeof t?u(!1):ht(e,t)}function yt(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(tn(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return tn(e)||!!e.$mobx||mn(e)||Wn(e)||Ln(e)}function bt(e){return 1!==arguments.length&&u(!1),yt(e)}function mt(e,t){return"string"!=typeof t?u(!1):yt(e,t)}function gt(e){return tn(e)?e.$mobx.getKeys():ur(e)?e._keys.slice():fr(e)?x(e.keys()):Wt(e)?e.map(function(e,t){return t}):u(!1)}function wt(e){return tn(e)?gt(e).map(function(t){return e[t]}):ur(e)?gt(e).map(function(t){return e.get(t)}):fr(e)?x(e.values()):Wt(e)?e.slice():u(!1)}function _t(e){return tn(e)?gt(e).map(function(t){return[t,e[t]]}):ur(e)?gt(e).map(function(t){return[t,e.get(t)]}):fr(e)?x(e.entries()):Wt(e)?e.map(function(e,t){return[t,e]}):u(!1)}function Ot(e,t,n){if(2!==arguments.length)if(tn(e)){var r=e.$mobx,o=r.values[t];o?r.write(e,t,n):Xt(e,t,n,r.defaultEnhancer)}else if(ur(e))e.set(t,n);else{if(!Wt(e))return u(!1);"number"!=typeof t&&(t=parseInt(t,10)),c(t>=0,"Not a valid index: '"+t+"'"),Oe(),t>=e.length&&(e.length=t+1),e[t]=n,Se()}else{Oe();var i=t;try{for(var a in i)Ot(e,a,i[a])}finally{Se()}}}function St(e,t){if(tn(e))e.$mobx.remove(t);else if(ur(e))e.delete(t);else if(fr(e))e.delete(t);else{if(!Wt(e))return u(!1);"number"!=typeof t&&(t=parseInt(t,10)),c(t>=0,"Not a valid index: '"+t+"'"),e.splice(t,1)}}function xt(e,t){if(tn(e)){var n=rn(e);return n.getKeys(),!!n.values[t]}return ur(e)?e.has(t):fr(e)?e.has(t):Wt(e)?t>=0&&t<e.length:u(!1)}function At(e,t){if(xt(e,t))return tn(e)?e[t]:ur(e)?e.get(t):Wt(e)?e[t]:u(!1)}function Et(e,t,n,r){return"function"==typeof n?jt(e,t,n,r):Dt(e,t,n)}function Dt(e,t,n){return rn(e).observe(t,n)}function jt(e,t,n,r){return rn(e,t).observe(n,r)}function Tt(e,t,n,r){return r.detectCycles&&e.set(t,n),n}function kt(e,t,n){if(!t.recurseEverything&&!bt(e))return e;if("object"!=typeof e)return e;if(null===e)return null;if(e instanceof Date)return e;if(Nn(e))return kt(e.get(),t,n);if(bt(e)&&gt(e),!0===t.detectCycles&&null!==e&&n.has(e))return n.get(e);if(Wt(e)||Array.isArray(e)){var r=Tt(n,e,[],t),o=e.map(function(e){return kt(e,t,n)});r.length=o.length;for(var i=0,a=o.length;i<a;i++)r[i]=o[i];return r}if(fr(e)||Object.getPrototypeOf(e)===Set.prototype){if(!1===t.exportMapsAsObjects){var s=Tt(n,e,new Set,t);return e.forEach(function(e){s.add(kt(e,t,n))}),s}var u=Tt(n,e,[],t);return e.forEach(function(e){u.push(kt(e,t,n))}),u}if(ur(e)||Object.getPrototypeOf(e)===Map.prototype){if(!1===t.exportMapsAsObjects){var c=Tt(n,e,new Map,t);return e.forEach(function(e,r){c.set(r,kt(e,t,n))}),c}var l=Tt(n,e,{},t);return e.forEach(function(e,r){l[r]=kt(e,t,n)}),l}var f=Tt(n,e,{},t);for(var p in e)f[p]=kt(e[p],t,n);return f}function It(e,t){"boolean"==typeof t&&(t={detectCycles:t}),t||(t=Qn),t.detectCycles=void 0===t.detectCycles?!0===t.recurseEverything:!0===t.detectCycles;var n;return t.detectCycles&&(n=new Map),kt(e,t,n)}function Ct(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=!1;"boolean"==typeof e[e.length-1]&&(n=e.pop());var r=Vt(e);if(!r)return u(!1);r.isTracing===Pn.NONE&&console.log("[mobx.trace] '"+r.name+"' tracing enabled"),r.isTracing=n?Pn.BREAK:Pn.LOG}function Vt(e){switch(e.length){case 0:return Hn.trackingDerivation;case 1:return nn(e[0]);case 2:return nn(e[0],e[1])}}function Nt(e,t){void 0===t&&(t=void 0),Oe();try{return e.apply(t)}finally{Se()}}function Rt(e,t,n){return 1===arguments.length||t&&"object"==typeof t?Pt(e,t):Lt(e,t,n||{})}function Lt(e,t,n){var r;"number"==typeof n.timeout&&(r=setTimeout(function(){if(!i.$mobx.isDisposed){i();var e=new Error("WHEN_TIMEOUT");if(!n.onError)throw e;n.onError(e)}},n.timeout)),n.name=n.name||"When@"+s();var o=X(n.name+"-effect",t),i=Ke(function(t){e()&&(t.dispose(),r&&clearTimeout(r),o())},n);return i}function Pt(e,t){var n,r=new Promise(function(r,o){var i=Lt(e,r,pn({},t,{onError:o}));n=function(){i(),o("WHEN_CANCELLED")}});return r.cancel=n,r}function Bt(e){return void 0!==e.interceptors&&e.interceptors.length>0}function $t(e,t){var n=e.interceptors||(e.interceptors=[]);return n.push(t),f(function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)})}function Mt(e,t){var n=fe();try{var r=e.interceptors;if(r)for(var o=0,i=r.length;o<i&&(t=r[o](t),c(!t||t.type,"Intercept handlers should return nothing or a change object"),t);o++);return t}finally{pe(n)}}function Ut(e){return void 0!==e.changeListeners&&e.changeListeners.length>0}function Gt(e,t){var n=e.changeListeners||(e.changeListeners=[]);return n.push(t),f(function(){var e=n.indexOf(t);-1!==e&&n.splice(e,1)})}function Ht(e,t){var n=fe(),r=e.changeListeners;if(r){r=r.slice();for(var o=0,i=r.length;o<i;o++)r[o](t);pe(n)}}function qt(e){return{enumerable:!1,configurable:!1,get:function(){return this.get(e)},set:function(t){this.set(e,t)}}}function zt(e){Object.defineProperty(rr.prototype,""+e,qt(e))}function Kt(e){for(var t=er;t<e;t++)zt(t);er=e}function Wt(e){return h(e)&&ir(e.$mobx)}function Jt(e,t,n){void 0===t&&(t=""),void 0===n&&(n=M);var r=e.$mobx;return r||(d(e)||(t=(e.constructor.name||"ObservableObject")+"@"+s()),t||(t="ObservableObject@"+s()),r=new pr(e,t,n),y(e,"$mobx",r),r)}function Xt(e,t,n,r){var o=Jt(e);if(b(e,t),Bt(o)){var i=Mt(o,{object:e,name:t,type:"add",newValue:n});if(!i)return;n=i.newValue}n=(o.values[t]=new Vn(n,r,o.name+"."+t,!1)).value,Object.defineProperty(e,t,Ft(t)),o.keys&&o.keys.push(t),en(o,e,t,n)}function Yt(e,t,n){var r=Jt(e);n.name=r.name+"."+t,n.context=e,r.values[t]=new Rn(n),Object.defineProperty(e,t,Zt(t))}function Ft(e){return hr[e]||(hr[e]={configurable:!0,enumerable:!0,get:function(){return this.$mobx.read(this,e)},set:function(t){this.$mobx.write(this,e,t)}})}function Qt(e){var t=e.$mobx;return t||(P(e),e.$mobx)}function Zt(e){return dr[e]||(dr[e]={configurable:!1,enumerable:!1,get:function(){return Qt(this).read(this,e)},set:function(t){Qt(this).write(this,e,t)}})}function en(e,t,n,r){var o=Ut(e),i=Ne(),a=o||i?{type:"add",object:t,name:n,newValue:r}:null;i&&Le(pn({},a,{name:e.name,key:n})),o&&Ht(e,a),i&&Pe()}function tn(e){return!!h(e)&&(P(e),vr(e.$mobx))}function nn(e,t){if("object"==typeof e&&null!==e){if(Wt(e))return void 0!==t&&u(!1),e.$mobx.atom;if(fr(e))return e.$mobx;if(ur(e)){var n=e;if(void 0===t)return nn(n._keys);var r=n._data.get(t)||n._hasMap.get(t);return r||u(!1),r}if(P(e),t&&!e.$mobx&&e[t],tn(e)){if(!t)return u(!1);var r=e.$mobx.values[t];return r||u(!1),r}if(mn(e)||Ln(e)||Wn(e))return e}else if("function"==typeof e&&Wn(e.$mobx))return e.$mobx;return u(!1)}function rn(e,t){return e||u("Expecting some object"),void 0!==t?rn(nn(e,t)):mn(e)||Ln(e)||Wn(e)?e:ur(e)||fr(e)?e:(P(e),e.$mobx?e.$mobx:void u(!1))}function on(e,t){var n;return n=void 0!==t?nn(e,t):tn(e)||ur(e)||fr(e)?rn(e):nn(e),n.name}function an(e,t){return sn(e,t)}function sn(e,t,n,r){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!==e)return t!==t;var o=typeof e;return("function"===o||"object"===o||"object"==typeof t)&&un(e,t,n,r)}function un(e,t,n,r){e=cn(e),t=cn(t);var o=yr.call(e);if(o!==yr.call(t))return!1;switch(o){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Symbol]":return"undefined"!=typeof Symbol&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t)}var i="[object Array]"===o;if(!i){if("object"!=typeof e||"object"!=typeof t)return!1;var a=e.constructor,s=t.constructor;if(a!==s&&!("function"==typeof a&&a instanceof a&&"function"==typeof s&&s instanceof s)&&"constructor"in e&&"constructor"in t)return!1}n=n||[],r=r||[];for(var u=n.length;u--;)if(n[u]===e)return r[u]===t;if(n.push(e),r.push(t),i){if((u=e.length)!==t.length)return!1;for(;u--;)if(!sn(e[u],t[u],n,r))return!1}else{var c=Object.keys(e),l=void 0;if(u=c.length,Object.keys(t).length!==u)return!1;for(;u--;)if(l=c[u],!ln(t,l)||!sn(e[l],t[l],n,r))return!1}return n.pop(),r.pop(),!0}function cn(e){return Wt(e)?e.peek():_(e)||ur(e)?x(e.entries()):O(e)||fr(e)?x(e.entries()):e}function ln(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Object.defineProperty(n,"__esModule",{value:!0});var fn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},pn=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},hn="An invariant failed, however the error is obfuscated because this is an production build.",dn=[];Object.freeze(dn);var vn={};Object.freeze(vn);var yn=function(){},bn=function(){function e(e){void 0===e&&(e="Atom@"+s()),this.name=e,this.isPendingUnobservation=!1,this.isBeingObserved=!1,this.observers=[],this.observersIndexes={},this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=n.IDerivationState.NOT_TRACKING}return e.prototype.onBecomeUnobserved=function(){},e.prototype.onBecomeObserved=function(){},e.prototype.reportObserved=function(){return xe(this)},e.prototype.reportChanged=function(){Oe(),Ae(this),Se()},e.prototype.toString=function(){return this.name},e}(),mn=m("Atom",bn),gn={identity:V,structural:N,default:R},wn={},_n={},On={deep:!0,name:void 0,defaultDecorator:void 0},Sn={deep:!1,name:void 0,defaultDecorator:void 0};Object.freeze(On),Object.freeze(Sn);var xn=q(M),An=q(U),En=q(G),Dn=q(H),jn={box:function(e,t){arguments.length>2&&J("box");var n=z(t);return new Vn(e,K(n),n.name,!0,n.equals)},shallowBox:function(e,t){return arguments.length>2&&J("shallowBox"),l("observable.shallowBox","observable.box(value, { deep: false })"),Tn.box(e,{name:t,deep:!1})},array:function(e,t){arguments.length>2&&J("array");var n=z(t);return new rr(e,K(n),n.name)},shallowArray:function(e,t){return arguments.length>2&&J("shallowArray"),l("observable.shallowArray","observable.array(values, { deep: false })"),Tn.array(e,{name:t,deep:!1})},map:function(e,t){arguments.length>2&&J("map");var n=z(t);return new sr(e,K(n),n.name)},shallowMap:function(e,t){return arguments.length>2&&J("shallowMap"),l("observable.shallowMap","observable.map(values, { deep: false })"),Tn.map(e,{name:t,deep:!1})},set:function(e,t){arguments.length>2&&J("set");var n=z(t);return new lr(e,K(n),n.name)},object:function(e,t,n){return"string"==typeof arguments[1]&&J("object"),nt({},e,t,z(n))},shallowObject:function(e,t){return"string"==typeof arguments[1]&&J("shallowObject"),l("observable.shallowObject","observable.object(values, {}, { deep: false })"),Tn.object(e,{},{name:t,deep:!1})},ref:En,shallow:An,deep:xn,struct:Dn},Tn=W;Object.keys(jn).forEach(function(e){return Tn[e]=jn[e]});var kn=B(!1,function(e,t,n,r,o){var i=n.get,a=n.set,s=o[0]||{};Yt(e,t,pn({get:i,set:a},s))}),In=kn({equals:gn.structural}),Cn=function(e,t,n){if("string"==typeof t)return kn.apply(null,arguments);if(null!==e&&"object"==typeof e&&1===arguments.length)return kn.apply(null,arguments);var r="object"==typeof t?t:{};return r.get=e,r.set="function"==typeof t?t:r.set,r.name=r.name||e.name||"",new Rn(r)};Cn.struct=In;var Vn=function(e){function t(t,n,r,o,i){void 0===r&&(r="ObservableValue@"+s()),void 0===o&&(o=!0),void 0===i&&(i=gn.default);var a=e.call(this,r)||this;return a.enhancer=n,a.name=r,a.equals=i,a.hasUnreportedChange=!1,a.value=n(t,void 0,r),o&&Ne()&&Re({type:"create",name:a.name,newValue:""+a.value}),a}return r(t,e),t.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.prototype.set=function(e){var t=this.value;if((e=this.prepareNewValue(e))!==Hn.UNCHANGED){var n=Ne();n&&Le({type:"update",name:this.name,newValue:e,oldValue:t}),this.setNewValue(e),n&&Pe()}},t.prototype.prepareNewValue=function(e){if(ae(this),Bt(this)){var t=Mt(this,{object:this,type:"update",newValue:e});if(!t)return Hn.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value,this.name),this.equals(this.value,e)?Hn.UNCHANGED:e},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),Ut(this)&&Ht(this,{type:"update",object:this,newValue:e,oldValue:t})},t.prototype.get=function(){return this.reportObserved(),this.dehanceValue(this.value)},t.prototype.intercept=function(e){return $t(this,e)},t.prototype.observe=function(e,t){return t&&e({object:this,type:"update",newValue:this.value,oldValue:void 0}),Gt(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t.prototype.valueOf=function(){return E(this.get())},t}(bn);Vn.prototype[A()]=Vn.prototype.valueOf;var Nn=m("ObservableValue",Vn),Rn=function(){function e(e){this.dependenciesState=n.IDerivationState.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isBeingObserved=!1,this.isPendingUnobservation=!1,this.observers=[],this.observersIndexes={},this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=n.IDerivationState.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+s(),this.value=new Bn(null),this.isComputing=!1,this.isRunningSetter=!1,this.isTracing=Pn.NONE,this.derivation=e.get,this.name=e.name||"ComputedValue@"+s(),e.set&&(this.setter=X(this.name+"-setter",e.set)),this.equals=e.equals||(e.compareStructural||e.struct?gn.structural:gn.default),this.scope=e.context,this.requiresReaction=!!e.requiresReaction,this.keepAlive=!!e.keepAlive}return e.prototype.onBecomeStale=function(){De(this)},e.prototype.onBecomeUnobserved=function(){},e.prototype.onBecomeObserved=function(){},e.prototype.get=function(){this.isComputing&&u("Cycle detected in computation "+this.name+": "+this.derivation),0!==Hn.inBatch||0!==this.observers.length||this.keepAlive?(xe(this),oe(this)&&this.trackAndCompute()&&Ee(this)):oe(this)&&(this.warnAboutUntrackedRead(),Oe(), this.value=this.computeValue(!1),Se());var e=this.value;if(re(e))throw e.cause;return e},e.prototype.peek=function(){var e=this.computeValue(!1);if(re(e))throw e.cause;return e},e.prototype.set=function(e){if(this.setter){c(!this.isRunningSetter,"The setter of computed value '"+this.name+"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"),this.isRunningSetter=!0;try{this.setter.call(this.scope,e)}finally{this.isRunningSetter=!1}}else c(!1,!1)},e.prototype.trackAndCompute=function(){Ne()&&Re({object:this.scope,type:"compute",name:this.name});var e=this.value,t=this.dependenciesState===n.IDerivationState.NOT_TRACKING,r=this.computeValue(!0),o=t||re(e)||re(r)||!this.equals(e,r);return o&&(this.value=r),o},e.prototype.computeValue=function(e){this.isComputing=!0,Hn.computationDepth++;var t;if(e)t=se(this,this.derivation,this.scope);else if(!0===Hn.disableErrorBoundaries)t=this.derivation.call(this.scope);else try{t=this.derivation.call(this.scope)}catch(e){t=new Bn(e)}return Hn.computationDepth--,this.isComputing=!1,t},e.prototype.suspend=function(){this.keepAlive||(ce(this),this.value=void 0)},e.prototype.observe=function(e,t){var n=this,r=!0,o=void 0;return Ke(function(){var i=n.get();if(!r||t){var a=fe();e({type:"update",object:n,newValue:i,oldValue:o}),pe(a)}r=!1,o=i})},e.prototype.warnAboutUntrackedRead=function(){},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.valueOf=function(){return E(this.get())},e}();Rn.prototype[A()]=Rn.prototype.valueOf;var Ln=m("ComputedValue",Rn);!function(e){e[e.NOT_TRACKING=-1]="NOT_TRACKING",e[e.UP_TO_DATE=0]="UP_TO_DATE",e[e.POSSIBLY_STALE=1]="POSSIBLY_STALE",e[e.STALE=2]="STALE"}(n.IDerivationState||(n.IDerivationState={}));var Pn;!function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(Pn||(Pn={}));var Bn=function(){function e(e){this.cause=e}return e}(),$n=["mobxGuid","spyListeners","enforceActions","computedRequiresReaction","disableErrorBoundaries","runId","UNCHANGED"],Mn=function(){function e(){this.version=5,this.UNCHANGED={},this.trackingDerivation=null,this.computationDepth=0,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!0,this.enforceActions=!1,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1}return e}(),Un=!0,Gn=!1,Hn=function(){var e=a();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Un=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==(new Mn).version&&(Un=!1),Un?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Mn):(setTimeout(function(){Gn||u("There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`")},1),new Mn)}(),qn=function(){function e(e,t,r){void 0===e&&(e="Reaction@"+s()),this.name=e,this.onInvalidate=t,this.errorHandler=r,this.observing=[],this.newObserving=[],this.dependenciesState=n.IDerivationState.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+s(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1,this.isTracing=Pn.NONE}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,Hn.pendingReactions.push(this),Ie())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){if(!this.isDisposed){if(Oe(),this._isScheduled=!1,oe(this)){this._isTrackPending=!0;try{this.onInvalidate(),this._isTrackPending&&Ne()&&Re({name:this.name,type:"scheduled-reaction"})}catch(e){this.reportExceptionInDerivation(e)}}Se()}},e.prototype.track=function(e){Oe();var t,n=Ne();n&&(t=Date.now(),Le({name:this.name,type:"reaction"})),this._isRunning=!0;var r=se(this,e,void 0);this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&ce(this),re(r)&&this.reportExceptionInDerivation(r.cause),n&&Pe({time:Date.now()-t}),Se()},e.prototype.reportExceptionInDerivation=function(e){var t=this;if(this.errorHandler)return void this.errorHandler(e,this);if(Hn.disableErrorBoundaries)throw e;var n="[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '"+this+"'";Hn.suppressReactionErrors?console.warn("[mobx] (error in reaction '"+this.name+"' suppressed, fix error of causing action below)"):console.error(n,e),Ne()&&Re({type:"error",name:this.name,message:n,error:""+e}),Hn.globalReactionErrorHandlers.forEach(function(n){return n(e,t)})},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(Oe(),ce(this),Se()))},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e.$mobx=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e.prototype.trace=function(e){void 0===e&&(e=!1),Ct(this,e)},e}(),zn=100,Kn=function(e){return e()},Wn=m("Reaction",qn),Jn={spyReportEnd:!0},Xn=function(e,t,n,r){return 1===arguments.length&&"function"==typeof e?X(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof t?X(e,t):1===arguments.length&&"string"==typeof e?Me(e):!0!==r?Me(t).apply(null,arguments):void(e[t]=X(e.name||t,n.value))};Xn.bound=Ge;var Yn=function(e){return e()},Fn=0,Qn={detectCycles:!0,exportMapsAsObjects:!0,recurseEverything:!1},Zn=function(){var e=!1,t={};return Object.defineProperty(t,"0",{set:function(){e=!0}}),Object.create(t)[0]=1,!1===e}(),er=0,tr=function(){function e(){}return e}();!function(e,t){void 0!==Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):void 0!==e.prototype.__proto__?e.prototype.__proto__=t:e.prototype=t}(tr,Array.prototype),Object.isFrozen(Array)&&["constructor","push","shift","concat","pop","unshift","replace","find","findIndex","splice","reverse","sort"].forEach(function(e){Object.defineProperty(tr.prototype,e,{configurable:!0,writable:!0,value:Array.prototype[e]})});var nr=function(){function e(e,t,n,r){this.array=n,this.owned=r,this.values=[],this.lastKnownLength=0,this.atom=new bn(e||"ObservableArray@"+s()),this.enhancer=function(n,r){return t(n,r,e+"[..]")}}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.dehanceValues=function(e){return void 0!==this.dehancer&&e.length>0?e.map(this.dehancer):e},e.prototype.intercept=function(e){return $t(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.array,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),Gt(this,e)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||e<0)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;if(e!==t)if(e>t){for(var n=new Array(e-t),r=0;r<e-t;r++)n[r]=void 0;this.spliceWithArray(t,0,n)}else this.spliceWithArray(e,t-e)},e.prototype.updateArrayLength=function(e,t){if(e!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");this.lastKnownLength+=t,t>0&&e+t+1>er&&Kt(e+t+1)},e.prototype.spliceWithArray=function(e,t,n){var r=this;ae(this.atom);var o=this.values.length;if(void 0===e?e=0:e>o?e=o:e<0&&(e=Math.max(0,o+e)),t=1===arguments.length?o-e:void 0===t||null===t?0:Math.max(0,Math.min(t,o-e)),void 0===n&&(n=dn),Bt(this)){var i=Mt(this,{object:this.array,type:"splice",index:e,removedCount:t,added:n});if(!i)return dn;t=i.removedCount,n=i.added}n=0===n.length?n:n.map(function(e){return r.enhancer(e,void 0)});var a=n.length-t;this.updateArrayLength(o,a);var s=this.spliceItemsIntoValues(e,t,n);return 0===t&&0===n.length||this.notifyArraySplice(e,n,s),this.dehanceValues(s)},e.prototype.spliceItemsIntoValues=function(e,t,n){var r;if(n.length<1e4)return(r=this.values).splice.apply(r,i([e,t],n));var o=this.values.slice(e,e+t);return this.values=this.values.slice(0,e).concat(n,this.values.slice(e+t)),o},e.prototype.notifyArrayChildUpdate=function(e,t,n){var r=!this.owned&&Ne(),o=Ut(this),i=o||r?{object:this.array,type:"update",index:e,newValue:t,oldValue:n}:null;r&&Le(pn({},i,{name:this.atom.name})),this.atom.reportChanged(),o&&Ht(this,i),r&&Pe()},e.prototype.notifyArraySplice=function(e,t,n){var r=!this.owned&&Ne(),o=Ut(this),i=o||r?{object:this.array,type:"splice",index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Le(pn({},i,{name:this.atom.name})),this.atom.reportChanged(),o&&Ht(this,i),r&&Pe()},e}(),rr=function(e){function t(t,n,r,o){void 0===r&&(r="ObservableArray@"+s()),void 0===o&&(o=!1);var i=e.call(this)||this,a=new nr(r,n,i,o);if(y(i,"$mobx",a),t&&t.length){var u=ee(!0);i.spliceWithArray(0,0,t),te(u)}return Zn&&Object.defineProperty(a.array,"0",or),i}return r(t,e),t.prototype.intercept=function(e){return this.$mobx.intercept(e)},t.prototype.observe=function(e,t){return void 0===t&&(t=!1),this.$mobx.observe(e,t)},t.prototype.clear=function(){return this.splice(0)},t.prototype.concat=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.$mobx.atom.reportObserved(),Array.prototype.concat.apply(this.peek(),e.map(function(e){return Wt(e)?e.peek():e}))},t.prototype.replace=function(e){return this.$mobx.spliceWithArray(0,this.$mobx.values.length,e)},t.prototype.toJS=function(){return this.slice()},t.prototype.toJSON=function(){return this.toJS()},t.prototype.peek=function(){return this.$mobx.atom.reportObserved(),this.$mobx.dehanceValues(this.$mobx.values)},t.prototype.find=function(e,t,n){void 0===n&&(n=0),3===arguments.length&&l("The array.find fromIndex argument to find will not be supported anymore in the next major");var r=this.findIndex.apply(this,arguments);return-1===r?void 0:this.get(r)},t.prototype.findIndex=function(e,t,n){void 0===n&&(n=0),3===arguments.length&&l("The array.findIndex fromIndex argument to find will not be supported anymore in the next major");for(var r=this.peek(),o=r.length,i=n;i<o;i++)if(e.call(t,r[i],i,this))return i;return-1},t.prototype.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];switch(arguments.length){case 0:return[];case 1:return this.$mobx.spliceWithArray(e);case 2:return this.$mobx.spliceWithArray(e,t)}return this.$mobx.spliceWithArray(e,t,n)},t.prototype.spliceWithArray=function(e,t,n){return this.$mobx.spliceWithArray(e,t,n)},t.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.$mobx;return n.spliceWithArray(n.values.length,0,e),n.values.length},t.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},t.prototype.shift=function(){return this.splice(0,1)[0]},t.prototype.unshift=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.$mobx;return n.spliceWithArray(0,0,e),n.values.length},t.prototype.reverse=function(){var e=this.slice();return e.reverse.apply(e,arguments)},t.prototype.sort=function(e){var t=this.slice();return t.sort.apply(t,arguments)},t.prototype.remove=function(e){var t=this.$mobx.dehanceValues(this.$mobx.values).indexOf(e);return t>-1&&(this.splice(t,1),!0)},t.prototype.move=function(e,t){function n(e){if(e<0)throw new Error("[mobx.array] Index out of bounds: "+e+" is negative");var t=this.$mobx.values.length;if(e>=t)throw new Error("[mobx.array] Index out of bounds: "+e+" is not smaller than "+t)}if(l("observableArray.move is deprecated, use .slice() & .replace() instead"),n.call(this,e),n.call(this,t),e!==t){var r,o=this.$mobx.values;r=e<t?i(o.slice(0,e),o.slice(e+1,t+1),[o[e]],o.slice(t+1)):i(o.slice(0,t),[o[e]],o.slice(t,e),o.slice(e+1)),this.replace(r)}},t.prototype.get=function(e){var t=this.$mobx;if(t){if(e<t.values.length)return t.atom.reportObserved(),t.dehanceValue(t.values[e]);console.warn("[mobx.array] Attempt to read an array index ("+e+") that is out of bounds ("+t.values.length+"). Please check length first. Out of bound indices will not be tracked by MobX")}},t.prototype.set=function(e,t){var n=this.$mobx,r=n.values;if(e<r.length){ae(n.atom);var o=r[e];if(Bt(n)){var i=Mt(n,{type:"update",object:this,index:e,newValue:t});if(!i)return;t=i.newValue}t=n.enhancer(t,o);t!==o&&(r[e]=t,n.notifyArrayChildUpdate(e,t,o))}else{if(e!==r.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+r.length);n.spliceWithArray(e,0,[t])}},t}(tr);j(rr.prototype,function(){this.$mobx.atom.reportObserved();var e=this,t=0;return T({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})}),Object.defineProperty(rr.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return this.$mobx.getArrayLength()},set:function(e){this.$mobx.setArrayLength(e)}}),v(rr.prototype,k(),"Array"),["every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some","toString","toLocaleString"].forEach(function(e){var t=Array.prototype[e];c("function"==typeof t,"Base function not defined on Array prototype: '"+e+"'"),v(rr.prototype,e,function(){return t.apply(this.peek(),arguments)})}),function(e,t){for(var n=0;n<t.length;n++)v(e,t[n],e[t[n]])}(rr.prototype,["constructor","intercept","observe","clear","concat","get","replace","toJS","toJSON","peek","find","findIndex","splice","spliceWithArray","push","pop","set","shift","unshift","reverse","sort","remove","move","toString","toLocaleString"]);var or=qt(0);Kt(1e3);var ir=m("ObservableArrayAdministration",nr),ar={},sr=function(){function e(e,t,n){if(void 0===t&&(t=M),void 0===n&&(n="ObservableMap@"+s()),this.enhancer=t,this.name=n,this.$mobx=ar,this._keys=new rr(void 0,G,this.name+".keys()",!0),"function"!=typeof Map)throw new Error("mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js");this._data=new Map,this._hasMap=new Map,this.merge(e)}return e.prototype._has=function(e){return this._data.has(e)},e.prototype.has=function(e){return this._hasMap.has(e)?this._hasMap.get(e).get():this._updateHasMapEntry(e,!1).get()},e.prototype.set=function(e,t){var n=this._has(e);if(Bt(this)){var r=Mt(this,{type:n?"update":"add",object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this._updateValue(e,t):this._addValue(e,t),this},e.prototype.delete=function(e){var t=this;if(Bt(this)){var n=Mt(this,{type:"delete",object:this,name:e});if(!n)return!1}if(this._has(e)){var r=Ne(),o=Ut(this),n=o||r?{type:"delete",object:this,oldValue:this._data.get(e).value,name:e}:null;return r&&Le(pn({},n,{name:this.name,key:e})),Nt(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1),t._data.get(e).setNewValue(void 0),t._data.delete(e)}),o&&Ht(this,n),r&&Pe(),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var n=this._hasMap.get(e);return n?n.setNewValue(t):(n=new Vn(t,G,this.name+"."+e+"?",!1),this._hasMap.set(e,n)),n},e.prototype._updateValue=function(e,t){var n=this._data.get(e);if((t=n.prepareNewValue(t))!==Hn.UNCHANGED){var r=Ne(),o=Ut(this),i=o||r?{type:"update",object:this,oldValue:n.value,name:e,newValue:t}:null;r&&Le(pn({},i,{name:this.name,key:e})),n.setNewValue(t),o&&Ht(this,i),r&&Pe()}},e.prototype._addValue=function(e,t){var n=this;Nt(function(){var r=new Vn(t,n.enhancer,n.name+"."+e,!1);n._data.set(e,r),t=r.value,n._updateHasMapEntry(e,!0),n._keys.push(e)});var r=Ne(),o=Ut(this),i=o||r?{type:"add",object:this,name:e,newValue:t}:null;r&&Le(pn({},i,{name:this.name,key:e})),o&&Ht(this,i),r&&Pe()},e.prototype.get=function(e){return this.has(e)?this.dehanceValue(this._data.get(e).get()):this.dehanceValue(void 0)},e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.keys=function(){return this._keys[D()]()},e.prototype.values=function(){var e=this,t=0;return T({next:function(){return t<e._keys.length?{value:e.get(e._keys[t++]),done:!1}:{value:void 0,done:!0}}})},e.prototype.entries=function(){var e=this,t=0;return T({next:function(){if(t<e._keys.length){var n=e._keys[t++];return{value:[n,e.get(n)],done:!1}}return{done:!0}}})},e.prototype.forEach=function(e,t){var n=this;this._keys.forEach(function(r){return e.call(t,n.get(r),r,n)})},e.prototype.merge=function(e){var t=this;return ur(e)&&(e=e.toJS()),Nt(function(){d(e)?Object.keys(e).forEach(function(n){return t.set(n,e[n])}):Array.isArray(e)?e.forEach(function(e){var n=o(e,2),r=n[0],i=n[1];return t.set(r,i)}):_(e)?e.constructor!==Map?u("Cannot initialize from classes that inherit from Map: "+e.constructor.name):e.forEach(function(e,n){return t.set(n,e)}):null!==e&&void 0!==e&&u("Cannot initialize map from "+e)}),this},e.prototype.clear=function(){var e=this;Nt(function(){le(function(){e._keys.slice().forEach(function(t){return e.delete(t)})})})},e.prototype.replace=function(e){var t=this;return Nt(function(){var n=S(e);t._keys.filter(function(e){return-1===n.indexOf(e)}).forEach(function(e){return t.delete(e)}),t.merge(e)}),this},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toPOJO=function(){var e=this,t={};return this._keys.forEach(function(n){return t[""+n]=e.get(n)}),t},e.prototype.toJS=function(){var e=this,t=new Map;return this._keys.forEach(function(n){return t.set(n,e.get(n))}),t},e.prototype.toJSON=function(){return this.toPOJO()},e.prototype.toString=function(){var e=this;return this.name+"[{ "+this._keys.map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return Gt(this,e)},e.prototype.intercept=function(e){return $t(this,e)},e}();j(sr.prototype,function(){return this.entries()}),y(sr.prototype,k(),"Map");var ur=m("ObservableMap",sr),cr={},lr=function(){function e(e,t,n){if(void 0===t&&(t=M),void 0===n&&(n="ObservableSet@"+s()),this.name=n,this.$mobx=cr,this._data=new Set,this._atom=C(this.name),"function"!=typeof Set)throw new Error("mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js");this.enhancer=function(e,r){return t(e,r,n)},e&&this.replace(e)}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.clear=function(){var e=this;Nt(function(){le(function(){e._data.forEach(function(t){e.delete(t)})})})},e.prototype.forEach=function(e,t){var n=this;this._data.forEach(function(r){e.call(t,r,r,n)})},Object.defineProperty(e.prototype,"size",{get:function(){return this._atom.reportObserved(),this._data.size},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this;if(ae(this._atom),Bt(this)){var n=Mt(this,{type:"add",object:this,newValue:e});if(!n)return this}if(!this.has(e)){Nt(function(){t._data.add(t.enhancer(e,void 0)),t._atom.reportChanged()});var r=Ne(),o=Ut(this),n=o||r?{type:"add",object:this,newValue:e}:null;o&&Ht(this,n)}return this},e.prototype.delete=function(e){var t=this;if(Bt(this)){var n=Mt(this,{type:"delete",object:this,oldValue:e});if(!n)return!1}if(this.has(e)){var r=Ne(),o=Ut(this),n=o||r?{type:"delete",object:this,oldValue:e}:null;return Nt(function(){t._atom.reportChanged(),t._data.delete(e)}),o&&Ht(this,n),!0}return!1},e.prototype.has=function(e){return this._atom.reportObserved(),this._data.has(this.dehanceValue(e))},e.prototype.entries=function(){var e=0,t=x(this.keys()),n=x(this.values());return T({next:function(){var r=e;return e+=1,r<n.length?{value:[t[r],n[r]],done:!1}:{done:!0}}})},e.prototype.keys=function(){return this.values()},e.prototype.values=function(){this._atom.reportObserved();var e,t=this,n=0;return void 0!==this._data.values?e=x(this._data.values()):(e=[],this._data.forEach(function(t){return e.push(t)})),T({next:function(){return n<e.length?{value:t.dehanceValue(e[n++]),done:!1}:{done:!0}}})},e.prototype.replace=function(e){var t=this;return fr(e)&&(e=e.toJS()),Nt(function(){Array.isArray(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):O(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):null!==e&&void 0!==e&&u("Cannot initialize set from "+e)}),this},e.prototype.observe=function(e,t){return Gt(this,e)},e.prototype.intercept=function(e){return $t(this,e)},e.prototype.toJS=function(){return new Set(this)},e.prototype.toString=function(){return this.name+"[ "+x(this.keys()).join(", ")+" ]"},e}();j(lr.prototype,function(){return this.values()}),y(lr.prototype,k(),"Set");var fr=m("ObservableSet",lr),pr=function(){function e(e,t,n){this.target=e,this.name=t,this.defaultEnhancer=n,this.values={}}return e.prototype.read=function(e,t){if(this.target===e||(this.illegalAccess(e,t),this.values[t]))return this.values[t].get()},e.prototype.write=function(e,t,n){var r=this.target;r!==e&&this.illegalAccess(e,t);var o=this.values[t];if(o instanceof Rn)return void o.set(n);if(Bt(this)){var i=Mt(this,{type:"update",object:r,name:t,newValue:n});if(!i)return;n=i.newValue}if((n=o.prepareNewValue(n))!==Hn.UNCHANGED){var a=Ut(this),s=Ne(),i=a||s?{type:"update",object:r,oldValue:o.value,name:t,newValue:n}:null;s&&Le(pn({},i,{name:this.name,key:t})),o.setNewValue(n),a&&Ht(this,i),s&&Pe()}},e.prototype.remove=function(e){if(this.values[e]){var t=this.target;if(Bt(this)){var n=Mt(this,{object:t,name:e,type:"remove"});if(!n)return}try{Oe();var r=Ut(this),o=Ne(),i=this.values[e].get();this.keys&&this.keys.remove(e),delete this.values[e],delete this.target[e];var n=r||o?{type:"remove",object:t,oldValue:i,name:e}:null;o&&Le(pn({},n,{name:this.name,key:e})),r&&Ht(this,n),o&&Pe()}finally{Se()}}},e.prototype.illegalAccess=function(e,t){console.warn("Property '"+t+"' of '"+e+"' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner")},e.prototype.observe=function(e,t){return Gt(this,e)},e.prototype.intercept=function(e){return $t(this,e)},e.prototype.getKeys=function(){var e=this;return void 0===this.keys&&(this.keys=new rr(Object.keys(this.values).filter(function(t){return e.values[t]instanceof Vn}),G,"keys("+this.name+")",!0)),this.keys.slice()},e}(),hr=Object.create(null),dr=Object.create(null),vr=m("ObservableObjectAdministration",pr),yr=Object.prototype.toString;!function(){function e(){}e.name}();"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Be,extras:{getDebugName:on},$mobx:"$mobx"});n.$mobx="$mobx",n.Reaction=qn,n.untracked=le,n.createAtom=C,n.spy=Be,n.comparer=gn,n.isObservableObject=tn,n.isBoxedObservable=Nn,n.isObservableArray=Wt,n.ObservableMap=sr,n.isObservableMap=ur,n.ObservableSet=lr,n.isObservableSet=fr,n.transaction=Nt,n.observable=Tn,n.computed=Cn,n.isObservable=bt,n.isObservableProp=mt,n.isComputed=dt,n.isComputedProp=vt,n.extendObservable=nt,n.extendShallowObservable=tt,n.observe=Et,n.intercept=lt,n.autorun=Ke,n.reaction=Je,n.when=Rt,n.action=Xn,n.isAction=qe,n.runInAction=He,n.keys=gt,n.values=wt,n.entries=_t,n.set=Ot,n.remove=St,n.has=xt,n.get=At,n.decorate=et,n.configure=Ze,n.onBecomeObserved=Ye,n.onBecomeUnobserved=Fe,n.flow=st,n.toJS=It,n.trace=Ct,n.getDependencyTree=rt,n.getObserverTree=it,n._resetGlobalState=ye,n._getGlobalState=ve,n.getDebugName=on,n.getAtom=nn,n._getAdministration=rn,n._allowStateChanges=Z,n._allowStateChangesInsideComputed=ne,n.isArrayLike=w,n._isComputingDerivation=ie,n.onReactionError=ke,n._interceptReads=ct}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:2}],2:[function(e,t,n){function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(f===setTimeout)return setTimeout(e,0);if((f===r||!f)&&setTimeout)return f=setTimeout,setTimeout(e,0);try{return f(e,0)}catch(t){try{return f.call(null,e,0)}catch(t){return f.call(this,e,0)}}}function a(e){if(p===clearTimeout)return clearTimeout(e);if((p===o||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function s(){y&&d&&(y=!1,d.length?v=d.concat(v):b=-1,v.length&&u())}function u(){if(!y){var e=i(s);y=!0;for(var t=v.length;t;){for(d=v,v=[];++b<t;)d&&d[b].run();b=-1,t=v.length}d=null,y=!1,a(e)}}function c(e,t){this.fun=e,this.array=t}function l(){}var f,p,h=t.exports={};!function(){try{f="function"==typeof setTimeout?setTimeout:r}catch(e){f=r}try{p="function"==typeof clearTimeout?clearTimeout:o}catch(e){p=o}}();var d,v=[],y=!1,b=-1;h.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];v.push(new c(e,t)),1!==v.length||y||i(u)},c.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=l,h.addListener=l,h.once=l,h.off=l,h.removeListener=l,h.removeAllListeners=l,h.emit=l,h.prependListener=l,h.prependOnceListener=l,h.listeners=function(e){return[]},h.binding=function(e){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(e){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}]},{},[1])(1)}); //# sourceMappingURL=lib/mobx.umd.min.js.map
src/components/LoadingPage/index.js
mrnav90/react-enigma-employee
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class LoadingPage extends React.Component { constructor(props) { super(props); } render() { return ( <div className={classNames('loading-wrapper', {'show-loading': this.props.isShow})}> <div className="loading-three-bounce"> <div className="loading-bounce"></div> <div className="loading-bounce"></div> <div className="loading-bounce"></div> </div> </div> ); } } LoadingPage.propTypes = { isShow: PropTypes.bool.isRequired };
src/profiles/FatherProfile.js
Arinono/uReflect_POC_Electron01
import React from 'react'; import ClockContainer from '../containers/ClockContainer'; //import WeatherContainer from '../containers/WeatherContainer'; import TwitterContainer from '../containers/TwitterContainer'; import DateContainer from '../containers/DateContainer'; import RssContainer from '../containers/RssContainer'; const styles = { none: { display: 'none', }, visible: { display: 'block', } }; var FatherProfile = React.createClass({ render: function() { return ( <div style={this.props.state == "hidden" ? styles.none : styles.visible}> <DateContainer /> <TwitterContainer /> <ClockContainer /> <RssContainer /> </div> ); }, }); export default FatherProfile;
ajax/libs/openlayers/2.12/lib/OpenLayers/Control/Panel.js
iskitz/cdnjs
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Control.js * @requires OpenLayers/Events/buttonclick.js */ /** * Class: OpenLayers.Control.Panel * The Panel control is a container for other controls. With it toolbars * may be composed. * * Inherits from: * - <OpenLayers.Control> */ OpenLayers.Control.Panel = OpenLayers.Class(OpenLayers.Control, { /** * Property: controls * {Array(<OpenLayers.Control>)} */ controls: null, /** * APIProperty: autoActivate * {Boolean} Activate the control when it is added to a map. Default is * true. */ autoActivate: true, /** * APIProperty: defaultControl * {<OpenLayers.Control>} The control which is activated when the control is * activated (turned on), which also happens at instantiation. * If <saveState> is true, <defaultControl> will be nullified after the * first activation of the panel. */ defaultControl: null, /** * APIProperty: saveState * {Boolean} If set to true, the active state of this panel's controls will * be stored on panel deactivation, and restored on reactivation. Default * is false. */ saveState: false, /** * APIProperty: allowDepress * {Boolean} If is true the <OpenLayers.Control.TYPE_TOOL> controls can * be deactivated by clicking the icon that represents them. Default * is false. */ allowDepress: false, /** * Property: activeState * {Object} stores the active state of this panel's controls. */ activeState: null, /** * Constructor: OpenLayers.Control.Panel * Create a new control panel. * * Each control in the panel is represented by an icon. When clicking * on an icon, the <activateControl> method is called. * * Specific properties for controls on a panel: * type - {Number} One of <OpenLayers.Control.TYPE_TOOL>, * <OpenLayers.Control.TYPE_TOGGLE>, <OpenLayers.Control.TYPE_BUTTON>. * If not provided, <OpenLayers.Control.TYPE_TOOL> is assumed. * title - {string} Text displayed when mouse is over the icon that * represents the control. * * The <OpenLayers.Control.type> of a control determines the behavior when * clicking its icon: * <OpenLayers.Control.TYPE_TOOL> - The control is activated and other * controls of this type in the same panel are deactivated. This is * the default type. * <OpenLayers.Control.TYPE_TOGGLE> - The active state of the control is * toggled. * <OpenLayers.Control.TYPE_BUTTON> - The * <OpenLayers.Control.Button.trigger> method of the control is called, * but its active state is not changed. * * If a control is <OpenLayers.Control.active>, it will be drawn with the * olControl[Name]ItemActive class, otherwise with the * olControl[Name]ItemInactive class. * * Parameters: * options - {Object} An optional object whose properties will be used * to extend the control. */ initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.controls = []; this.activeState = {}; }, /** * APIMethod: destroy */ destroy: function() { if (this.map) { this.map.events.unregister("buttonclick", this, this.onButtonClick); } OpenLayers.Control.prototype.destroy.apply(this, arguments); for (var ctl, i = this.controls.length - 1; i >= 0; i--) { ctl = this.controls[i]; if (ctl.events) { ctl.events.un({ activate: this.iconOn, deactivate: this.iconOff }); } ctl.panel_div = null; } this.activeState = null; }, /** * APIMethod: activate */ activate: function() { if (OpenLayers.Control.prototype.activate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; if (control === this.defaultControl || (this.saveState && this.activeState[control.id])) { control.activate(); } } if (this.saveState === true) { this.defaultControl = null; } this.redraw(); return true; } else { return false; } }, /** * APIMethod: deactivate */ deactivate: function() { if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; this.activeState[control.id] = control.deactivate(); } this.redraw(); return true; } else { return false; } }, /** * Method: draw * * Returns: * {DOMElement} */ draw: function() { OpenLayers.Control.prototype.draw.apply(this, arguments); if (this.outsideViewport) { this.events.attachToElement(this.div); this.events.register("buttonclick", this, this.onButtonClick); } else { this.map.events.register("buttonclick", this, this.onButtonClick); } this.addControlsToMap(this.controls); return this.div; }, /** * Method: redraw */ redraw: function() { for (var l=this.div.childNodes.length, i=l-1; i>=0; i--) { this.div.removeChild(this.div.childNodes[i]); } this.div.innerHTML = ""; if (this.active) { for (var i=0, len=this.controls.length; i<len; i++) { this.div.appendChild(this.controls[i].panel_div); } } }, /** * APIMethod: activateControl * This method is called when the user click on the icon representing a * control in the panel. * * Parameters: * control - {<OpenLayers.Control>} */ activateControl: function (control) { if (!this.active) { return false; } if (control.type == OpenLayers.Control.TYPE_BUTTON) { control.trigger(); return; } if (control.type == OpenLayers.Control.TYPE_TOGGLE) { if (control.active) { control.deactivate(); } else { control.activate(); } return; } if (this.allowDepress && control.active) { control.deactivate(); } else { var c; for (var i=0, len=this.controls.length; i<len; i++) { c = this.controls[i]; if (c != control && (c.type === OpenLayers.Control.TYPE_TOOL || c.type == null)) { c.deactivate(); } } control.activate(); } }, /** * APIMethod: addControls * To build a toolbar, you add a set of controls to it. addControls * lets you add a single control or a list of controls to the * Control Panel. * * Parameters: * controls - {<OpenLayers.Control>} Controls to add in the panel. */ addControls: function(controls) { if (!(OpenLayers.Util.isArray(controls))) { controls = [controls]; } this.controls = this.controls.concat(controls); for (var i=0, len=controls.length; i<len; i++) { var control = controls[i], element = this.createControlMarkup(control); OpenLayers.Element.addClass(element, control.displayClass + "ItemInactive"); OpenLayers.Element.addClass(element, "olButton"); if (control.title != "" && !element.title) { element.title = control.title; } control.panel_div = element; } if (this.map) { // map.addControl() has already been called on the panel this.addControlsToMap(controls); this.redraw(); } }, /** * APIMethod: createControlMarkup * This function just creates a div for the control. If specific HTML * markup is needed this function can be overridden in specific classes, * or at panel instantiation time: * * Example: * (code) * var panel = new OpenLayers.Control.Panel({ * defaultControl: control, * // ovverride createControlMarkup to create actual buttons * // including texts wrapped into span elements. * createControlMarkup: function(control) { * var button = document.createElement('button'), * span = document.createElement('span'); * if (control.text) { * span.innerHTML = control.text; * } * return button; * } * }); * (end) * * Parameters: * control - {<OpenLayers.Control>} The control to create the HTML * markup for. * * Returns: * {DOMElement} The markup. */ createControlMarkup: function(control) { return document.createElement("div"); }, /** * Method: addControlsToMap * Only for internal use in draw() and addControls() methods. * * Parameters: * controls - {Array(<OpenLayers.Control>)} Controls to add into map. */ addControlsToMap: function (controls) { var control; for (var i=0, len=controls.length; i<len; i++) { control = controls[i]; if (control.autoActivate === true) { control.autoActivate = false; this.map.addControl(control); control.autoActivate = true; } else { this.map.addControl(control); control.deactivate(); } control.events.on({ activate: this.iconOn, deactivate: this.iconOff }); } }, /** * Method: iconOn * Internal use, for use only with "controls[i].events.on/un". */ iconOn: function() { var d = this.panel_div; // "this" refers to a control on panel! var re = new RegExp("\\b(" + this.displayClass + "Item)Inactive\\b"); d.className = d.className.replace(re, "$1Active"); }, /** * Method: iconOff * Internal use, for use only with "controls[i].events.on/un". */ iconOff: function() { var d = this.panel_div; // "this" refers to a control on panel! var re = new RegExp("\\b(" + this.displayClass + "Item)Active\\b"); d.className = d.className.replace(re, "$1Inactive"); }, /** * Method: onButtonClick * * Parameters: * evt - {Event} */ onButtonClick: function (evt) { var controls = this.controls, button = evt.buttonElement; for (var i=controls.length-1; i>=0; --i) { if (controls[i].panel_div === button) { this.activateControl(controls[i]); break; } } }, /** * APIMethod: getControlsBy * Get a list of controls with properties matching the given criteria. * * Parameters: * property - {String} A control property to be matched. * match - {String | Object} A string to match. Can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * match.test(control[property]) evaluates to true, the control will be * included in the array returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given criteria. * An empty array is returned if no matches are found. */ getControlsBy: function(property, match) { var test = (typeof match.test == "function"); var found = OpenLayers.Array.filter(this.controls, function(item) { return item[property] == match || (test && match.test(item[property])); }); return found; }, /** * APIMethod: getControlsByName * Get a list of contorls with names matching the given name. * * Parameters: * match - {String | Object} A control name. The name can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * name.test(control.name) evaluates to true, the control will be included * in the list of controls returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given name. * An empty array is returned if no matches are found. */ getControlsByName: function(match) { return this.getControlsBy("name", match); }, /** * APIMethod: getControlsByClass * Get a list of controls of a given type (CLASS_NAME). * * Parameters: * match - {String | Object} A control class name. The type can also be a * regular expression literal or object. In addition, it can be any * object with a method named test. For reqular expressions or other, * if type.test(control.CLASS_NAME) evaluates to true, the control will * be included in the list of controls returned. If no controls are * found, an empty array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given type. * An empty array is returned if no matches are found. */ getControlsByClass: function(match) { return this.getControlsBy("CLASS_NAME", match); }, CLASS_NAME: "OpenLayers.Control.Panel" });
src/ButtonLoadMore/index.js
DuckyTeam/ducky-components
import ActionButton from '../ActionButton'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Spacer from '../Spacer'; import styles from './styles.css'; import Typography from '../Typography'; function ButtonLoadMore(props) { return ( <div className={classNames(styles.container, { [props.className]: props.className })} > {props.endOfContent ? <div className={styles.innerWrapper}> <Typography className={styles.textOne} type="bodyTextNormal" > {props.endOfContentText} </Typography> <Spacer size="double" /> <ActionButton className={styles.upBtn} disabled={Boolean(props.disabled)} icon="icon-keyboard_arrow_up" onClick={props.onClick} size="standard" /> <Spacer size="standard" /> <Typography className={styles.textTwo} type="bodyTextNormal" > {props.backToTopText} </Typography> </div> : <div className={styles.wrapper} onClick={props.onClick} > <Typography className={styles.loadmoreBtnText} type="bodyTextNormal" > {props.showMoreText} </Typography> </div> } </div> ); } ButtonLoadMore.propTypes = { backToTopText: PropTypes.string, className: PropTypes.string, disabled: PropTypes.bool, endOfContent: PropTypes.bool, endOfContentText: PropTypes.string, onClick: PropTypes.func, showMoreText: PropTypes.string }; export default ButtonLoadMore;
examples/auth-with-shared-root/app.js
taion/rrtr
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router } from 'rrtr' import routes from './config/routes' render(<Router history={browserHistory} routes={routes}/>, document.getElementById('example'))
src/shared/visualization/BigNumber.js
cityofasheville/simplicity2
import React from 'react'; import PropTypes from 'prop-types'; import { Query } from 'react-apollo'; const BigNumber = props => ( <Query query={props.query} variables={props.queryVars} > {({ loading, error, data }) => { if (loading) return (<div className="col-sm-4">Loading...</div>) let val = '' if (error) { val = 'Error' } val = props.aggregateFunction(data) return (<div className='card-item'> <div className='topic-card' style={{ textAlign: 'center', }} > <div style={{ fontSize: '3em' }} > {val} </div> <div> {props.label} </div> </div> </div>) }} </Query> ); BigNumber.propTypes = { // query: PropTypes.object, label: PropTypes.string, } BigNumber.defaultProps = { // query: '', label: '', } export default BigNumber;
app/javascript/mastodon/components/status_action_bar.js
dunn/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import DropdownMenuContainer from '../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, isStaff } from '../initial_state'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' }, direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, share: { id: 'status.share', defaultMessage: 'Share' }, more: { id: 'status.more', defaultMessage: 'More' }, replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost to original audience' }, cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' }, removeBookmark: { id: 'status.remove_bookmark', defaultMessage: 'Remove bookmark' }, open: { id: 'status.open', defaultMessage: 'Expand this status' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, embed: { id: 'status.embed', defaultMessage: 'Embed' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, admin_status: { id: 'status.admin_status', defaultMessage: 'Open this status in the moderation interface' }, copy: { id: 'status.copy', defaultMessage: 'Copy link to status' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Hide everything from {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, }); const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; const mapStateToProps = (state, { status }) => ({ relationship: state.getIn(['relationships', status.getIn(['account', 'id'])]), }); export default @connect(mapStateToProps) @injectIntl class StatusActionBar extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, relationship: ImmutablePropTypes.map, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onMute: PropTypes.func, onUnmute: PropTypes.func, onBlock: PropTypes.func, onUnblock: PropTypes.func, onBlockDomain: PropTypes.func, onUnblockDomain: PropTypes.func, onReport: PropTypes.func, onEmbed: PropTypes.func, onMuteConversation: PropTypes.func, onPin: PropTypes.func, onBookmark: PropTypes.func, withDismiss: PropTypes.bool, intl: PropTypes.object.isRequired, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'relationship', 'withDismiss', ] handleReplyClick = () => { if (me) { this.props.onReply(this.props.status, this.context.router.history); } else { this._openInteractionDialog('reply'); } } handleShareClick = () => { navigator.share({ text: this.props.status.get('search_index'), url: this.props.status.get('url'), }).catch((e) => { if (e.name !== 'AbortError') console.error(e); }); } handleFavouriteClick = () => { if (me) { this.props.onFavourite(this.props.status); } else { this._openInteractionDialog('favourite'); } } handleReblogClick = e => { if (me) { this.props.onReblog(this.props.status, e); } else { this._openInteractionDialog('reblog'); } } _openInteractionDialog = type => { window.open(`/interact/${this.props.status.get('id')}?type=${type}`, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes'); } handleBookmarkClick = () => { this.props.onBookmark(this.props.status); } handleDeleteClick = () => { this.props.onDelete(this.props.status, this.context.router.history); } handleRedraftClick = () => { this.props.onDelete(this.props.status, this.context.router.history, true); } handlePinClick = () => { this.props.onPin(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleDirectClick = () => { this.props.onDirect(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { const { status, relationship, onMute, onUnmute } = this.props; const account = status.get('account'); if (relationship && relationship.get('muting')) { onUnmute(account); } else { onMute(account); } } handleBlockClick = () => { const { status, relationship, onBlock, onUnblock } = this.props; const account = status.get('account'); if (relationship && relationship.get('blocking')) { onUnblock(account); } else { onBlock(status); } } handleBlockDomain = () => { const { status, onBlockDomain } = this.props; const account = status.get('account'); onBlockDomain(account.get('acct').split('@')[1]); } handleUnblockDomain = () => { const { status, onUnblockDomain } = this.props; const account = status.get('account'); onUnblockDomain(account.get('acct').split('@')[1]); } handleOpen = () => { this.context.router.history.push(`/statuses/${this.props.status.get('id')}`); } handleEmbed = () => { this.props.onEmbed(this.props.status); } handleReport = () => { this.props.onReport(this.props.status); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } handleCopy = () => { const url = this.props.status.get('url'); const textarea = document.createElement('textarea'); textarea.textContent = url; textarea.style.position = 'fixed'; document.body.appendChild(textarea); try { textarea.select(); document.execCommand('copy'); } catch (e) { } finally { document.body.removeChild(textarea); } } render () { const { status, relationship, intl, withDismiss } = this.props; const mutingConversation = status.get('muted'); const anonymousAccess = !me; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const account = status.get('account'); let menu = []; let reblogIcon = 'retweet'; let replyIcon; let replyTitle; menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen }); if (publicStatus) { menu.push({ text: intl.formatMessage(messages.copy), action: this.handleCopy }); menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed }); } menu.push({ text: intl.formatMessage(status.get('bookmarked') ? messages.removeBookmark : messages.bookmark), action: this.handleBookmarkClick }); menu.push(null); if (status.getIn(['account', 'id']) === me || withDismiss) { menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); } if (status.getIn(['account', 'id']) === me) { if (publicStatus) { menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick }); } else { if (status.get('visibility') === 'private') { menu.push({ text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog_private), action: this.handleReblogClick }); } } menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); menu.push({ text: intl.formatMessage(messages.redraft), action: this.handleRedraftClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.handleMentionClick }); menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.handleDirectClick }); menu.push(null); if (relationship && relationship.get('muting')) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.handleMuteClick }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.handleMuteClick }); } if (relationship && relationship.get('blocking')) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.handleBlockClick }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.handleBlockClick }); } menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.handleReport }); if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (relationship && relationship.get('domain_blocking')) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.handleUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.handleBlockDomain }); } } if (isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${status.getIn(['account', 'id'])}` }); menu.push({ text: intl.formatMessage(messages.admin_status), href: `/admin/accounts/${status.getIn(['account', 'id'])}/statuses/${status.get('id')}` }); } } if (status.get('visibility') === 'direct') { reblogIcon = 'envelope'; } else if (status.get('visibility') === 'private') { reblogIcon = 'lock'; } if (status.get('in_reply_to_id', null) === null) { replyIcon = 'reply'; replyTitle = intl.formatMessage(messages.reply); } else { replyIcon = 'reply-all'; replyTitle = intl.formatMessage(messages.replyAll); } const shareButton = ('share' in navigator) && publicStatus && ( <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShareClick} /> ); return ( <div className='status__action-bar'> <div className='status__action-bar__counter'><IconButton className='status__action-bar-button' title={replyTitle} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} /><span className='status__action-bar__counter__label' >{obfuscatedCount(status.get('replies_count'))}</span></div> <IconButton className='status__action-bar-button' disabled={!publicStatus} active={status.get('reblogged')} pressed={status.get('reblogged')} title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /> <IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} pressed={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} /> {shareButton} <div className='status__action-bar-dropdown'> <DropdownMenuContainer disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> </div> </div> ); } }
packages/material-ui-icons/src/LinkRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 7h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c1.65 0 3 1.35 3 3s-1.35 3-3 3h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c2.76 0 5-2.24 5-5s-2.24-5-5-5zm-9 5c0 .55.45 1 1 1h6c.55 0 1-.45 1-1s-.45-1-1-1H9c-.55 0-1 .45-1 1zm2 3H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h3c.55 0 1-.45 1-1s-.45-1-1-1H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h3c.55 0 1-.45 1-1s-.45-1-1-1z" /> , 'LinkRounded');
client/src/component/ListView.js
wujichao/wencheng
/** * Created by wujichao on 16/4/28. */ "use strict"; import React from 'react'; import { Cells, CellsTitle, CellsTips, Cell, CellHeader, CellBody, CellFooter, } from 'react-weui'; /* headerView section cell(可配置cell)? 先title subtitle + jumpUrl footerView */ export default class ListView extends React.Component { constructor (props) { super(props); this.state = { loaded: false }; } componentWillMount () { } componentDidMount () { } componentWillUnmount () { } componentWillReceiveProps(nextProps) { this.setState({ loaded: true }); } render() { var section_titles = this.props.sections.map((section) => { return (<CellsTitle style={{height:'1.5em'}}>{section.header.title}</CellsTitle>); }); var section_rows = this.props.sections.map((section) => { var rows = []; for (var i = 0; i < section.rows.length; i++) { var item = section.rows[i]; if (!item.key) { throw new Error('必须提供唯一的key'); } rows.push(<Cell href={item.jumpUrl} key={item.key}> <CellBody style={{minWidth:'27%'}}> {item.title} </CellBody> <CellFooter> {item.subTitle} </CellFooter> </Cell>); } return (<Cells access={!!section.header.access}>{rows}</Cells>); }); var table = []; for (var i = 0; i < section_titles.length; i++) { table.push(section_titles[i]); table.push(section_rows[i]); } var components = []; if (this.props.headerView) { components.push(this.props.headerView) } if (table.length > 0) { components.push(table); } if (this.props.footerView) { components.push(this.props.footerView) } if (components.length === 0) { if (this.state.loaded) { return ( <div style={{textAlign:'center', marginTop:'38%'}}> 没有数据 </div> ); } else { return ( <div>{null}</div> ); } } else { return ( <div> {components} </div> ); } } } /* sections = [ { header:{title:'', access:true ...}, rows:[{title, subTitle, jumpUrl}, {}] } ] 其中access只能按section配置, 不能指定单独cell */ ListView.defaultProps = { sections: [] }; ListView.propTypes = { sections: React.PropTypes.array, headerView: React.PropTypes.element, footerView: React.PropTypes.element, };
src/App.js
cityofsurrey/polltal-app
import React from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' import { ApolloProvider, ApolloClient, createNetworkInterface } from 'react-apollo' import { Provider } from 'react-redux' import Routes from './routes' // Base stylesheets import './normalize.css' import './app.css' // Setup Apollo client const createClient = () => ( new ApolloClient({ networkInterface: createNetworkInterface({ uri: `${process.env.POLLTAL_API}/graphql`, }), }) ) function App(props) { return ( <ApolloProvider client={createClient()}> <Provider store={props.store}> <div style={{ position: 'relative', overflowX: 'hidden' }}> <Helmet titleTemplate="%s | Some Boilerplate" meta={[ { charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, ]} /> <Routes /> </div> </Provider> </ApolloProvider> ) } App.propTypes = { store: PropTypes.object.isRequired, // eslint-disable-line } export default App
app/containers/DevTools.js
communicode-source/communicode
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" defaultIsVisible={false}> <LogMonitor /> </DockMonitor>, );
dist/Partials/Years.js
A-Kasaaian/react-advance-jalaali-datepicker
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "react"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("react")); } else { var mod = { exports: {} }; factory(mod.exports, global.react); global.Years = mod.exports; } })(this, function (exports, _react) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _react2 = _interopRequireDefault(_react); 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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 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 mapObj = { 1: "۱", 2: "۲", 3: "۳", 4: "۴", 5: "۵", 6: "۶", 7: "۷", 8: "۸", 9: "۹", 0: "۰" }; var Years = function (_React$Component) { _inherits(Years, _React$Component); function Years(props) { _classCallCheck(this, Years); var _this = _possibleConstructorReturn(this, (Years.__proto__ || Object.getPrototypeOf(Years)).call(this, props)); _this.yearChanged = _this.yearChanged.bind(_this); _this.state = { year: _this.props.year, error: "" }; return _this; } _createClass(Years, [{ key: "yearChanged", value: function yearChanged() { var year = this.refs.year; var changeEvent = this.props.changeEvent; this.setState({ year: year.value }); if (year.value.length == 4 && year.value > 1300 && year.value < 1500) { this.setState({ editable: false, error: "" }); if (!!changeEvent) changeEvent(parseInt(year.value)); } else this.setState({ error: "سال ۴ رقم و درفاصله ۱۳۰۰ تا ۱۵۰۰ باشد" }); } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextprops) { this.setState({ year: nextprops.year }); } }, { key: "render", value: function render() { var _this2 = this; var _state = this.state, error = _state.error, year = _state.year, editable = _state.editable; var yearString = year.toString().replace(/1|2|3|4|5|6|7|8|9|0/gi, function (e) { return mapObj[e]; }); return _react2.default.createElement( "div", { className: "JC-years" }, _react2.default.createElement( "span", null, "\u0633\u0627\u0644: " ), !editable && _react2.default.createElement( "span", { className: "number", style: { cursor: "pointer" }, onClick: function onClick() { return _this2.setState({ editable: true }); } }, yearString ), editable && _react2.default.createElement("input", { type: "tel", ref: "year", placeholder: "\u0633\u0627\u0644", onChange: this.yearChanged, onBlur: this.yearChanged, value: year }), editable && _react2.default.createElement("div", { onClick: this.yearChanged, style: { content: "&quot;&quot", position: "absolute", width: "100%", height: "100%", top: "0px", zIndex: "1", left: "0px" } }), error && _react2.default.createElement( "div", { className: "JC-tooltip" }, _react2.default.createElement( "p", { style: { color: "red" } }, error ) ) ); } }]); return Years; }(_react2.default.Component); exports.default = Years; });
packages/material-ui-icons/src/StraightenRounded.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 10H4c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h1v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h1c.55 0 1 .45 1 1v6c0 .55-.45 1-1 1z" /></g></React.Fragment> , 'StraightenRounded');
src/components/layout.js
openregister/specification
import React from 'react'; import PropTypes from 'prop-types'; import { StaticQuery, graphql } from 'gatsby'; import 'prismjs/themes/prism.css'; const Layout = ({children}) => ( <StaticQuery query={graphql` query LayoutQuery { core: coreToml { title } }`} render={() => { return ( <React.Fragment> {children} </React.Fragment> );}} /> ); Layout.propTypes = { children: PropTypes.any.isRequired }; export default Layout;
ajax/libs/reactive-coffee/1.2.2/reactive-coffee.js
qrohlf/cdnjs
(function() { var rxFactory, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; rxFactory = function(_, $) { var DepArray, DepCell, DepMap, DepMgr, Ev, FakeObsCell, FakeSrcCell, IndexedArray, IndexedDepArray, IndexedMappedDepArray, MappedDepArray, ObsArray, ObsCell, ObsMap, ObsMapEntryCell, RawHtml, Recorder, SrcArray, SrcCell, SrcMap, SrcMapEntryCell, asyncBind, bind, depMgr, ev, events, firstWhere, flatten, lagBind, mkAtts, mkMap, mktag, mkuid, nextUid, nthWhere, permToSplices, popKey, postLagBind, prop, propSet, props, recorder, rx, rxt, setDynProp, setProp, specialAttrs, sum, tag, tags, _fn, _i, _len; rx = {}; nextUid = 0; mkuid = function() { return nextUid += 1; }; popKey = function(x, k) { var v; if (!(k in x)) { throw new Error('object has no key ' + k); } v = x[k]; delete x[k]; return v; }; nthWhere = function(xs, n, f) { var i, x, _i, _len; for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) { x = xs[i]; if (f(x) && (n -= 1) < 0) { return [x, i]; } } return [null, -1]; }; firstWhere = function(xs, f) { return nthWhere(xs, 0, f); }; mkMap = function(xs) { var k, map, v, _i, _len, _ref; if (xs == null) { xs = []; } map = Object.create != null ? Object.create(null) : {}; if (_.isArray(xs)) { for (_i = 0, _len = xs.length; _i < _len; _i++) { _ref = xs[_i], k = _ref[0], v = _ref[1]; map[k] = v; } } else { for (k in xs) { v = xs[k]; map[k] = v; } } return map; }; sum = function(xs) { var n, x, _i, _len; n = 0; for (_i = 0, _len = xs.length; _i < _len; _i++) { x = xs[_i]; n += x; } return n; }; DepMgr = rx.DepMgr = (function() { function DepMgr() { this.uid2src = {}; this.buffering = 0; this.buffer = []; } DepMgr.prototype.sub = function(uid, src) { return this.uid2src[uid] = src; }; DepMgr.prototype.unsub = function(uid) { return popKey(this.uid2src, uid); }; DepMgr.prototype.transaction = function(f) { var b, res, _i, _len, _ref; this.buffering += 1; try { res = f(); } finally { this.buffering -= 1; if (this.buffering === 0) { _ref = this.buffer; for (_i = 0, _len = _ref.length; _i < _len; _i++) { b = _ref[_i]; b(); } this.buffer = []; } } return res; }; return DepMgr; })(); rx._depMgr = depMgr = new DepMgr(); Ev = rx.Ev = (function() { function Ev(inits) { this.inits = inits; this.subs = mkMap(); } Ev.prototype.sub = function(listener) { var init, uid, _i, _len, _ref; uid = mkuid(); if (this.inits != null) { _ref = this.inits(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { init = _ref[_i]; listener(init); } } this.subs[uid] = listener; depMgr.sub(uid, this); return uid; }; Ev.prototype.pub = function(data) { var listener, uid, _ref, _results; if (depMgr.buffering) { return depMgr.buffer.push((function(_this) { return function() { return _this.pub(data); }; })(this)); } else { _ref = this.subs; _results = []; for (uid in _ref) { listener = _ref[uid]; _results.push(listener(data)); } return _results; } }; Ev.prototype.unsub = function(uid) { popKey(this.subs, uid); return depMgr.unsub(uid, this); }; Ev.prototype.scoped = function(listener, context) { var uid; uid = this.sub(listener); try { return context(); } finally { this.unsub(uid); } }; return Ev; })(); rx.skipFirst = function(f) { var first; first = true; return function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (first) { return first = false; } else { return f.apply(null, args); } }; }; Recorder = rx.Recorder = (function() { function Recorder() { this.stack = []; this.isMutating = false; this.isIgnoring = false; this.onMutationWarning = new Ev(); } Recorder.prototype.record = function(dep, f) { var wasIgnoring, wasMutating; if (this.stack.length > 0 && !this.isMutating) { _(this.stack).last().addNestedBind(dep); } this.stack.push(dep); wasMutating = this.isMutating; this.isMutating = false; wasIgnoring = this.isIgnoring; this.isIgnoring = false; try { return f(); } finally { this.isIgnoring = wasIgnoring; this.isMutating = wasMutating; this.stack.pop(); } }; Recorder.prototype.sub = function(sub) { var handle, topCell; if (this.stack.length > 0 && !this.isIgnoring) { topCell = _(this.stack).last(); return handle = sub(topCell); } }; Recorder.prototype.addCleanup = function(cleanup) { if (this.stack.length > 0) { return _(this.stack).last().addCleanup(cleanup); } }; Recorder.prototype.mutating = function(f) { var wasMutating; if (this.stack.length > 0) { console.warn('Mutation to observable detected during a bind context'); this.onMutationWarning.pub(null); } wasMutating = this.isMutating; this.isMutating = true; try { return f(); } finally { this.isMutating = wasMutating; } }; Recorder.prototype.ignoring = function(f) { var wasIgnoring; wasIgnoring = this.isIgnoring; this.isIgnoring = true; try { return f(); } finally { this.isIgnoring = wasIgnoring; } }; return Recorder; })(); rx._recorder = recorder = new Recorder(); rx.asyncBind = asyncBind = function(init, f) { var dep; dep = new DepCell(f, init); dep.refresh(); return dep; }; rx.bind = bind = function(f) { return asyncBind(null, function() { return this.done(this.record(f)); }); }; rx.lagBind = lagBind = function(lag, init, f) { var timeout; timeout = null; return asyncBind(init, function() { if (timeout != null) { clearTimeout(timeout); } return timeout = setTimeout((function(_this) { return function() { return _this.done(_this.record(f)); }; })(this), lag); }); }; rx.postLagBind = postLagBind = function(init, f) { var timeout; timeout = null; return asyncBind(init, function() { var ms, val, _ref; _ref = this.record(f), val = _ref.val, ms = _ref.ms; if (timeout != null) { clearTimeout(timeout); } return timeout = setTimeout(((function(_this) { return function() { return _this.done(val); }; })(this)), ms); }); }; rx.snap = function(f) { return recorder.ignoring(f); }; rx.onDispose = function(cleanup) { return recorder.addCleanup(cleanup); }; rx.autoSub = function(ev, listener) { var subid; subid = ev.sub(listener); rx.onDispose(function() { return ev.unsub(subid); }); return subid; }; ObsCell = rx.ObsCell = (function() { function ObsCell(x) { var _ref; this.x = x; this.x = (_ref = this.x) != null ? _ref : null; this.onSet = new Ev((function(_this) { return function() { return [[null, _this.x]]; }; })(this)); } ObsCell.prototype.get = function() { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onSet, function() { return target.refresh(); }); }; })(this)); return this.x; }; return ObsCell; })(); SrcCell = rx.SrcCell = (function(_super) { __extends(SrcCell, _super); function SrcCell() { return SrcCell.__super__.constructor.apply(this, arguments); } SrcCell.prototype.set = function(x) { return recorder.mutating((function(_this) { return function() { var old; if (_this.x !== x) { old = _this.x; _this.x = x; _this.onSet.pub([old, x]); return old; } }; })(this)); }; return SrcCell; })(ObsCell); DepCell = rx.DepCell = (function(_super) { __extends(DepCell, _super); function DepCell(body, init) { this.body = body; DepCell.__super__.constructor.call(this, init != null ? init : null); this.refreshing = false; this.nestedBinds = []; this.cleanups = []; } DepCell.prototype.refresh = function() { var env, isSynchronous, old, realDone, syncResult; if (!this.refreshing) { old = this.x; realDone = (function(_this) { return function(x) { _this.x = x; return _this.onSet.pub([old, _this.x]); }; })(this); ({ recorded: false }); syncResult = null; isSynchronous = false; env = { record: (function(_this) { return function(f) { var recorded, res; if (!_this.refreshing) { _this.disconnect(); if (recorded) { throw new Error('this refresh has already recorded its dependencies'); } _this.refreshing = true; recorded = true; try { res = recorder.record(_this, function() { return f.call(env); }); } finally { _this.refreshing = false; } if (isSynchronous) { realDone(syncResult); } return res; } }; })(this), done: (function(_this) { return function(x) { if (old !== x) { if (_this.refreshing) { isSynchronous = true; return syncResult = x; } else { return realDone(x); } } }; })(this) }; return this.body.call(env); } }; DepCell.prototype.disconnect = function() { var cleanup, nestedBind, _i, _j, _len, _len1, _ref, _ref1; _ref = this.cleanups; for (_i = 0, _len = _ref.length; _i < _len; _i++) { cleanup = _ref[_i]; cleanup(); } _ref1 = this.nestedBinds; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { nestedBind = _ref1[_j]; nestedBind.disconnect(); } this.nestedBinds = []; return this.cleanups = []; }; DepCell.prototype.addNestedBind = function(nestedBind) { return this.nestedBinds.push(nestedBind); }; DepCell.prototype.addCleanup = function(cleanup) { return this.cleanups.push(cleanup); }; return DepCell; })(ObsCell); ObsArray = rx.ObsArray = (function() { function ObsArray(xs, diff) { this.xs = xs != null ? xs : []; this.diff = diff != null ? diff : rx.basicDiff(); this.onChange = new Ev((function(_this) { return function() { return [[0, [], _this.xs]]; }; })(this)); this.indexed_ = null; } ObsArray.prototype.all = function() { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function() { return target.refresh(); }); }; })(this)); return _.clone(this.xs); }; ObsArray.prototype.raw = function() { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function() { return target.refresh(); }); }; })(this)); return this.xs; }; ObsArray.prototype.at = function(i) { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; if (index === i) { return target.refresh(); } }); }; })(this)); return this.xs[i]; }; ObsArray.prototype.length = function() { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; if (removed.length !== added.length) { return target.refresh(); } }); }; })(this)); return this.xs.length; }; ObsArray.prototype.map = function(f) { var ys; ys = new MappedDepArray(); rx.autoSub(this.onChange, function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; return ys.realSplice(index, removed.length, added.map(f)); }); return ys; }; ObsArray.prototype.indexed = function() { if (this.indexed_ == null) { this.indexed_ = new IndexedDepArray(); rx.autoSub(this.onChange, (function(_this) { return function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; return _this.indexed_.realSplice(index, removed.length, added); }; })(this)); } return this.indexed_; }; ObsArray.prototype.concat = function(that) { return rx.concat(this, that); }; ObsArray.prototype.realSplice = function(index, count, additions) { var removed; removed = this.xs.splice.apply(this.xs, [index, count].concat(additions)); return this.onChange.pub([index, removed, additions]); }; ObsArray.prototype._update = function(val, diff) { var additions, count, fullSplice, index, old, splice, splices, x, _i, _len, _ref, _results; if (diff == null) { diff = this.diff; } old = this.xs; fullSplice = [0, old.length, val]; x = null; splices = diff != null ? (_ref = permToSplices(old.length, val, diff(old, val))) != null ? _ref : [fullSplice] : [fullSplice]; _results = []; for (_i = 0, _len = splices.length; _i < _len; _i++) { splice = splices[_i]; index = splice[0], count = splice[1], additions = splice[2]; _results.push(this.realSplice(index, count, additions)); } return _results; }; return ObsArray; })(); SrcArray = rx.SrcArray = (function(_super) { __extends(SrcArray, _super); function SrcArray() { return SrcArray.__super__.constructor.apply(this, arguments); } SrcArray.prototype.spliceArray = function(index, count, additions) { return recorder.mutating((function(_this) { return function() { return _this.realSplice(index, count, additions); }; })(this)); }; SrcArray.prototype.splice = function() { var additions, count, index; index = arguments[0], count = arguments[1], additions = 3 <= arguments.length ? __slice.call(arguments, 2) : []; return this.spliceArray(index, count, additions); }; SrcArray.prototype.insert = function(x, index) { return this.splice(index, 0, x); }; SrcArray.prototype.remove = function(x) { var i; i = _(this.raw()).indexOf(x); if (i >= 0) { return this.removeAt(i); } }; SrcArray.prototype.removeAt = function(index) { return this.splice(index, 1); }; SrcArray.prototype.push = function(x) { return this.splice(this.length(), 0, x); }; SrcArray.prototype.put = function(i, x) { return this.splice(i, 1, x); }; SrcArray.prototype.replace = function(xs) { return this.spliceArray(0, this.length(), xs); }; SrcArray.prototype.update = function(xs) { return recorder.mutating((function(_this) { return function() { return _this._update(xs); }; })(this)); }; return SrcArray; })(ObsArray); MappedDepArray = rx.MappedDepArray = (function(_super) { __extends(MappedDepArray, _super); function MappedDepArray() { return MappedDepArray.__super__.constructor.apply(this, arguments); } return MappedDepArray; })(ObsArray); IndexedDepArray = rx.IndexedDepArray = (function(_super) { __extends(IndexedDepArray, _super); function IndexedDepArray(xs, diff) { var i, x; if (xs == null) { xs = []; } IndexedDepArray.__super__.constructor.call(this, xs, diff); this.is = (function() { var _i, _len, _ref, _results; _ref = this.xs; _results = []; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { x = _ref[i]; _results.push(rx.cell(i)); } return _results; }).call(this); this.onChange = new Ev((function(_this) { return function() { return [[0, [], _.zip(_this.xs, _this.is)]]; }; })(this)); } IndexedDepArray.prototype.map = function(f) { var ys; ys = new IndexedMappedDepArray(); rx.autoSub(this.onChange, function(_arg) { var a, added, i, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; return ys.realSplice(index, removed.length, (function() { var _i, _len, _ref, _results; _results = []; for (_i = 0, _len = added.length; _i < _len; _i++) { _ref = added[_i], a = _ref[0], i = _ref[1]; _results.push(f(a, i)); } return _results; })()); }); return ys; }; IndexedDepArray.prototype.realSplice = function(index, count, additions) { var i, newIs, offset, removed, _i, _len, _ref, _ref1, _ref2; removed = (_ref = this.xs).splice.apply(_ref, [index, count].concat(__slice.call(additions))); _ref1 = this.is.slice(index + count); for (offset = _i = 0, _len = _ref1.length; _i < _len; offset = ++_i) { i = _ref1[offset]; i.set(index + additions.length + offset); } newIs = (function() { var _j, _ref2, _results; _results = []; for (i = _j = 0, _ref2 = additions.length; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; i = 0 <= _ref2 ? ++_j : --_j) { _results.push(rx.cell(index + i)); } return _results; })(); (_ref2 = this.is).splice.apply(_ref2, [index, count].concat(__slice.call(newIs))); return this.onChange.pub([index, removed, _.zip(additions, newIs)]); }; return IndexedDepArray; })(ObsArray); IndexedMappedDepArray = rx.IndexedMappedDepArray = (function(_super) { __extends(IndexedMappedDepArray, _super); function IndexedMappedDepArray() { return IndexedMappedDepArray.__super__.constructor.apply(this, arguments); } return IndexedMappedDepArray; })(IndexedDepArray); DepArray = rx.DepArray = (function(_super) { __extends(DepArray, _super); function DepArray(f, diff) { this.f = f; DepArray.__super__.constructor.call(this, [], diff); rx.autoSub((bind((function(_this) { return function() { return _this.f(); }; })(this))).onSet, (function(_this) { return function(_arg) { var old, val; old = _arg[0], val = _arg[1]; return _this._update(val); }; })(this)); } return DepArray; })(ObsArray); IndexedArray = rx.IndexedArray = (function(_super) { __extends(IndexedArray, _super); function IndexedArray(xs) { this.xs = xs; } IndexedArray.prototype.map = function(f) { var ys; ys = new MappedDepArray(); rx.autoSub(this.xs.onChange, function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; return ys.realSplice(index, removed.length, added.map(f)); }); return ys; }; return IndexedArray; })(DepArray); rx.concat = function() { var repLens, xs, xss, ys; xss = 1 <= arguments.length ? __slice.call(arguments, 0) : []; ys = new MappedDepArray(); repLens = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = xss.length; _i < _len; _i++) { xs = xss[_i]; _results.push(0); } return _results; })(); xss.map(function(xs, i) { return rx.autoSub(xs.onChange, function(_arg) { var added, index, removed, xsOffset; index = _arg[0], removed = _arg[1], added = _arg[2]; xsOffset = sum(repLens.slice(0, i)); repLens[i] += added.length - removed.length; return ys.realSplice(xsOffset + index, removed.length, added); }); }); return ys; }; FakeSrcCell = rx.FakeSrcCell = (function(_super) { __extends(FakeSrcCell, _super); function FakeSrcCell(_getter, _setter) { this._getter = _getter; this._setter = _setter; } FakeSrcCell.prototype.get = function() { return this._getter(); }; FakeSrcCell.prototype.set = function(x) { return this._setter(x); }; return FakeSrcCell; })(SrcCell); FakeObsCell = rx.FakeObsCell = (function(_super) { __extends(FakeObsCell, _super); function FakeObsCell(_getter) { this._getter = _getter; } FakeObsCell.prototype.get = function() { return this._getter(); }; return FakeObsCell; })(ObsCell); SrcMapEntryCell = rx.MapEntryCell = (function(_super) { __extends(MapEntryCell, _super); function MapEntryCell(_map, _key) { this._map = _map; this._key = _key; } MapEntryCell.prototype.get = function() { return this._map.get(this._key); }; MapEntryCell.prototype.set = function(x) { return this._map.put(this._key, x); }; return MapEntryCell; })(FakeSrcCell); ObsMapEntryCell = rx.ObsMapEntryCell = (function(_super) { __extends(ObsMapEntryCell, _super); function ObsMapEntryCell(_map, _key) { this._map = _map; this._key = _key; } ObsMapEntryCell.prototype.get = function() { return this._map.get(this._key); }; return ObsMapEntryCell; })(FakeObsCell); ObsMap = rx.ObsMap = (function() { function ObsMap(x) { this.x = x != null ? x : {}; this.onAdd = new Ev(function() { var k, v, _results; _results = []; for (k in x) { v = x[k]; _results.push([k, v]); } return _results; }); this.onRemove = new Ev(); this.onChange = new Ev(); } ObsMap.prototype.get = function(key) { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onAdd, function(_arg) { var subkey, val; subkey = _arg[0], val = _arg[1]; if (key === subkey) { return target.refresh(); } }); }; })(this)); recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function(_arg) { var old, subkey, val; subkey = _arg[0], old = _arg[1], val = _arg[2]; if (key === subkey) { return target.refresh(); } }); }; })(this)); recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onRemove, function(_arg) { var old, subkey; subkey = _arg[0], old = _arg[1]; if (key === subkey) { return target.refresh(); } }); }; })(this)); return this.x[key]; }; ObsMap.prototype.all = function() { recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onAdd, function() { return target.refresh(); }); }; })(this)); recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onChange, function() { return target.refresh(); }); }; })(this)); recorder.sub((function(_this) { return function(target) { return rx.autoSub(_this.onRemove, function() { return target.refresh(); }); }; })(this)); return _.clone(this.x); }; ObsMap.prototype.realPut = function(key, val) { var old; if (key in this.x) { old = this.x[key]; this.x[key] = val; this.onChange.pub([key, old, val]); return old; } else { this.x[key] = val; this.onAdd.pub([key, val]); return void 0; } }; ObsMap.prototype.realRemove = function(key) { var val; val = popKey(this.x, key); this.onRemove.pub([key, val]); return val; }; ObsMap.prototype.cell = function(key) { return new ObsMapEntryCell(this, key); }; return ObsMap; })(); SrcMap = rx.SrcMap = (function(_super) { __extends(SrcMap, _super); function SrcMap() { return SrcMap.__super__.constructor.apply(this, arguments); } SrcMap.prototype.put = function(key, val) { return recorder.mutating((function(_this) { return function() { return _this.realPut(key, val); }; })(this)); }; SrcMap.prototype.remove = function(key) { return recorder.mutating((function(_this) { return function() { return _this.realRemove(key); }; })(this)); }; SrcMap.prototype.cell = function(key) { return new SrcMapEntryCell(this, key); }; SrcMap.prototype.update = function(x) { return recorder.mutating((function(_this) { return function() { var k, v, _i, _len, _ref, _results; _ref = _.difference(_.keys(_this.x), _.keys(x)); for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; _this.realRemove(k); } _results = []; for (k in x) { v = x[k]; if (!(k in _this.x) || _this.x[k] !== v) { _results.push(_this.realPut(k, v)); } } return _results; }; })(this)); }; return SrcMap; })(ObsMap); DepMap = rx.DepMap = (function(_super) { __extends(DepMap, _super); function DepMap(f) { this.f = f; DepMap.__super__.constructor.call(this); rx.autoSub(new DepCell(this.f).onSet, function(_arg) { var k, old, v, val, _results; old = _arg[0], val = _arg[1]; for (k in old) { v = old[k]; if (!(k in val)) { this.realRemove(k); } } _results = []; for (k in val) { v = val[k]; if (this.x[k] !== v) { _results.push(this.realPut(k, v)); } else { _results.push(void 0); } } return _results; }); } return DepMap; })(ObsMap); rx.liftSpec = function(obj) { var name, type, val; return _.object((function() { var _i, _len, _ref, _results; _ref = Object.getOwnPropertyNames(obj); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; val = obj[name]; if ((val != null) && (val instanceof rx.ObsMap || val instanceof rx.ObsCell || val instanceof rx.ObsArray)) { continue; } type = _.isFunction(val) ? null : _.isArray(val) ? 'array' : 'cell'; _results.push([ name, { type: type, val: val } ]); } return _results; })()); }; rx.lift = function(x, fieldspec) { var c, name, spec; if (fieldspec == null) { fieldspec = rx.liftSpec(x); } for (name in fieldspec) { spec = fieldspec[name]; if (!_.some((function() { var _i, _len, _ref, _results; _ref = [ObsCell, ObsArray, ObsMap]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { c = _ref[_i]; _results.push(x[name] instanceof c); } return _results; })())) { x[name] = (function() { switch (spec.type) { case 'cell': return rx.cell(x[name]); case 'array': return rx.array(x[name]); case 'map': return rx.map(x[name]); default: return x[name]; } })(); } } return x; }; rx.unlift = function(x) { var k, v; return _.object((function() { var _results; _results = []; for (k in x) { v = x[k]; _results.push([k, v instanceof rx.ObsCell ? v.get() : v instanceof rx.ObsArray ? v.all() : v]); } return _results; })()); }; rx.reactify = function(obj, fieldspec) { var arr, methName, name, spec; if (_.isArray(obj)) { arr = rx.array(_.clone(obj)); Object.defineProperties(obj, _.object((function() { var _i, _len, _ref, _results; _ref = _.functions(arr); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { methName = _ref[_i]; if (methName !== 'length') { _results.push((function(methName) { var meth, newMeth, spec; meth = obj[methName]; newMeth = function() { var args, res, _ref1; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (meth != null) { res = meth.call.apply(meth, [obj].concat(__slice.call(args))); } (_ref1 = arr[methName]).call.apply(_ref1, [arr].concat(__slice.call(args))); return res; }; spec = { configurable: true, enumerable: false, value: newMeth, writable: true }; return [methName, spec]; })(methName)); } } return _results; })())); return obj; } else { return Object.defineProperties(obj, _.object((function() { var _results; _results = []; for (name in fieldspec) { spec = fieldspec[name]; _results.push((function(name, spec) { var desc, obs, view, _ref, _ref1; desc = null; switch (spec.type) { case 'cell': obs = rx.cell((_ref = spec.val) != null ? _ref : null); desc = { configurable: true, enumerable: true, get: function() { return obs.get(); }, set: function(x) { return obs.set(x); } }; break; case 'array': view = rx.reactify((_ref1 = spec.val) != null ? _ref1 : []); desc = { configurable: true, enumerable: true, get: function() { view.raw(); return view; }, set: function(x) { view.splice.apply(view, [0, view.length].concat(__slice.call(x))); return view; } }; break; default: throw new Error("Unknown observable type: " + type); } return [name, desc]; })(name, spec)); } return _results; })())); } }; rx.autoReactify = function(obj) { var name, type, val; return rx.reactify(obj, _.object((function() { var _i, _len, _ref, _results; _ref = Object.getOwnPropertyNames(obj); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; val = obj[name]; if (val instanceof ObsMap || val instanceof ObsCell || val instanceof ObsArray) { continue; } type = _.isFunction(val) ? null : _.isArray(val) ? 'array' : 'cell'; _results.push([ name, { type: type, val: val } ]); } return _results; })())); }; _.extend(rx, { cell: function(x) { return new SrcCell(x); }, array: function(xs, diff) { return new SrcArray(xs, diff); }, map: function(x) { return new SrcMap(x); } }); rx.flatten = function(xs) { return new DepArray(function() { var x; return _((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = xs.length; _i < _len; _i++) { x = xs[_i]; if (x instanceof ObsArray) { _results.push(x.raw()); } else if (x instanceof ObsCell) { _results.push(x.get()); } else { _results.push(x); } } return _results; })()).chain().flatten(true).filter(function(x) { return x != null; }).value(); }); }; flatten = function(xss) { var xs; xs = _.flatten(xss); return rx.cellToArray(bind(function() { return _.flatten(xss); })); }; rx.cellToArray = function(cell, diff) { return new DepArray((function() { return cell.get(); }), diff); }; rx.basicDiff = function(key) { if (key == null) { key = rx.smartUidify; } return function(oldXs, newXs) { var i, oldKeys, x, _i, _len, _ref, _results; oldKeys = mkMap((function() { var _i, _len, _results; _results = []; for (i = _i = 0, _len = oldXs.length; _i < _len; i = ++_i) { x = oldXs[i]; _results.push([key(x), i]); } return _results; })()); _results = []; for (_i = 0, _len = newXs.length; _i < _len; _i++) { x = newXs[_i]; _results.push((_ref = oldKeys[key(x)]) != null ? _ref : -1); } return _results; }; }; rx.uidify = function(x) { var _ref; return (_ref = x.__rxUid) != null ? _ref : (Object.defineProperty(x, '__rxUid', { enumerable: false, value: mkuid() })).__rxUid; }; rx.smartUidify = function(x) { if (_.isObject(x)) { return rx.uidify(x); } else { return JSON.stringify(x); } }; permToSplices = function(oldLength, newXs, perm) { var cur, i, last, refs, splice, splices; refs = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = perm.length; _i < _len; _i++) { i = perm[_i]; if (i >= 0) { _results.push(i); } } return _results; })(); if (_.some((function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = refs.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(refs[i + 1] - refs[i] <= 0); } return _results; })())) { return null; } splices = []; last = -1; i = 0; while (i < perm.length) { while (i < perm.length && perm[i] === last + 1) { last += 1; i += 1; } splice = { index: i, count: 0, additions: [] }; while (i < perm.length && perm[i] === -1) { splice.additions.push(newXs[i]); i += 1; } cur = i === perm.length ? oldLength : perm[i]; splice.count = cur - (last + 1); if (splice.count > 0 || splice.additions.length > 0) { splices.push([splice.index, splice.count, splice.additions]); } last = cur; i += 1; } return splices; }; rx.transaction = function(f) { return depMgr.transaction(f); }; if ($ != null) { $.fn.rx = function(prop) { var checked, focused, map, val; map = this.data('rx-map'); if (map == null) { this.data('rx-map', map = mkMap()); } if (prop in map) { return map[prop]; } return map[prop] = (function() { switch (prop) { case 'focused': focused = rx.cell(this.is(':focus')); this.focus(function() { return focused.set(true); }); this.blur(function() { return focused.set(false); }); return focused; case 'val': val = rx.cell(this.val()); this.change((function(_this) { return function() { return val.set(_this.val()); }; })(this)); this.on('input', (function(_this) { return function() { return val.set(_this.val()); }; })(this)); return val; case 'checked': checked = rx.cell(this.is(':checked')); this.change((function(_this) { return function() { return checked.set(_this.is(':checked')); }; })(this)); return checked; default: throw new Error('Unknown reactive property type'); } }).call(this); }; rxt = {}; RawHtml = rxt.RawHtml = (function() { function RawHtml(html) { this.html = html; } return RawHtml; })(); events = ["blur", "change", "click", "dblclick", "error", "focus", "focusin", "focusout", "hover", "keydown", "keypress", "keyup", "load", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "ready", "resize", "scroll", "select", "submit", "toggle", "unload"]; specialAttrs = rxt.specialAttrs = { init: function(elt, fn) { return fn.call(elt); } }; _fn = function(ev) { return specialAttrs[ev] = function(elt, fn) { return elt[ev](function(e) { return fn.call(elt, e); }); }; }; for (_i = 0, _len = events.length; _i < _len; _i++) { ev = events[_i]; _fn(ev); } props = ['async', 'autofocus', 'checked', 'location', 'multiple', 'readOnly', 'selected', 'selectedIndex', 'tagName', 'nodeName', 'nodeType', 'ownerDocument', 'defaultChecked', 'defaultSelected']; propSet = _.object((function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = props.length; _j < _len1; _j++) { prop = props[_j]; _results.push([prop, null]); } return _results; })()); setProp = function(elt, prop, val) { if (prop === 'value') { return elt.val(val); } else if (prop in propSet) { return elt.prop(prop, val); } else { return elt.attr(prop, val); } }; setDynProp = function(elt, prop, val, xform) { if (xform == null) { xform = _.identity; } if (val instanceof ObsCell) { return rx.autoSub(val.onSet, function(_arg) { var n, o; o = _arg[0], n = _arg[1]; return setProp(elt, prop, xform(n)); }); } else { return setProp(elt, prop, xform(val)); } }; rxt.mkAtts = mkAtts = function(attstr) { return (function(atts) { var classes, cls, id; id = attstr.match(/[#](\w+)/); if (id) { atts.id = id[1]; } classes = attstr.match(/\.\w+/g); if (classes) { atts["class"] = ((function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = classes.length; _j < _len1; _j++) { cls = classes[_j]; _results.push(cls.replace(/^\./, '')); } return _results; })()).join(' '); } return atts; })({}); }; rxt.mktag = mktag = function(tag) { return function(arg1, arg2) { var attrs, contents, elt, key, name, toNodes, updateContents, value, _ref, _ref1; _ref = (arg1 == null) && (arg2 == null) ? [{}, null] : arg1 instanceof Object && (arg2 != null) ? [arg1, arg2] : _.isString(arg1) && (arg2 != null) ? [mkAtts(arg1), arg2] : (arg2 == null) && _.isString(arg1) || _.isNumber(arg1) || arg1 instanceof Element || arg1 instanceof RawHtml || arg1 instanceof $ || _.isArray(arg1) || arg1 instanceof ObsCell || arg1 instanceof ObsArray ? [{}, arg1] : [arg1, null], attrs = _ref[0], contents = _ref[1]; elt = $("<" + tag + "/>"); _ref1 = _.omit(attrs, _.keys(specialAttrs)); for (name in _ref1) { value = _ref1[name]; setDynProp(elt, name, value); } if (contents != null) { toNodes = function(contents) { var child, parsed, _j, _len1, _results; _results = []; for (_j = 0, _len1 = contents.length; _j < _len1; _j++) { child = contents[_j]; if (child != null) { if (_.isString(child) || _.isNumber(child)) { _results.push(document.createTextNode(child)); } else if (child instanceof Element) { _results.push(child); } else if (child instanceof RawHtml) { parsed = $(child.html); if (parsed.length !== 1) { throw new Error('RawHtml must wrap a single element'); } _results.push(parsed[0]); } else if (child instanceof $) { if (child.length !== 1) { throw new Error('jQuery object must wrap a single element'); } _results.push(child[0]); } else { throw new Error("Unknown element type in array: " + child.constructor.name + " (must be string, number, Element, RawHtml, or jQuery objects)"); } } else { _results.push(void 0); } } return _results; }; updateContents = function(contents) { var covers, hasWidth, left, node, nodes, top; elt.html(''); if (_.isArray(contents)) { nodes = toNodes(contents); elt.append(nodes); if (false) { hasWidth = function(node) { var e; try { return ($(node).width() != null) !== 0; } catch (_error) { e = _error; return false; } }; covers = (function() { var _j, _len1, _ref2, _ref3, _results; _ref2 = nodes != null ? nodes : []; _results = []; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { node = _ref2[_j]; if (!(hasWidth(node))) { continue; } _ref3 = $(node).offset(), left = _ref3.left, top = _ref3.top; _results.push($('<div/>').appendTo($('body').first()).addClass('updated-element').offset({ top: top, left: left }).width($(node).width()).height($(node).height())); } return _results; })(); return setTimeout((function() { var cover, _j, _len1, _results; _results = []; for (_j = 0, _len1 = covers.length; _j < _len1; _j++) { cover = covers[_j]; _results.push($(cover).remove()); } return _results; }), 2000); } } else if (_.isString(contents) || _.isNumber(contents) || contents instanceof Element || contents instanceof RawHtml || contents instanceof $) { return updateContents([contents]); } else { throw new Error("Unknown type for element contents: " + contents.constructor.name + " (accepted types: string, number, Element, RawHtml, jQuery object of single element, or array of the aforementioned)"); } }; if (contents instanceof ObsArray) { rx.autoSub(contents.onChange, function(_arg) { var added, index, removed, toAdd; index = _arg[0], removed = _arg[1], added = _arg[2]; elt.contents().slice(index, index + removed.length).remove(); toAdd = toNodes(added); if (index === elt.contents().length) { return elt.append(toAdd); } else { return elt.contents().eq(index).before(toAdd); } }); } else if (contents instanceof ObsCell) { rx.autoSub(contents.onSet, function(_arg) { var old, val; old = _arg[0], val = _arg[1]; return updateContents(val); }); } else { updateContents(contents); } } for (key in attrs) { if (key in specialAttrs) { specialAttrs[key](elt, attrs[key], attrs, contents); } } return elt; }; }; tags = ['html', 'head', 'title', 'base', 'link', 'meta', 'style', 'script', 'noscript', 'body', 'body', 'section', 'nav', 'article', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h1', 'h6', 'header', 'footer', 'address', 'main', 'main', 'p', 'hr', 'pre', 'blockquote', 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'dd', 'figure', 'figcaption', 'div', 'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data', 'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr', 'ins', 'del', 'img', 'iframe', 'embed', 'object', 'param', 'object', 'video', 'audio', 'source', 'video', 'audio', 'track', 'video', 'audio', 'canvas', 'map', 'area', 'area', 'map', 'svg', 'math', 'table', 'caption', 'colgroup', 'col', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'form', 'fieldset', 'legend', 'fieldset', 'label', 'input', 'button', 'select', 'datalist', 'optgroup', 'option', 'select', 'datalist', 'textarea', 'keygen', 'output', 'progress', 'meter', 'details', 'summary', 'details', 'menuitem', 'menu']; rxt.tags = _.object((function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = tags.length; _j < _len1; _j++) { tag = tags[_j]; _results.push([tag, rxt.mktag(tag)]); } return _results; })()); rxt.rawHtml = function(html) { return new RawHtml(html); }; rxt.importTags = (function(_this) { return function(x) { return _(x != null ? x : _this).extend(rxt.tags); }; })(this); rxt.cast = function(value, type) { var key, opts, types; if (type == null) { type = "cell"; } if (_.isString(type)) { switch (type) { case 'array': if (value instanceof rx.ObsArray) { return value; } else if (_.isArray(value)) { return new rx.DepArray(function() { return value; }); } else if (value instanceof rx.ObsCell) { return new rx.DepArray(function() { return value.get(); }); } else { throw new Error('Cannot cast to array: ' + value.constructor.name); } break; case 'cell': if (value instanceof rx.ObsCell) { return value; } else { return bind(function() { return value; }); } break; default: return value; } } else { opts = value; types = type; return _.object((function() { var _results; _results = []; for (key in opts) { value = opts[key]; _results.push([key, types[key] ? rxt.cast(value, types[key]) : value]); } return _results; })()); } }; rxt.trim = $.trim; rxt.dasherize = function(str) { return rxt.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase(); }; rxt.cssify = function(map) { var k, v; return ((function() { var _results; _results = []; for (k in map) { v = map[k]; if (v != null) { _results.push("" + (rxt.dasherize(k)) + ": " + (_.isNumber(v) ? v + 'px' : v) + ";"); } } return _results; })()).join(' '); }; specialAttrs.style = function(elt, value) { return setDynProp(elt, 'style', value, function(val) { if (_.isString(val)) { return val; } else { return rxt.cssify(val); } }); }; rxt.smushClasses = function(xs) { return _(xs).chain().flatten().compact().value().join(' ').replace(/\s+/, ' ').trim(); }; specialAttrs["class"] = function(elt, value) { return setDynProp(elt, 'class', value, function(val) { if (_.isString(val)) { return val; } else { return rxt.smushClasses(val); } }); }; } rx.rxt = rxt; return rx; }; (function(root, factory, deps) { var rx, _; if ((typeof define !== "undefined" && define !== null ? define.amd : void 0) != null) { return define(deps, factory); } else if ((typeof module !== "undefined" && module !== null ? module.exports : void 0) != null) { _ = require('underscore'); rx = factory(_); return module.exports = rx; } else if ((root._ != null) && (root.$ != null)) { return root.rx = factory(root._, root.$); } else { throw "Dependencies are not met for reactive: _ and $ not found"; } })(this, rxFactory, ['underscore', 'jquery']); }).call(this); //# sourceMappingURL=reactive.js.map
ajax/libs/vkui/4.28.0/cjs/hoc/withContext.min.js
cdnjs/cdnjs
"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard").default,_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default;Object.defineProperty(exports,"__esModule",{value:!0}),exports.withContext=withContext;var _jsxRuntime=require("../lib/jsxRuntime"),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),React=_interopRequireWildcard(require("react"));function withContext(t,i,u){return function(e){var r=React.useContext(i);return(0,_jsxRuntime.createScopedElement)(t,(0,_extends2.default)({},e,(0,_defineProperty2.default)({},u,r)))}}
electron/app/components/ComponentsDropdown.js
zindlerb/static
import React from 'react'; import FormLabel from './forms/FormLabel'; import PopupSelect from './PopupSelect'; import SimplePopupSelectDropdown from './SimplePopupSelectDropdown'; const ComponentsDropdown = function (props) { const { currentComponentId, componentsList, isDefaultComponent, currentComponentName, actions } = props; let trash; if (!isDefaultComponent) { trash = ( <i className="fa fa-trash mh1 clickable" aria-hidden="true" onClick={() => { actions.deleteCurrentComponentBox() }} /> ); } return ( <FormLabel className="mh2" name="Component"> <PopupSelect value={currentComponentName} inlineAction={trash} className="f6 pv1" > <SimplePopupSelectDropdown items={componentsList} activeValue={currentComponentId} onClick={value => actions.setCurrentComponentId(value)} /> </PopupSelect> </FormLabel> ); } export default ComponentsDropdown;
components/list/List.js
react-toolbox/react-toolbox
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import { LIST } from '../identifiers'; import InjectListItem from './ListItem'; const mergeProp = (propName, child, parent) => ( child[propName] !== undefined ? child[propName] : parent[propName] ); const factory = (ListItem) => { class List extends Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, ripple: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types selectable: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types theme: PropTypes.shape({ list: PropTypes.string, }), }; static defaultProps = { className: '', ripple: false, selectable: false, }; renderItems() { return React.Children.map(this.props.children, (item) => { if (item === null || item === undefined) { return item; } if (item.type === ListItem) { const selectable = mergeProp('selectable', item.props, this.props); const ripple = mergeProp('ripple', item.props, this.props); return React.cloneElement(item, { selectable, ripple }); } return React.cloneElement(item); }); } render() { return ( <ul data-react-toolbox="list" className={classnames(this.props.theme.list, this.props.className)}> {this.renderItems()} </ul> ); } } return List; }; const List = factory(InjectListItem); export default themr(LIST)(List); export { factory as listFactory }; export { List };
test/RowSpec.js
roadmanfong/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Row from '../src/Row'; describe('Row', function () { it('uses "div" by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Row /> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); }); it('has "row" class', function () { let instance = ReactTestUtils.renderIntoDocument( <Row>Row content</Row> ); assert.equal(React.findDOMNode(instance).className, 'row'); }); it('Should merge additional classes passed in', function () { let instance = ReactTestUtils.renderIntoDocument( <Row className="bob"/> ); assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/)); assert.ok(React.findDOMNode(instance).className.match(/\brow\b/)); }); it('allows custom elements instead of "div"', function () { let instance = ReactTestUtils.renderIntoDocument( <Row componentClass='section' /> ); assert.equal(React.findDOMNode(instance).nodeName, 'SECTION'); }); });
src/content/Essay.js
ltoddy/ltoddy.github.io
import React from 'react' import PropTypes from 'prop-types' import ReactTooltip from 'react-tooltip' import { TimelineEvent } from 'react-event-timeline' import css from './Essay.css' const Essay = props => ( <TimelineEvent title={props.title} createdAt={props.createdAt} icon={<i className="fas fa-book" style={{ fontSize: '16px' }} />} > <div className={css.preview}> <a href={props.link} target="_blank" data-tip data-for={props.title}> {props.preview} </a> </div> <ReactTooltip id={props.title}> Go to {props.link.split('/').slice(-1)} </ReactTooltip> </TimelineEvent> ) Essay.propTypes = { title: PropTypes.string, createdAt: PropTypes.string, link: PropTypes.string, preview: PropTypes.string, } export default Essay
ajax/libs/soundplayer-widget/0.3.4/soundplayer-widget.min.js
peteygao/cdnjs
!function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}n(10);for(var o=n(12),i=r(o),a=document.querySelectorAll(".sb-soundplayer-widget"),s=0,u=a.length;u>s;s++){var c=a[s],l=c.getAttribute("data-url"),p=c.getAttribute("data-layout");i.create(c,{url:l,layout:p})}},function(e,t,n){t.tree=t.scene=t.deku=n(26),"undefined"!=typeof document&&(t.render=n(27)),t.renderString=n(28),t.element=t.createElement=t.dom=n(30)},function(e,t,n){"use strict";function r(e){if(!(this instanceof r))return new r(e);if(!e)throw new Error("SoundCloud API clientId is required, get it - https://developers.soundcloud.com/");this._events={},this._clientId=e,this._baseUrl="http://api.soundcloud.com",this.playing=!1,this.duration=0,this.audio=document.createElement("audio")}r.prototype.resolve=function(e,t){if(!e)throw new Error("SoundCloud track or playlist url is required");e=this._baseUrl+"/resolve.json?url="+e+"&client_id="+this._clientId,this._jsonp(e,function(e){e.tracks?this._playlist=e:this._track=e,this.duration=e.duration/1e3,t(e)}.bind(this))},r.prototype._jsonp=function(e,t){var n=document.getElementsByTagName("script")[0]||document.head,r=document.createElement("script"),o="jsonp_callback_"+Math.round(1e5*Math.random());window[o]=function(e){r.parentNode&&r.parentNode.removeChild(r),window[o]=function(){},t(e)},r.src=e+(e.indexOf("?")>=0?"&":"?")+"callback="+o,n.parentNode.insertBefore(r,n)},r.prototype.on=function(e,t){this._events[e]=t,this.audio.addEventListener(e,t,!1)},r.prototype.off=function(e,t){this._events[e]=null,this.audio.removeEventListener(e,t)},r.prototype.unbindAll=function(){for(var e in this._events){var t=this._events[e];t&&this.off(e,t)}},r.prototype.preload=function(e){this._track={stream_url:e},this.audio.src=e+"?client_id="+this._clientId},r.prototype.play=function(e){e=e||{};var t;if(e.streamUrl)t=e.streamUrl;else if(this._playlist){var n=this._playlist.tracks.length;if(n){if(this._playlistIndex=e.playlistIndex||0,this._playlistIndex>=n||this._playlistIndex<0)return void(this._playlistIndex=0);t=this._playlist.tracks[this._playlistIndex].stream_url}}else this._track&&(t=this._track.stream_url);if(!t)throw new Error("There is no tracks to play, use `streamUrl` option or `load` method");t+="?client_id="+this._clientId,t!==this.audio.src&&(this.audio.src=t),this.playing=t,this.audio.play()},r.prototype.pause=function(){this.audio.pause(),this.playing=!1},r.prototype.stop=function(){this.audio.pause(),this.audio.currentTime=0,this.playing=!1},r.prototype.next=function(){var e=this._playlist.tracks.length;this._playlistIndex>=e-1||this._playlist&&e&&this.play({playlistIndex:++this._playlistIndex})},r.prototype.previous=function(){this._playlistIndex<=0||this._playlist&&this._playlist.tracks.length&&this.play({playlistIndex:--this._playlistIndex})},r.prototype.seek=function(e){if(!this.audio.readyState)return!1;var t=e.offsetX/e.target.offsetWidth||(e.layerX-e.target.offsetLeft)/e.target.offsetWidth;this.audio.currentTime=t*(this.audio.duration||0)},e.exports=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o={onClick:{type:"function",optional:!0}},i={propTypes:o,shouldUpdate:function(){return!1},render:function(e){var t=e.props;return r.dom("svg",{"class":"sb-soundplayer-cover-logo",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",onClick:t.onClick},r.dom("path",{d:"M10.517 3.742c-.323 0-.49.363-.49.582 0 0-.244 3.591-.244 4.641 0 1.602.15 2.621.15 2.621 0 .222.261.401.584.401.321 0 .519-.179.519-.401 0 0 .398-1.038.398-2.639 0-1.837-.153-4.127-.284-4.592-.112-.395-.313-.613-.633-.613zm-1.996.268c-.323 0-.49.363-.49.582 0 0-.244 3.322-.244 4.372 0 1.602.119 2.621.119 2.621 0 .222.26.401.584.401.321 0 .581-.179.581-.401 0 0 .081-1.007.081-2.608 0-1.837-.206-4.386-.206-4.386 0-.218-.104-.581-.425-.581zm-2.021 1.729c-.324 0-.49.362-.49.582 0 0-.272 1.594-.272 2.644 0 1.602.179 2.559.179 2.559 0 .222.229.463.552.463.321 0 .519-.241.519-.463 0 0 .19-.944.19-2.546 0-1.837-.253-2.657-.253-2.657 0-.22-.104-.582-.425-.582zm-2.046-.358c-.323 0-.49.363-.49.582 0 0-.162 1.92-.162 2.97 0 1.602.069 2.496.069 2.496 0 .222.26.557.584.557.321 0 .581-.304.581-.526 0 0 .143-.936.143-2.538 0-1.837-.206-2.96-.206-2.96 0-.218-.198-.581-.519-.581zm-2.169 1.482c-.272 0-.232.218-.232.218v3.982s-.04.335.232.335c.351 0 .716-.832.716-2.348 0-1.245-.436-2.187-.716-2.187zm18.715-.976c-.289 0-.567.042-.832.116-.417-2.266-2.806-3.989-5.263-3.989-1.127 0-2.095.705-2.931 1.316v8.16s0 .484.5.484h8.526c1.655 0 3-1.55 3-3.155 0-1.607-1.346-2.932-3-2.932zm10.17.857c-1.077-.253-1.368-.389-1.368-.815 0-.3.242-.611.97-.611.621 0 1.106.253 1.542.699l.981-.951c-.641-.669-1.417-1.067-2.474-1.067-1.339 0-2.425.757-2.425 1.99 0 1.338.873 1.736 2.124 2.026 1.281.291 1.513.486 1.513.923 0 .514-.379.738-1.184.738-.65 0-1.26-.223-1.736-.777l-.98.873c.514.757 1.504 1.232 2.639 1.232 1.853 0 2.668-.873 2.668-2.163 0-1.477-1.193-1.845-2.27-2.097zm6.803-2.745c-1.853 0-2.949 1.435-2.949 3.502s1.096 3.501 2.949 3.501c1.852 0 2.949-1.434 2.949-3.501s-1.096-3.502-2.949-3.502zm0 5.655c-1.097 0-1.553-.941-1.553-2.153 0-1.213.456-2.153 1.553-2.153 1.096 0 1.551.94 1.551 2.153.001 1.213-.454 2.153-1.551 2.153zm8.939-1.736c0 1.086-.533 1.756-1.396 1.756-.864 0-1.388-.689-1.388-1.775v-3.897h-1.358v3.916c0 1.978 1.106 3.084 2.746 3.084 1.726 0 2.754-1.136 2.754-3.103v-3.897h-1.358v3.916zm8.142-.89l.019 1.485c-.087-.174-.31-.515-.475-.768l-2.703-3.692h-1.362v6.894h1.401v-2.988l-.02-1.484c.088.175.311.514.475.767l2.79 3.705h1.213v-6.894h-1.339v2.975zm5.895-2.923h-2.124v6.791h2.027c1.746 0 3.474-1.01 3.474-3.395 0-2.484-1.437-3.396-3.377-3.396zm-.097 5.472h-.67v-4.152h.719c1.436 0 2.028.688 2.028 2.076 0 1.242-.651 2.076-2.077 2.076zm7.909-4.229c.611 0 1 .271 1.242.737l1.26-.582c-.426-.883-1.202-1.503-2.483-1.503-1.775 0-3.016 1.435-3.016 3.502 0 2.143 1.191 3.501 2.968 3.501 1.232 0 2.047-.572 2.513-1.533l-1.145-.68c-.358.602-.718.864-1.329.864-1.019 0-1.611-.932-1.611-2.153-.001-1.261.583-2.153 1.601-2.153zm5.17-1.192h-1.359v6.791h4.083v-1.338h-2.724v-5.453zm6.396-.157c-1.854 0-2.949 1.435-2.949 3.502s1.095 3.501 2.949 3.501c1.853 0 2.95-1.434 2.95-3.501s-1.097-3.502-2.95-3.502zm0 5.655c-1.097 0-1.553-.941-1.553-2.153 0-1.213.456-2.153 1.553-2.153 1.095 0 1.55.94 1.55 2.153.001 1.213-.454 2.153-1.55 2.153zm8.557-1.736c0 1.086-.532 1.756-1.396 1.756-.864 0-1.388-.689-1.388-1.775v-3.794h-1.358v3.813c0 1.978 1.106 3.084 2.746 3.084 1.726 0 2.755-1.136 2.755-3.103v-3.794h-1.36v3.813zm5.449-3.907h-2.318v6.978h2.211c1.908 0 3.789-1.037 3.789-3.489 0-2.552-1.565-3.489-3.682-3.489zm-.108 5.623h-.729v-4.266h.783c1.565 0 2.21.706 2.21 2.133.001 1.276-.707 2.133-2.264 2.133z"}))}},a={propTypes:o,render:function(e){var t=e.props;return r.dom("svg",{"class":"sb-soundplayer-button-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",fill:"currentColor",onClick:t.onClick},t.children)}},s={propTypes:o,shouldUpdate:function(){return!1},render:function(e){var t=e.props;return r.dom(a,t,r.dom("path",{d:"M0 0 L32 16 L0 32 z"}))}},u={propTypes:o,shouldUpdate:function(){return!1},render:function(e){var t=e.props;return r.dom(a,t,r.dom("path",{d:"M0 0 H12 V32 H0 z M20 0 H32 V32 H20 z"}))}},c={propTypes:{onClick:{type:"function",optional:!0}},shouldUpdate:function(){return!1},render:function(e){var t=e.props;return r.dom(a,t,r.dom("path",{d:"M4 4 L24 14 V4 H28 V28 H24 V18 L4 28 z "}))}},l={propTypes:{onClick:{type:"function",optional:!0}},shouldUpdate:function(){return!1},render:function(e){var t=e.props;return r.dom(a,t,r.dom("path",{d:"M4 4 H8 V14 L28 4 V28 L8 18 V28 H4 z "}))}};t["default"]={SoundCloudLogoSVG:i,PlayIconSVG:s,PauseIconSVG:u,NextIconSVG:c,PrevIconSVG:l},e.exports=t["default"]},function(e,t,n){e.exports={onBlur:"blur",onChange:"change",onClick:"click",onContextMenu:"contextmenu",onCopy:"copy",onCut:"cut",onDoubleClick:"dblclick",onDrag:"drag",onDragEnd:"dragend",onDragEnter:"dragenter",onDragExit:"dragexit",onDragLeave:"dragleave",onDragOver:"dragover",onDragStart:"dragstart",onDrop:"drop",onFocus:"focus",onInput:"input",onKeyDown:"keydown",onKeyPress:"keypress",onKeyUp:"keyup",onMouseDown:"mousedown",onMouseEnter:"mouseenter",onMouseLeave:"mouseleave",onMouseMove:"mousemove",onMouseOut:"mouseout",onMouseOver:"mouseover",onMouseUp:"mouseup",onPaste:"paste",onScroll:"scroll",onSubmit:"submit",onTouchCancel:"touchcancel",onTouchEnd:"touchend",onTouchMove:"touchmove",onTouchStart:"touchstart",onWheel:"wheel"}},function(e,t,n){t.defaults=function(e,t){return Object.keys(t).forEach(function(n){"undefined"==typeof e[n]&&(e[n]=t[n])}),e}},function(e,t,n){var r=Object.prototype.toString;e.exports=function(e){switch(r.call(e)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}return null===e?"null":void 0===e?"undefined":e!==e?"nan":e&&1===e.nodeType?"element":(e=e.valueOf?e.valueOf():Object.prototype.valueOf.apply(e),typeof e)}},function(e,t,n){"use strict";e.exports=function(e,t){return function(n,r,o){return e.call(t,n,r,o)}}},function(e,t,n){"use strict";e.exports=function(e,t){return function(n,r,o,i){return e.call(t,n,r,o,i)}}},function(e,t,n){t=e.exports=n(13)(),t.push([e.id,".sb-soundplayer-cover,.sb-soundplayer-widget{border-radius:3px;background-repeat:no-repeat;position:relative;min-height:240px}.sb-soundplayer-widget{color:#fff;font-family:Avenir Next,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f5f5f5;background-image:url(https://w.soundcloud.com/player/assets/images/logo-200x120-177df3dd.png);background-position:center center;background-size:100px 60px;overflow:hidden;box-sizing:border-box}.sb-soundplayer-widget *,.sb-soundplayer-widget :after,.sb-soundplayer-widget :before{box-sizing:inherit;margin:0;padding:0}.sb-soundplayer-widget-track-info{color:#fff;position:relative;z-index:1;text-align:center;padding-top:80px;padding-bottom:53px;text-transform:uppercase;letter-spacing:.1em}.sb-soundplayer-widget-title,.sb-soundplayer-widget-user{margin:2px 0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.sb-soundplayer-widget-user{font-size:14px}.sb-soundplayer-widget-title{font-size:20px}.sb-soundplayer-widget-controls{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;padding:0 10px 15px;position:relative;z-index:1}.sb-soundplayer-progress-container{background-color:#000;background-color:rgba(0,0,0,.25);width:100%;height:8px;overflow:hidden;cursor:pointer;border-radius:3px}.sb-soundplayer-progress-inner{background-color:#fff;height:100%;-webkit-transition:width .2s ease-in;transition:width .2s ease-in}.sb-soundplayer-cover{background-position:center;background-size:cover}.sb-soundplayer-widget-overlay{background-color:#000;background-color:rgba(0,0,0,.3);position:absolute;top:0;left:0;right:0;bottom:0;border-radius:3px}.sb-soundplayer-play-btn{display:inline-block;color:#fff;font-size:20px;text-decoration:none;line-height:1;padding:8px 16px;height:auto;vertical-align:middle;-webkit-box-flex:0;-webkit-flex:none;-ms-flex:none;flex:none;margin-right:12px;position:relative;z-index:2;background-color:transparent;transition-duration:.1s;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;-webkit-transition-property:box-shadow;transition-property:box-shadow;-webkit-appearance:none;border-radius:3px;cursor:pointer}.sb-soundplayer-play-btn,.sb-soundplayer-play-btn:before{border:1px solid transparent;-webkit-transition-duration:.1s}.sb-soundplayer-play-btn:before{content:'';display:block;background-color:currentcolor;position:absolute;z-index:-1;top:-1px;right:-1px;bottom:-1px;left:-1px;transition-duration:.1s;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;-webkit-transition-property:opacity;transition-property:opacity;opacity:0;border-radius:3px}.sb-soundplayer-play-btn:active,.sb-soundplayer-play-btn:hover{box-shadow:none}.sb-soundplayer-play-btn:focus:before,.sb-soundplayer-play-btn:hover:before{opacity:.09375}.sb-soundplayer-play-btn:focus{outline:0;border-color:transparent;box-shadow:0 0 0 2px}.sb-soundplayer-button-icon{width:1em;height:1em;position:relative;vertical-align:middle}.sb-soundplayer-cover-logo{color:#fff;width:100px;height:14px;position:absolute;top:10px;right:10px;z-index:1}.sb-soundplayer-timer{-webkit-box-flex:0;-webkit-flex:none;-ms-flex:none;flex:none;color:#fff;font-size:12px;padding:0 3px 0 15px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.sb-soundplayer-widget-message{color:#999;font-size:12px;text-align:center;position:absolute;right:0;left:0;bottom:10px}.sb-soundplayer-widget-message a{color:#666}",""])},function(e,t,n){var r=n(9);"string"==typeof r&&(r=[[e.id,r,""]]);n(50)(r,{singleton:!0});r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(2),a=r(i),s=n(15),u=n(14),c=s.Icons.SoundCloudLogoSVG,l={propTypes:{duration:{type:"number",optional:!0},currentTime:{type:"number",optional:!0},playing:{type:"boolean",optional:!0},seeking:{type:"boolean",optional:!0},track:{type:"object",optional:!0},soundCloudAudio:function(e){return e instanceof a["default"]}},defaultProps:{duration:0,currentTime:0,seeking:!1,playing:!1},render:function(e){var t=e.props;return t.track?t.track&&!t.track.streamable?o.dom("div",{"class":"sb-soundplayer-widget-message"},o.dom("a",{href:t.track.permalink_url,target:"_blank"},t.track.title)," is not streamable!"):o.dom(s.Cover,{artworkUrl:t.track.artwork_url.replace("large","t500x500")},o.dom("div",{"class":"sb-soundplayer-widget-overlay"}),o.dom("div",{"class":"sb-soundplayer-widget-track-info"},o.dom("h3",{"class":"sb-soundplayer-widget-user"},t.track.user.username),o.dom("h2",{"class":"sb-soundplayer-widget-title"},t.track.title)),o.dom("a",{href:t.track.permalink_url,target:"_blank"},o.dom(c,null)),o.dom("div",{"class":"sb-soundplayer-widget-controls"},o.dom(s.PlayButton,{playing:t.playing,soundCloudAudio:t.soundCloudAudio}),o.dom(s.Progress,{value:t.currentTime/t.duration*100||0,soundCloudAudio:t.soundCloudAudio}),o.dom(s.Timer,{duration:t.track.duration/1e3,currentTime:t.currentTime}))):o.dom("span",null)}};t["default"]={propTypes:{resolveUrl:{type:"string"},clientId:{type:"string"}},render:function(e){var t=e.props;return o.dom(u.SoundPlayerContainer,t,o.dom(l,null))}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=t.clientId||window.sb_soundplayer_client_id;if(!n)return void console.error(["You must provide SoundCloud clientId for SoundPlayer widget","","Example:","<script>",'var sb_soundplayer_client_id = "YOUR_CLIENT_ID";',"</script>","","Register for an app and get clientId at https://developers.soundcloud.com/"].join("\n"));var r=a["default"].tree(a["default"].dom(u["default"],{resolveUrl:t.url,clientId:n}));"development"===c&&r.option("validateProps",!0),a["default"].render(r,e)}Object.defineProperty(t,"__esModule",{value:!0}),t.create=o;var i=n(1),a=r(i),s=n(11),u=r(s),c="production"},function(e,t,n){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<t.length;o++){var a=t[o];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(e,t,n){e.exports=n(17)},function(e,t,n){e.exports=n(22)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(25),a=r(i),s=n(2),u=r(s),c=n(23);t["default"]={propTypes:{resolveUrl:{type:"string"},clientId:{type:"string"}},initialState:function(){return{duration:0,currentTime:0,seeking:!1,playing:!1}},beforeMount:function(e){var t=e.props,n=(e.state,e.id),r=t.clientId;if(!r)throw new Error("You need to get clientId from SoundCloud\n https://github.com/soundblogs/react-soundplayer#usage");if("undefined"!=typeof window){var o=new u["default"](r);c.addToRegistry(n,o)}},afterMount:function(e,t,n){function r(){n({playing:!0}),c.stopAllOther(h.playing),c.addToPlayedStore(h)}function o(){n({currentTime:h.audio.currentTime})}function i(){n({duration:h.audio.duration})}function a(){n({seeking:!0})}function s(){n({seeking:!1})}function u(){n({playing:!1})}var l=e.props,p=(e.state,e.id),d=l.resolveUrl,f=l.streamUrl,h=c.getFromRegistry(p);f?h.preload(f):d&&h.resolve(d,function(e){var t=e.tracks?e.tracks[0]:e;n({track:t})}),h.on("playing",r),h.on("timeupdate",o),h.on("loadedmetadata",i),h.on("seeking",a),h.on("seeked",s),h.on("pause",u),h.on("ended",u)},afterUpdate:function(e,t,n,r){function o(){d&&p.play()}var i=e.props,a=e.state,s=e.id,u=i.resolveUrl,l=i.streamUrl,p=c.getFromRegistry(s),d=a.playing;l!==t.streamUrl?(p.stop(),p.preload(l),o()):u!==t.resolveUrl&&(p.stop(),p.resolve(u,function(e){var t=e.tracks?e.tracks[0]:e;r({track:t}),o()}))},beforeUnmount:function(e){var t=c.getFromRegistry(e.id);t.unbindAll()},render:function(e){function t(e){var t=a["default"]({},e);return t.props&&(t.props=a["default"]({},t.props,r,{soundCloudAudio:s})),t}var n=e.props,r=e.state,i=e.id,s=c.getFromRegistry(i);return o.dom("span",null,n.children.map(t))}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(16),i=r(o);t.SoundPlayerContainer=i["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(24),a=r(i);t["default"]={propTypes:{artworkUrl:{type:"string"}},render:function(e){var t=e.props,n=a["default"]("sb-soundplayer-cover",t["class"]);return o.dom("div",{"class":n,style:{"background-image":"url("+t.artworkUrl+")"}},t.children)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(2),a=r(i),s=n(3);t["default"]={defaultProps:{playing:!1,seeking:!1},propTypes:{playing:{type:"boolean",optional:!0},seeking:{type:"boolean",optional:!0},soundCloudAudio:function(e){return e instanceof a["default"]}},render:function(e){function t(e){e.preventDefault();var t=n.playing,r=n.soundCloudAudio;t?r&&r.pause():r&&r.play()}var n=e.props;return o.dom("button",{"class":"sb-soundplayer-play-btn",onClick:t},n.playing?o.dom(s.PauseIconSVG,{onClick:t}):o.dom(s.PlayIconSVG,{onClick:t}))}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(2),a=r(i);t["default"]={defaultProps:{value:0},propTypes:{value:{type:"number"},soundCloudAudio:function(e){return e instanceof a["default"]}},render:function(e){function t(e){var t=(e.pageX-e.delegateTarget.getBoundingClientRect().left)/e.delegateTarget.offsetWidth;i&&!isNaN(i.audio.duration)&&(i.audio.currentTime=t*i.audio.duration)}var n=e.props,r=n.value,i=n.soundCloudAudio;0>r&&(r=0),r>100&&(r=100);var a={width:""+r+"%"};return o.dom("div",{"class":"sb-soundplayer-progress-container",onClick:t},o.dom("div",{"class":"sb-soundplayer-progress-inner",style:a}))}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){var t=Math.floor(e/3600),n="0"+Math.floor(e%3600/60),r="0"+Math.floor(e%60);return n=n.substr(n.length-2),r=r.substr(r.length-2),isNaN(r)?"00:00":t?""+t+":"+n+":"+r:""+n+":"+r}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1);t["default"]={defaultProps:{duration:0,currentTime:0},propTypes:{duration:{type:"number"},currentTime:{type:"number"}},render:function(e){var t=e.props;return o.dom("div",{"class":"sb-soundplayer-timer"},r(t.currentTime)," / ",r(t.duration))}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(19),i=r(o);t.PlayButton=i["default"];var a=n(20),s=r(a);t.Progress=s["default"];var u=n(21),c=r(u);t.Timer=c["default"];var l=n(18),p=r(l);t.Cover=p["default"];var d=n(3),f=r(d);t.Icons=f["default"]},function(e,t,n){"use strict";function r(e){s.forEach(function(t){t.playing&&t.playing!==e&&t.stop()})}function o(e){for(var t=!1,n=0,r=s.length;r>n;n++){var o=s[n];if(o.playing===e.playing){t=!0;break}}t||s.push(e)}function i(e,t){u[e]=t}function a(e){return u[e]}Object.defineProperty(t,"__esModule",{value:!0}),t.stopAllOther=r,t.addToPlayedStore=o,t.addToRegistry=i,t.getFromRegistry=a;var s=[],u={}},function(e,t,n){var r;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function o(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];if(n){var r=typeof n;if("string"===r||"number"===r)e+=" "+n;else if(Array.isArray(n))e+=" "+o.apply(null,n);else if("object"===r)for(var i in n)n.hasOwnProperty(i)&&n[i]&&(e+=" "+i)}}return e.substr(1)}"undefined"!=typeof e&&e.exports?e.exports=o:(r=function(){return o}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}()},function(e,t,n){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function o(e){var t=Object.getOwnPropertyNames(e);return Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(e))),t.filter(function(t){return i.call(e,t)})}var i=Object.prototype.propertyIsEnumerable;e.exports=Object.assign||function(e,t){for(var n,i,a=r(e),s=1;s<arguments.length;s++){n=arguments[s],i=o(Object(n));for(var u=0;u<i.length;u++)a[i[u]]=n[i[u]]}return a}},function(e,t,n){function r(e){return this instanceof r?(this.options={},this.sources={},void(this.element=e)):new r(e)}var o=n(32);e.exports=r,o(r.prototype),r.prototype.use=function(e){return e(this),this},r.prototype.option=function(e,t){return this.options[e]=t,this},r.prototype.set=function(e,t){return this.sources[e]=t,this.emit("source",e,t),this},r.prototype.mount=function(e){return this.element=e,this.emit("mount",e),this},r.prototype.unmount=function(){return this.element?(this.element=null,this.emit("unmount"),this):void 0}},function(e,t,n){function r(e,t,n){function r(){he(),P(),e.off("unmount",f),e.off("mount",l),e.off("source",w)}function l(){E()}function f(){P(),_e=null}function w(e,t){Ee[e]&&Ee[e].forEach(function(e){e(t)})}function k(e){ce(e),de(e),Ae[e.id]={},Me[e.id]=e,se(e),ne("beforeMount",e,[e.context]),ne("beforeRender",e,[e.context]);var t=C(e),n=I(e.id,"0",t);return e.virtualElement=t,e.nativeElement=n,Se.push(e.id),n}function _(e){var t=Me[e];if(t){ne("beforeUnmount",t,[t.context,t.nativeElement]),A(e),ge(e);var n=je[e].entities;delete n[e],delete je[e],delete Me[e],delete Ae[e]}}function C(e){var t=e.component;if(!t.render)throw new Error("Component needs a render function");var n=t.render(e.context,T(e));if(!n)throw new Error("Render function must return an element.");return n}function T(e){return function(t){oe(e,t)}}function E(){Pe.batching?we||(we=a(j)):ke||j()}function j(){return N(),ke?void(we=a(j)):(ke=!0,Ce?_e!==e.element?(Ce=R(Te,_e,e.element,Ce),_e=e.element,S(Te)):S(Te):(_e=e.element,Ce=I(Te,"0",_e),t.children.length>0&&console.info("deku: The container element is not empty. These elements will be removed. Read more: http://cl.ly/b0Sr"),t===document.body&&console.warn("deku: Using document.body is allowed but it can cause some issues. Read more: http://cl.ly/b0SC"),te(t),t.appendChild(Ce)),M(),void(ke=!1))}function M(){for(var e;e=Se.pop();){var t=Me[e];ne("afterRender",t,[t.context,t.nativeElement]),re("afterMount",t,[t.context,t.nativeElement,T(t)])}}function N(){we&&(a.cancel(we),we=0)}function O(e){var t=Me[e];if(de(t),!ue(t))return se(t),S(e);var n=t.virtualElement,r=t.pendingProps,o=t.pendingState,i=t.context.state,a=t.context.props;ne("beforeUpdate",t,[t.context,r,o]),ne("beforeRender",t,[t.context]),se(t);var s=C(t);return s===n?S(e):(t.nativeElement=R(e,n,s,t.nativeElement),t.virtualElement=s,S(e),ne("afterRender",t,[t.context,t.nativeElement]),void re("afterUpdate",t,[t.context,a,i]))}function S(e){m(Ae[e],function(e){O(e)})}function A(e){m(Ae[e],function(e){_(e)})}function P(){N(),q(Te,"0",Ce),Ce=null}function I(e,t,n){switch(n.type){case"text":return U(n);case"element":return z(e,t,n);case"component":return L(e,t,n)}}function U(e){return document.createTextNode(e.data)}function z(e,t,n){var r,o=n.attributes,a=n.children,s=n.tagName;if(Pe.pooling&&i(s)){var u=Z(s);r=Q(u.pop()),r.parentNode&&r.parentNode.removeChild(r)}else r=h.isElement(s)?document.createElementNS(h.namespace,s):document.createElement(s);return m(o,function(n,o){K(e,t,r,o,n)}),r.__entity__=e,r.__path__=t,m(a,function(n,o){var i=I(e,t+"."+o,n);i.parentNode||r.appendChild(i)}),r}function L(e,t,n){var r=new o(n.component,n.props,e);return Ae[e][t]=r.id,k(r)}function R(e,t,n,r){return D("0",e,t,n,r)}function D(e,t,n,r,o){if(n.type!==r.type)return $(t,e,o,r);switch(r.type){case"text":return B(n,r,o);case"element":return G(e,t,n,r,o);case"component":return F(e,t,n,r,o)}}function B(e,t,n){return t.data!==e.data&&(n.data=t.data),n}function V(e,t,n,r,o){function i(e,t){return null!=t.key&&(e[t.key]=t,s=!0),e}var a=[],s=!1,u=Array.prototype.slice.apply(o.childNodes),c=b(n.children,i,{}),l=b(r.children,i,{}),p=g({},Ae[t]);if(s)m(c,function(n,r){if(null==l[r]){var o=e+"."+n.index;q(t,o,u[n.index])}}),m(l,function(n,r){var o=c[r];if(null!=o){var i=e+"."+o.index;a[n.index]=D(i,t,o,n,u[o.index])}}),m(l,function(n,r){var o=c[r];if(null!=o&&o.index!==n.index){var i=e+"."+n.index,a=e+"."+o.index;m(p,function(e,n){a===n&&(delete Ae[t][n],Ae[t][i]=e)})}}),m(l,function(n,r){var o=e+"."+n.index;null==c[r]&&(a[n.index]=I(t,o,n))});else for(var d=Math.max(n.children.length,r.children.length),f=0;d>f;f++){var h=n.children[f],v=r.children[f];null==v&&q(t,e+"."+h.index,u[h.index]),null==h&&(a[v.index]=I(t,e+"."+v.index,v)),h&&v&&(a[h.index]=D(e+"."+h.index,t,h,v,u[h.index]))}m(a,function(e,t){var n=o.childNodes[t];e!==n&&(n?o.insertBefore(e,n):o.appendChild(e))})}function H(e,t,n,r,o){var i=t.attributes,a=e.attributes;m(i,function(e,t){!v[t]&&t in a&&a[t]===e||K(r,o,n,t,e)}),m(a,function(e,t){t in i||X(r,o,n,t)})}function F(e,t,n,r,o){if(r.component!==n.component)return $(t,e,o,r);var i=Ae[t][e];return i&&ie(i,r.props),o}function G(e,t,n,r,o){return r.tagName!==n.tagName?$(t,e,o,r):(H(n,r,o,t,e),V(e,t,n,r,o),o)}function q(e,t,n){var r=Ae[e],o=r[t],a=Oe[e]||{},s=[];if(o){var c=Me[o];n=c.nativeElement,_(o),s.push(t)}else{if(!J(n))return n&&n.parentNode.removeChild(n);m(r,function(e,n){(n===t||Y(t,n))&&(_(e),s.push(n))}),m(a,function(n,r){(r===t||Y(t,r))&&me(e,r)})}m(s,function(t){delete Ae[e][t]}),n.parentNode.removeChild(n),Pe.pooling&&u(n,function(e){J(e)&&i(e.tagName)&&Z(e.tagName.toLowerCase()).push(e)})}function $(e,t,n,r){var o=n.parentNode,i=Array.prototype.indexOf.call(o.childNodes,n);q(e,t,n);var a=I(e,t,r),s=o.childNodes[i];return s?o.insertBefore(a,s):o.appendChild(a),"root"!==e&&"0"===t&&W(e,a),a}function W(e,t){var n=Me[e];"root"!==n.ownerId&&Ae[n.ownerId][0]===e&&(Me[n.ownerId].nativeElement=t,W(n.ownerId,t))}function K(e,t,n,r,o){if(v[r])return void ye(e,t,v[r],o);switch(r){case"checked":case"disabled":case"selected":n[r]=!0;break;case"innerHTML":case"value":n[r]=o;break;case h.isAttribute(r):n.setAttributeNS(h.namespace,r,o);break;default:n.setAttribute(r,o)}}function X(e,t,n,r){if(v[r])return void me(e,t,v[r]);switch(r){case"checked":case"disabled":case"selected":n[r]=!1;break;case"innerHTML":case"value":n[r]="";break;default:n.removeAttribute(r)}}function Y(e,t){return 0===t.indexOf(e+".")}function J(e){return!(!e||!e.tagName)}function Z(e){var t=Ne[e];if(!t){var n=h.isElement(e)?{namespace:h.namespace,tagName:e}:{tagName:e};t=Ne[e]=new s(n)}return t}function Q(e){return te(e),ee(e),e}function ee(e){for(var t=e.attributes.length-1;t>=0;t--){var n=e.attributes[t].name;e.removeAttribute(n)}}function te(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function ne(e,t,n){return"function"==typeof t.component[e]?t.component[e].apply(null,n):void 0}function re(e,t,n){var r=T(t);n.push(r);var o=ne(e,t,n);o&&oe(t,o)}function oe(e,t){x(t)?t.then(function(t){ae(e,t)}):ae(e,t)}function ie(e,t){var n=Me[e];n.pendingProps=t,n.dirty=!0,E()}function ae(e,t){e.pendingState=g(e.pendingState,t),e.dirty=!0,E()}function se(e){e.context={state:e.pendingState,props:e.pendingProps,id:e.id},e.pendingState=g({},e.context.state),e.pendingProps=g({},e.context.props),be(e.context.props,e.propTypes),e.dirty=!1}function ue(e){if(!e.dirty)return!1;if(!e.component.shouldUpdate)return!0;var t=e.pendingProps,n=e.pendingState,r=e.component.shouldUpdate(e.context,t,n);return r}function ce(e){le(e);var t=e.component;t.registered||(pe(e),t.registered=!0)}function le(e){var t=e.component,n=t.entities=t.entities||{};n[e.id]=e,je[e.id]=t}function pe(e){var t=je[e.id],n=t.sources;if(!n){var r=t.entities,o=t.sourceToPropertyName={};t.sources=n=[];var i=t.propTypes;for(var a in i){var s=i[a];s&&s.source&&(n.push(s.source),o[s.source]=a)}n.forEach(function(e){function t(t){var n=o[e];for(var i in r){var a=r[i],s={};s[n]=t,ie(i,g(a.pendingProps,s))}}Ee[e]=Ee[e]||[],Ee[e].push(t)})}}function de(t){var n=t.component,r=n.sourceToPropertyName,o=n.sources;o.forEach(function(n){var o=r[n];null==t.pendingProps[o]&&(t.pendingProps[o]=e.sources[n])})}function fe(){m(v,function(e){document.body.addEventListener(e,ve,!0)})}function he(){m(v,function(e){document.body.removeEventListener(e,ve,!0)})}function ve(e){for(var t=e.target,n=e.type;t;){var r=p.get(Oe,[t.__entity__,t.__path__,n]);if(r){e.delegateTarget=t,r(e);break}t=t.parentNode}}function ye(e,t,n,r){p.set(Oe,[e,t,n],function(t){var n=Me[e];if(n){var o=T(n),i=r.call(null,t,n.context,o);i&&oe(n,i)}else r.call(null,t)})}function me(e,t,n){var r=[e];t&&r.push(t),n&&r.push(n),p.del(Oe,r)}function ge(e){p.del(Oe,[e])}function be(e,t,n){var r=n||"";Pe.validateProps&&(m(t,function(t,n){if(!t)throw new Error("deku: propTypes should have an options object for each type");var o=r?r+"."+n:n,i=p.get(e,n),a=d(i),s=d(t.type),u=t.optional===!0;if(!u||null!=i){if(!u&&null==i)throw new TypeError("Missing property: "+o);if("object"===s)return void be(i,t.type,o);if("string"===s&&a!==t.type)throw new TypeError("Invalid property type: "+o);if("function"===s&&!t.type(i))throw new TypeError("Invalid property type: "+o);if("array"===s&&t.type.indexOf(a)<0)throw new TypeError("Invalid property type: "+o);if(t.expects&&t.expects.indexOf(i)<0)throw new TypeError("Invalid property value: "+o)}}),m(e,function(e,n){if("children"!==n&&!t[n])throw new Error("Unexpected property: "+n)}))}function xe(){return{entities:Me,pools:Ne,handlers:Oe,connections:Ee,currentElement:_e,options:Pe,app:e,container:t,children:Ae}}var we,ke,_e,Ce,Te="root",Ee={},je={},Me={},Ne={},Oe={},Se=[],Ae={};if(Ae[Te]={},!c(t))throw new Error("Container element must be a DOM element");var Pe=y(g({},e.options||{},n||{}),{pooling:!0,batching:!0,validateProps:!1});return fe(),e.on("unmount",f),e.on("mount",l),e.on("source",w),e.element&&j(),{remove:r,inspect:xe}}function o(e,t,n){this.id=l(),this.ownerId=n,this.component=e,this.propTypes=e.propTypes||{},this.context={},this.context.id=this.id,this.context.props=y(t||{},e.defaultProps||{}),this.context.state=this.component.initialState?this.component.initialState(this.context.props):{},this.pendingProps=g({},this.context.props),this.pendingState=g({},this.context.state),this.dirty=!1,this.virtualElement=null,this.nativeElement=null,this.displayName=e.name||"Component"}function i(e){return w.indexOf(e)<0}var a=n(33),s=n(34),u=n(35),c=n(45),l=n(44),p=n(47),d=n(6),f=n(5),h=n(29),v=n(4),y=f.defaults,m=n(39),g=n(40),b=n(43),x=n(46),w=["input","textarea","select","option"];e.exports=r},function(e,t,n){function r(e){var t="";for(var n in e)"innerHTML"!==n&&(a[n]||(t+=o(n,e[n])));return t}function o(e,t){return" "+e+'="'+t+'"'}var i=n(5),a=n(4),s=i.defaults;e.exports=function(e){function t(t,r){var o=t.propTypes||{},i=s(r||{},t.defaultProps||{}),a=t.initialState?t.initialState(i):{};for(var u in o){var c=o[u];c.source&&(i[u]=e.sources[c.source])}t.beforeMount&&t.beforeMount({props:i,state:a}),t.beforeRender&&t.beforeRender({props:i,state:a});var l=t.render({props:i,state:a});return n(l,"0")}function n(e,o){switch(e.type){case"text":return e.data;case"element":var i=e.children,a=e.attributes,s=e.tagName,u=a.innerHTML,c="<"+s+r(a)+">";if(u)c+=u;else for(var l=0,p=i.length;p>l;l++)c+=n(i[l],o+"."+l);return c+="</"+s+">";case"component":return t(e.component,e.props)}throw new Error("Invalid type")}if(!e.element)throw new Error("No element mounted");return n(e.element,"0")}},function(e,t,n){var r=n(37);t.namespace="http://www.w3.org/2000/svg",t.elements=["animate","circle","defs","ellipse","g","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"],t.attributes=["cx","cy","d","dx","dy","fill","fillOpacity","fontFamily","fontSize","fx","fy","gradientTransform","gradientUnits","markerEnd","markerMid","markerStart","offset","opacity","patternContentUnits","patternUnits","points","preserveAspectRatio","r","rx","ry","spreadMethod","stopColor","stopOpacity","stroke","strokeDasharray","strokeLinecap","strokeOpacity","strokeWidth","textAnchor","transform","version","viewBox","x1","x2","x","y1","y2","y"],t.isElement=function(e){return-1!==r(t.elements,e)},t.isAttribute=function(e){return-1!==r(t.attributes,e)}},function(e,t,n){function r(e,t,n){if(!e)throw new Error("deku: Element needs a type. Read more: http://cl.ly/b0KZ");2!==arguments.length||"string"!=typeof t&&!Array.isArray(t)||(n=t,t={}),arguments.length>2&&Array.isArray(arguments[2])===!1&&(n=d(arguments,2)),n=n||[],t=t||{},Array.isArray(n)||(n=[n]),n=f(n,1).reduce(o,[]);var r="key"in t?String(t.key):null;delete t.key;var s;return s="string"==typeof e?new a(e,t,r,n):new i(e,t,r,n),s.index=0,s}function o(e,t){if(null==t)return e;if("string"==typeof t||"number"==typeof t){var n=new s(String(t));n.index=e.length,e.push(n)}else t.index=e.length,e.push(t);return e}function i(e,t,n,r){this.key=n,this.props=t,this.type="component",this.component=e,this.props.children=r||[]}function a(e,t,n,r){this.type="element",this.attributes=u(t),this.tagName=e,this.children=r||[],this.key=n}function s(e){this.type="text",this.data=String(e)}function u(e){e.style&&(e.style=c(e.style)),e["class"]&&(e["class"]=l(e["class"]));var t={};for(var n in e){var r=e[n];null!=r&&r!==!1&&(t[n]=r)}return t}function c(e){if("string"===p(e))return e;var t="";for(var n in e){var r=e[n];t=t+n+":"+r+";"}return t}function l(e){if("object"===p(e)){var t=[];for(var n in e)e[n]&&t.push(n);e=t}if("array"===p(e)){if(0===e.length)return;e=e.join(" ")}return e}var p=n(6),d=n(48),f=n(31);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){for(var o=0;o<e.length;o++){var i=e[o];n>0&&Array.isArray(i)?r(i,t,n-1):t.push(i)}return t}function o(e,t){for(var n=0;n<e.length;n++){var r=e[n];Array.isArray(r)?o(r,t):t.push(r)}return t}function i(e,t){return null==t?o(e,[]):r(e,[],t)}e.exports=i},function(e,t,n){function r(e){return e?o(e):void 0}function o(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}e.exports=r,r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r,o=0;o<n.length;o++)if(r=n[o],r===t||r.fn===t){n.splice(o,1);break}return this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),n=this._callbacks["$"+e];if(n){n=n.slice(0);for(var r=0,o=n.length;o>r;++r)n[r].apply(this,t)}return this},r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}},function(e,t,n){function r(e){var t=(new Date).getTime(),n=Math.max(0,16-(t-o)),r=setTimeout(e,n);return o=t,r}t=e.exports=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||r;var o=(new Date).getTime(),i=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.clearTimeout;t.cancel=function(e){i.call(window,e)}},function(e,t,n){function r(e){if("object"!=typeof e)throw new Error('Please pass parameters. Example -> new Pool({ tagName: "div" })');if("string"!=typeof e.tagName)throw new Error('Please specify a tagName. Example -> new Pool({ tagName: "div" })');this.storage=[],this.tagName=e.tagName.toLowerCase(),this.namespace=e.namespace}r.prototype.push=function(e){e.tagName.toLowerCase()===this.tagName&&this.storage.push(e)},r.prototype.pop=function(e){return 0===this.storage.length?this.create():this.storage.pop()},r.prototype.create=function(){return this.namespace?document.createElementNS(this.namespace,this.tagName):document.createElement(this.tagName)},r.prototype.allocate=function(e){if(!(this.storage.length>=e))for(var t=e-this.storage.length,n=0;t>n;n++)this.storage.push(this.create())},"undefined"!=typeof e&&"undefined"!=typeof e.exports&&(e.exports=r)},function(e,t,n){function r(e,t){"length"in e||(e=[e]),e=o.call(e);for(;e.length;){var n=e.shift(),r=t(n);if(r)return r;n.childNodes&&n.childNodes.length&&(e=o.call(n.childNodes).concat(e))}}var o=Array.prototype.slice;e.exports=r},function(e,t,n){"use strict";var r=n(7);e.exports=function(e,t,n){var o,i=e.length,a=void 0!==n?r(t,n):t;for(o=0;i>o;o++)a(e[o],o,e)}},function(e,t,n){"use strict";e.exports=function(e,t,n){var r=e.length,o=0;for("number"==typeof n&&(o=n,0>o&&(o+=r,0>o&&(o=0)));r>o;o++)if(e[o]===t)return o;return-1}},function(e,t,n){"use strict";var r=n(8);e.exports=function(e,t,n,o){var i,a,s=e.length,u=void 0!==o?r(t,o):t;for(void 0===n?(i=1,a=e[0]):(i=0,a=n);s>i;i++)a=u(a,e[i],i,e);return a}},function(e,t,n){"use strict";var r=n(36),o=n(41);e.exports=function(e,t,n){return e instanceof Array?r(e,t,n):o(e,t,n)}},function(e,t,n){"use strict";e.exports=function(e){var t,n,r,o,i,a,s=arguments.length;for(n=1;s>n;n++)for(t=arguments[n],o=Object.keys(t),r=o.length,a=0;r>a;a++)i=o[a],e[i]=t[i];return e}},function(e,t,n){"use strict";var r=n(7);e.exports=function(e,t,n){var o,i,a=Object.keys(e),s=a.length,u=void 0!==n?r(t,n):t;for(i=0;s>i;i++)o=a[i],u(e[o],o,e)}},function(e,t,n){"use strict";var r=n(8);e.exports=function(e,t,n,o){var i,a,s,u=Object.keys(e),c=u.length,l=void 0!==o?r(t,o):t;for(void 0===n?(i=1,s=e[u[0]]):(i=0,s=n);c>i;i++)a=u[i],s=l(s,e[a],a,e);return s}},function(e,t,n){"use strict";var r=n(38),o=n(42);e.exports=function(e,t,n,i){return e instanceof Array?r(e,t,n,i):o(e,t,n,i)}},function(e,t,n){var r=Date.now()%1e9;e.exports=function(){return(1e9*Math.random()>>>0)+r++}},function(e,t,n){e.exports=function(e){return e&&"object"==typeof e?window&&"object"==typeof window.Node?e instanceof window.Node:"number"==typeof e.nodeType&&"string"==typeof e.nodeName:!1}},function(e,t,n){function r(e){return e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=r},function(e,t,n){var r,o,i;!function(n,a){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(o=[],r=a,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i)))}(this,function(){"use strict";function e(e){if(!e)return!0;if(i(e)&&0===e.length)return!0;for(var t in e)if(p.call(e,t))return!1;return!0}function t(e){return l.call(e)}function n(e){return"number"==typeof e||"[object Number]"===t(e)}function r(e){return"string"==typeof e||"[object String]"===t(e)}function o(e){return"object"==typeof e&&"[object Object]"===t(e)}function i(e){return"object"==typeof e&&"number"==typeof e.length&&"[object Array]"===t(e)}function a(e){return"boolean"==typeof e||"[object Boolean]"===t(e)}function s(e){var t=parseInt(e);return t.toString()===e?t:e}function u(t,o,i,a){if(n(o)&&(o=[o]),e(o))return t;if(r(o))return u(t,o.split(".").map(s),i,a);var c=o[0];if(1===o.length){var l=t[c];return void 0!==l&&a||(t[c]=i),l}return void 0===t[c]&&(n(o[1])?t[c]=[]:t[c]={}),u(t[c],o.slice(1),i,a)}function c(t,o){if(n(o)&&(o=[o]),e(t))return void 0;if(e(o))return t;if(r(o))return c(t,o.split("."));var a=s(o[0]),u=t[a];if(1===o.length)void 0!==u&&(i(t)?t.splice(a,1):delete t[a]);else if(void 0!==t[a])return c(t[a],o.slice(1));return t}var l=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d={};return d.has=function(t,a){if(e(t))return!1;if(n(a)?a=[a]:r(a)&&(a=a.split(".")),e(a)||0===a.length)return!1;for(var s=0;s<a.length;s++){var u=a[s];if(!o(t)&&!i(t)||!p.call(t,u))return!1;t=t[u]}return!0},d.ensureExists=function(e,t,n){return u(e,t,n,!0)},d.set=function(e,t,n,r){return u(e,t,n,r)},d.insert=function(e,t,n,r){var o=d.get(e,t);r=~~r,i(o)||(o=[],d.set(e,t,o)),o.splice(r,0,n)},d.empty=function(t,s){if(e(s))return t;if(e(t))return void 0;var u,c;if(!(u=d.get(t,s)))return t;if(r(u))return d.set(t,s,"");if(a(u))return d.set(t,s,!1);if(n(u))return d.set(t,s,0);if(i(u))u.length=0;else{if(!o(u))return d.set(t,s,null);for(c in u)p.call(u,c)&&delete u[c]}},d.push=function(e,t){var n=d.get(e,t);i(n)||(n=[],d.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},d.coalesce=function(e,t,n){for(var r,o=0,i=t.length;i>o;o++)if(void 0!==(r=d.get(e,t[o])))return r;return n},d.get=function(t,o,i){if(n(o)&&(o=[o]),e(o))return t;if(e(t))return i;if(r(o))return d.get(t,o.split("."),i);var a=s(o[0]);return 1===o.length?void 0===t[a]?i:t[a]:d.get(t[a],o.slice(1),i)},d.del=function(e,t){return c(e,t)},d})},function(e,t,n){e.exports=t=n(49)},function(e,t,n){e.exports=function(e,t,n){var r=[],o=e.length;if(0===o)return r;var i=0>t?Math.max(0,t+o):t||0;for(void 0!==n&&(o=0>n?n+o:n);o-->i;)r[o-i]=e[o];return r}},function(e,t,n){function r(e,t){for(var n=0;n<e.length;n++){var r=e[n],o=p[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(s(r.parts[i],t))}else{for(var a=[],i=0;i<r.parts.length;i++)a.push(s(r.parts[i],t));p[r.id]={id:r.id,refs:1,parts:a}}}}function o(e){for(var t=[],n={},r=0;r<e.length;r++){var o=e[r],i=o[0],a=o[1],s=o[2],u=o[3],c={css:a,media:s,sourceMap:u};n[i]?n[i].parts.push(c):t.push(n[i]={id:i,parts:[c]})}return t}function i(){var e=document.createElement("style"),t=h();return e.type="text/css",t.appendChild(e),e}function a(){var e=document.createElement("link"),t=h();return e.rel="stylesheet",t.appendChild(e),e}function s(e,t){var n,r,o;if(t.singleton){var s=y++;n=v||(v=i()),r=u.bind(null,n,s,!1),o=u.bind(null,n,s,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(),r=l.bind(null,n),o=function(){n.parentNode.removeChild(n),n.href&&URL.revokeObjectURL(n.href)}):(n=i(),r=c.bind(null,n),o=function(){n.parentNode.removeChild(n)});return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else o()}}function u(e,t,n,r){var o=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=m(t,o);else{var i=document.createTextNode(o),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function c(e,t){var n=t.css,r=t.media;t.sourceMap;if(r&&e.setAttribute("media",r),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function l(e,t){var n=t.css,r=(t.media,t.sourceMap);r&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([n],{type:"text/css"}),i=e.href;e.href=URL.createObjectURL(o),i&&URL.revokeObjectURL(i)}var p={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},f=d(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),h=d(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,y=0;e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=f());var n=o(e);return r(n,t),function(e){for(var i=[],a=0;a<n.length;a++){var s=n[a],u=p[s.id];u.refs--,i.push(u)}if(e){var c=o(e);r(c,t)}for(var a=0;a<i.length;a++){var u=i[a];if(0===u.refs){for(var l=0;l<u.parts.length;l++)u.parts[l]();delete p[u.id]}}}};var m=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()}]);
src/shared/components/DemoApp/Error404/Error404.js
LorbusChris/react-universally
/* @flow */ import React from 'react'; function Error404() { return ( <div>Sorry, that page was not found.</div> ); } export default Error404;
scripts/publish-npm.js
tadeuzagallo/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. */ 'use strict'; /** * This script publishes a new version of react-native to NPM. * It is supposed to run in CI environment, not on a developer's machine. * * To make it easier for developers it uses some logic to identify with which version to publish the package. * * To cut a branch (and release RC): * - Developer: `git checkout -b 0.XY-stable` * - Developer: `git tag v0.XY.0-rc` and `git push --tags` to [email protected]:facebook/react-native.git * - CI: test and deploy to npm (run this script) with version 0.XY.0-rc with tag "next" * * To update RC release: * - Developer: `git checkout 0.XY-stable` * - Developer: cherry-pick whatever changes needed * - Developer: `git tag v0.XY.0-rc1` and `git push --tags` to [email protected]:facebook/react-native.git * - CI: test and deploy to npm (run this script) with version 0.XY.0-rc1 with tag "next" * * To publish a release: * - Developer: `git checkout 0.XY-stable` * - Developer: cherry-pick whatever changes needed * - Developer: `git tag latest` * - Developer: `git tag v0.XY.0` * - Developer: `git push --tags` to [email protected]:facebook/react-native.git * - CI: test and deploy to npm (run this script) with version 0.XY.0 with and not tag (latest is implied by npm) * * To patch old release: * - Developer: `git checkout 0.XY-stable` * - Developer: cherry-pick whatever changes needed * - Developer: `git tag v0.XY.Z` * - Developer: `git push` to [email protected]:facebook/react-native.git (or merge as pull request) * - CI: test and deploy to npm (run this script) with version 0.XY.Z with no tag, npm will not mark it as latest if * there is a version higher than XY * * Important tags: * If tag v0.XY.0-rcZ is present on the commit then publish to npm with version 0.XY.0-rcZ and tag next * If tag v0.XY.Z is present on the commit then publish to npm with version 0.XY.Z and no tag (npm will consider it latest) */ /*eslint-disable no-undef */ require(`shelljs/global`); const buildBranch = process.env.CIRCLE_BRANCH; let branchVersion; if (buildBranch.indexOf(`-stable`) !== -1) { branchVersion = buildBranch.slice(0, buildBranch.indexOf(`-stable`)); } else { echo(`Error: We publish only from stable branches`); exit(0); } // 34c034298dc9cad5a4553964a5a324450fda0385 const currentCommit = exec(`git rev-parse HEAD`, {silent: true}).stdout.trim(); // [34c034298dc9cad5a4553964a5a324450fda0385, refs/heads/0.33-stable, refs/tags/latest, refs/tags/v0.33.1, refs/tags/v0.34.1-rc] const tagsWithVersion = exec(`git ls-remote origin | grep ${currentCommit}`, {silent: true}) .stdout.split(/\s/) // ['refs/tags/v0.33.0', 'refs/tags/v0.33.0-rc', 'refs/tags/v0.33.0-rc1', 'refs/tags/v0.33.0-rc2', 'refs/tags/v0.34.0'] .filter(version => !!version && version.indexOf(`refs/tags/v${branchVersion}`) === 0) // ['refs/tags/v0.33.0', 'refs/tags/v0.33.0-rc', 'refs/tags/v0.33.0-rc1', 'refs/tags/v0.33.0-rc2'] .filter(version => version.indexOf(branchVersion) !== -1) // ['v0.33.0', 'v0.33.0-rc', 'v0.33.0-rc1', 'v0.33.0-rc2'] .map(version => version.slice(`refs/tags/`.length)); if (tagsWithVersion.length === 0) { echo(`Error: Can't find version tag in current commit. To deploy to NPM you must add tag v0.XY.Z[-rc] to your commit`); exit(1); } let releaseVersion; if (tagsWithVersion[0].indexOf(`-rc`) === -1) { // if first tag on this commit is non -rc then we are making a stable release // '0.33.0' releaseVersion = tagsWithVersion[0].slice(1); } else { // otherwise pick last -rc tag alphabetically // 0.33.0-rc2 releaseVersion = tagsWithVersion[tagsWithVersion.length - 1].slice(1); } // -------- Generating Android Artifacts with JavaDoc if (exec(`./gradlew :ReactAndroid:installArchives`).code) { echo(`Couldn't generate artifacts`); exit(1); } // undo uncommenting javadoc setting exec(`git checkout ReactAndroid/gradle.properties`); echo("Generated artifacts for Maven"); let artifacts = ['-javadoc.jar', '-sources.jar', '.aar', '.pom'].map((suffix) => { return `react-native-${releaseVersion}${suffix}`; }); artifacts.forEach((name) => { if (!test(`-e`, `./android/com/facebook/react/react-native/${releaseVersion}/${name}`)) { echo(`file ${name} was not generated`); exit(1); } }); if (releaseVersion.indexOf(`-rc`) === -1) { // release, package will be installed by default exec(`npm publish`); } else { // RC release, package will be installed only if users specifically do it exec(`npm publish --tag next`); } echo(`Published to npm ${releaseVersion}`); exit(0); /*eslint-enable no-undef */
modules/Route.js
stshort/react-router
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { component, components } from './InternalPropTypes' const { string, func } = React.PropTypes /** * 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. */ /* eslint-disable react/require-render-return */ const Route = React.createClass({ statics: { createRouteFromReactElement }, propTypes: { path: string, component, components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Route> elements are for router configuration only and should not be rendered' ) } }) export default Route
imports/client/ui/pages/WhitePaper/Why/Content.js
focallocal/fl-maps
// External Libraries import React from 'react' import { Container, Col } from 'reactstrap' // Internal Imports import DCSLink from '/imports/client/ui/components/DCSLink/index.js' import i18n from '/imports/both/i18n/en/' const Content = (props) => { return ( <React.Fragment> <Container className="mt-5 mb-4"> <h1>The World Needs a Public Happiness Economy Because:</h1> <br /> <h3>Short</h3> </Container> {i18n.Whitepaper.Why.concise.map((item, index) => { return ( <Col key={index} className="pl-5 mt-3 wp-item" xs={11}> <details> <summary> <h5>{item.heading} </h5> <DCSLink badge="true" format="speech-bubble" title=" " subtitle="discuss" triggerId={`short${index + 1}`} display="inline" /> </summary> <li className="mb-1 mt-2 text-left">{item.text}</li> </details> </Col> ); })} <Container className="mt-5 mb-4"> <h3>Longer</h3> </Container> {i18n.Whitepaper.Why['more depth'].map((item, index) => { return ( <Col key={index} className="pl-5 mt-3 wp-item" xs={11}> <details> <summary> <h5>{item.heading} </h5> <DCSLink badge="true" format="speech-bubble" title=" " subtitle="discuss" triggerId={`longer${index + 1}`} display="inline" /> </summary> <li className="mb-1 mt-2 text-left">{item.text}</li> <li className="mb-1 text-left">{item.answer}</li> </details> </Col> ); })} </React.Fragment> ); } export default Content
docs/app/Examples/elements/Segment/Variations/SegmentExampleClearing.js
shengnian/shengnian-ui-react
import React from 'react' import { Button, Segment } from 'shengnian-ui-react' const SegmentExampleClearing = () => ( <Segment clearing> <Button floated='right'> floated </Button> </Segment> ) export default SegmentExampleClearing
src/js/components/meter/utils.js
marlonpp/grommet-old
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { PropTypes } from 'react'; function polarToCartesian (centerX, centerY, radius, angleInDegrees) { var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0; return { x: centerX + (radius * Math.cos(angleInRadians)), y: centerY + (radius * Math.sin(angleInRadians)) }; } module.exports = { baseUnit: 24, baseDimension: 192, // 24 * 8 classRoot: 'meter', propTypes: { activeIndex: PropTypes.number, a11yDesc: PropTypes.string, a11yDescId: PropTypes.string, max: PropTypes.shape({ value: PropTypes.number, label: PropTypes.string }).isRequired, min: PropTypes.shape({ value: PropTypes.number, label: PropTypes.string }).isRequired, onActivate: PropTypes.func.isRequired, // size: PropTypes.oneOf(['small', 'medium', 'large']).isRequired, series: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string, value: PropTypes.number.isRequired, colorIndex: PropTypes.string, important: PropTypes.bool, onClick: PropTypes.func })).isRequired, total: PropTypes.number.isRequired, units: PropTypes.string }, polarToCartesian: polarToCartesian, arcCommands: function (centerX, centerY, radius, startAngle, endAngle) { var start = polarToCartesian(centerX, centerY, radius, endAngle); var end = polarToCartesian(centerX, centerY, radius, startAngle); var arcSweep = endAngle - startAngle <= 180 ? "0" : "1"; var d = [ "M", start.x, start.y, "A", radius, radius, 0, arcSweep, 0, end.x, end.y ].join(" "); return d; }, translateEndAngle: function (startAngle, anglePer, value) { return Math.min(360, Math.max(0, startAngle + (anglePer * value))); }, buildPath (itemIndex, commands, classes, onActivate, onClick, a11yDescId) { if (onActivate) { var onOver = onActivate.bind(null, itemIndex); var onOut = onActivate.bind(null, null); return ( <path key={itemIndex} className={classes.join(' ')} d={commands} tabIndex="0" onFocus={onOver} onBlur={onOut} onMouseOver={onOver} onMouseOut={onOut} onClick={onClick} role="img" aria-labelledby={a11yDescId} /> ); } else { return ( <path key={itemIndex} className={classes.join(' ')} d={commands} /> ); } } };
src/main/components/lib/json-schema-form-controller.js
hayond/web-pack-example
import React from 'react' import ObjectJsonSchema from './schema/object-json-schema' export default class JsonSchemaFormController { jsonSchema = null baseFieldProps = {} componentContext = {} initController() { } getValues() { } setValues() { } reset() { } componentDefaultSchema(type) { let componentMeta = { type: '', props: {} } if (type === 'string') { componentMeta.type = 'input' } else if (type === 'number') { componentMeta.type = 'input' componentMeta.props.type = 'number' } else if (type === 'boolean') { componentMeta.type = 'input' componentMeta.props.type = 'checkbox' } else if (type === 'object') { componentMeta.type = 'form' } return componentMeta } firstFieldSchemaToProps(fieldSchemaObject, props, formSchemaObject) { } getDefaultComponent(componentType, props, children, schemaObject) { return [componentType, props, children] } lastFieldSchemaToProps(fieldSchemaObject, props, formSchemaObject) { } renderField(component, props, children, fieldSchemaObject, formSchemaObject) { return React && React.createElement(component, props, children) } renderForm(component, props, children, formSchemaObject) { return React && React.createElement(component, props, children) } formPropsToBaseFieldProps(formProps) { if ('fieldProps' in formProps) { let {fieldProps} = this.drawProps(formProps, ['fieldProps']) Object.assign(this.baseFieldProps, fieldProps) } } getCustomComponent(componentType, props, children, schemaObject) { let component = this.componentContext[componentType] if (component && typeof component === 'array' && component.length === 2) { let [tempComp, propsHandler] = component propsHandler(schemaObject, props, componentMeta) component = tempComp } return [component, props, children] } registerCustomComponent(componentType, component, propsHandler) { let value = propsHandler ? [component, propsHandler] : component this.componentContext[componentType] = value } drawProps(props, keys, ...excludes) { let drawProps = {} keys.forEach(key => { let value = props[key] value !== undefined && (drawProps[key] = value) if (excludes.indexOf(key) === -1) { delete props[key] } }) return drawProps } getSchemaComponentArguments(schemaObject, baseProps={}) { let componentMeta = schemaObject.extKeyMap['component'] let componentType = '' let component = null let props = {} let children = null if (!componentMeta) { componentMeta = this.componentDefaultSchema(schemaObject.type) } else if (!componentMeta.type || !(componentMeta.type in this.componentContext)) { let tempCompMeta = this.componentDefaultSchema(schemaObject.type) componentMeta.props && Object.assign(tempCompMeta.props, componentMeta.props) componentMeta = tempCompMeta } componentType = componentMeta.type props = Object.assign(baseProps, componentMeta.props) return (componentType in this.componentContext) ? this.getCustomComponent(componentType, props, children, schemaObject) : this.getDefaultComponent(componentType, props, children, schemaObject) } generate(appendedChildren) { let formSchemaObject = this.jsonSchema ? new ObjectJsonSchema(this.jsonSchema) : null if (!formSchemaObject) return null let [formComponent, formProps, formChildren] = this.getSchemaComponentArguments(formSchemaObject) this.formPropsToBaseFieldProps(formProps) formChildren = formSchemaObject.properties ? Object.entries(formSchemaObject.properties).map(([name, fieldSchemaObject], i) => { let tempProps = { key: i, name: name } this.firstFieldSchemaToProps(fieldSchemaObject, tempProps, formSchemaObject) let [component, props, children] = this.getSchemaComponentArguments(fieldSchemaObject, tempProps) props = Object.assign({}, this.baseFieldProps, props) this.lastFieldSchemaToProps(fieldSchemaObject, props, formSchemaObject) return this.renderField(component, props, children, fieldSchemaObject, formSchemaObject) }) : [] appendedChildren && (formChildren = formChildren.concat(appendedChildren)) return this.renderForm(formComponent, formProps, formChildren, formSchemaObject) } }
node_modules/material-ui/svg-icons/av/games.js
tempestaddepvc/proyecto-electron
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AvGames = function AvGames(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z' }) ); }; AvGames = (0, _pure2.default)(AvGames); AvGames.displayName = 'AvGames'; exports.default = AvGames;
docs/src/pages/styles/advanced/UseTheme.js
lgollut/material-ui
import React from 'react'; import { ThemeProvider, useTheme } from '@material-ui/core/styles'; function DeepChild() { const theme = useTheme(); return <span>{`spacing ${theme.spacing}`}</span>; } export default function UseTheme() { return ( <ThemeProvider theme={{ spacing: '8px', }} > <DeepChild /> </ThemeProvider> ); }
app/javascript/user_profile/index.js
DaveSpivey/muttwhat
import React from 'react'; import ReactDOM from 'react-dom'; import UserProfilePage from './UserProfilePage.jsx'; document.addEventListener('DOMContentLoaded', () => { const node = document.getElementById('user-profile-page'); const data = JSON.parse(node.getAttribute('data')); ReactDOM.render( <UserProfilePage userId={ data.user.id } username={ data.user.username } breeds={ data.profile } mutts={ data.mutts } profilePhotos={ data.profilePhotos } />, node ); });
stubo/static/node_modules/react-tools/src/browser/ui/ReactDefaultInjection.js
Stub-O-Matic-BA/stubo-app
/** * 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. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = require('BeforeInputEventPlugin'); var ChangeEventPlugin = require('ChangeEventPlugin'); var ClientReactRootIndex = require('ClientReactRootIndex'); var DefaultEventPluginOrder = require('DefaultEventPluginOrder'); var EnterLeaveEventPlugin = require('EnterLeaveEventPlugin'); var ExecutionEnvironment = require('ExecutionEnvironment'); var HTMLDOMPropertyConfig = require('HTMLDOMPropertyConfig'); var MobileSafariClickEventPlugin = require('MobileSafariClickEventPlugin'); var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); var ReactClass = require('ReactClass'); var ReactComponentBrowserEnvironment = require('ReactComponentBrowserEnvironment'); var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy'); var ReactDOMComponent = require('ReactDOMComponent'); var ReactDOMButton = require('ReactDOMButton'); var ReactDOMForm = require('ReactDOMForm'); var ReactDOMImg = require('ReactDOMImg'); var ReactDOMIDOperations = require('ReactDOMIDOperations'); var ReactDOMIframe = require('ReactDOMIframe'); var ReactDOMInput = require('ReactDOMInput'); var ReactDOMOption = require('ReactDOMOption'); var ReactDOMSelect = require('ReactDOMSelect'); var ReactDOMTextarea = require('ReactDOMTextarea'); var ReactDOMTextComponent = require('ReactDOMTextComponent'); var ReactElement = require('ReactElement'); var ReactEventListener = require('ReactEventListener'); var ReactInjection = require('ReactInjection'); var ReactInstanceHandles = require('ReactInstanceHandles'); var ReactMount = require('ReactMount'); var ReactReconcileTransaction = require('ReactReconcileTransaction'); var SelectEventPlugin = require('SelectEventPlugin'); var ServerReactRootIndex = require('ServerReactRootIndex'); var SimpleEventPlugin = require('SimpleEventPlugin'); var SVGDOMPropertyConfig = require('SVGDOMPropertyConfig'); var createFullPageComponent = require('createFullPageComponent'); function autoGenerateWrapperClass(type) { return ReactClass.createClass({ tagName: type.toUpperCase(), render: function() { return new ReactElement( type, null, null, null, null, this.props ); } }); } function inject() { ReactInjection.EventEmitter.injectReactEventListener( ReactEventListener ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass( ReactDOMComponent ); ReactInjection.NativeComponent.injectTextComponentClass( ReactDOMTextComponent ); ReactInjection.NativeComponent.injectAutoWrapper( autoGenerateWrapperClass ); // This needs to happen before createFullPageComponent() otherwise the mixin // won't be included. ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.NativeComponent.injectComponentClasses({ 'button': ReactDOMButton, 'form': ReactDOMForm, 'iframe': ReactDOMIframe, 'img': ReactDOMImg, 'input': ReactDOMInput, 'option': ReactDOMOption, 'select': ReactDOMSelect, 'textarea': ReactDOMTextarea, 'html': createFullPageComponent('html'), 'head': createFullPageComponent('head'), 'body': createFullPageComponent('body') }); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction( ReactReconcileTransaction ); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); ReactInjection.DOMComponent.injectIDOperations(ReactDOMIDOperations); if (__DEV__) { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = require('ReactDefaultPerf'); ReactDefaultPerf.start(); } } } module.exports = { inject: inject };
ajax/libs/react-data-grid/0.13.8/react-data-grid.js
pvnr0082t/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["ReactDataGrid"] = factory(require("react")); else root["ReactDataGrid"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_18__) { 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 Grid = __webpack_require__(1); var Row = __webpack_require__(50); var Cell = __webpack_require__(51); module.exports = Grid; module.exports.Row = Row; module.exports.Cell = Cell; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(2)['default']; var _Object$assign = __webpack_require__(3)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var BaseGrid = __webpack_require__(19); var Row = __webpack_require__(50); var ExcelColumn = __webpack_require__(41); var KeyboardHandlerMixin = __webpack_require__(53); var CheckboxEditor = __webpack_require__(82); var FilterableHeaderCell = __webpack_require__(83); var cloneWithProps = __webpack_require__(29); var DOMMetrics = __webpack_require__(79); var ColumnMetricsMixin = __webpack_require__(84); var RowUtils = __webpack_require__(86); var ColumnUtils = __webpack_require__(25); if (!_Object$assign) { Object.assign = __webpack_require__(85); } var ReactDataGrid = React.createClass({ displayName: 'ReactDataGrid', propTypes: { rowHeight: React.PropTypes.number.isRequired, minHeight: React.PropTypes.number.isRequired, enableRowSelect: React.PropTypes.bool, onRowUpdated: React.PropTypes.func, rowGetter: React.PropTypes.func.isRequired, rowsCount: React.PropTypes.number.isRequired, toolbar: React.PropTypes.element, enableCellSelect: React.PropTypes.bool, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, onFilter: React.PropTypes.func, onCellCopyPaste: React.PropTypes.func, onCellsDragged: React.PropTypes.func, onAddFilter: React.PropTypes.func }, mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin], getDefaultProps: function getDefaultProps() { return { enableCellSelect: false, tabIndex: -1, rowHeight: 35, enableRowSelect: false, minHeight: 350 }; }, getInitialState: function getInitialState() { var columnMetrics = this.createColumnMetrics(true); var initialState = { columnMetrics: columnMetrics, selectedRows: this.getInitialSelectedRows(), copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 }; if (this.props.enableCellSelect) { initialState.selected = { rowIdx: 0, idx: 0 }; } else { initialState.selected = { rowIdx: -1, idx: -1 }; } return initialState; }, getInitialSelectedRows: function getInitialSelectedRows() { var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(false); } return selectedRows; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount === this.props.rowsCount + 1) { this.onAfterAddRow(nextProps.rowsCount + 1); } }, componentDidMount: function componentDidMount() { var scrollOffset = 0; var canvas = this.getDOMNode().querySelector('.react-grid-Canvas'); if (canvas != null) { scrollOffset = canvas.offsetWidth - canvas.clientWidth; } this.setState({ scrollOffset: scrollOffset }); }, render: function render() { var cellMetaData = { selected: this.state.selected, dragged: this.state.dragged, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCommit: this.onCellCommit, onCommitCancel: this.setInactive, copied: this.state.copied, handleDragEnterRow: this.handleDragEnter, handleTerminateDrag: this.handleTerminateDrag }; var toolbar = this.renderToolbar(); var gridWidth = this.DOMMetrics.gridWidth(); var containerWidth = gridWidth + this.state.scrollOffset; return React.createElement( 'div', { className: 'react-grid-Container', style: { width: containerWidth } }, toolbar, React.createElement( 'div', { className: 'react-grid-Main' }, React.createElement(BaseGrid, _extends({ ref: 'base' }, this.props, { headerRows: this.getHeaderRows(), columnMetrics: this.state.columnMetrics, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, rowHeight: this.props.rowHeight, cellMetaData: cellMetaData, selectedRows: this.state.selectedRows, expandedRows: this.state.expandedRows, rowOffsetHeight: this.getRowOffsetHeight(), sortColumn: this.state.sortColumn, sortDirection: this.state.sortDirection, onSort: this.handleSort, minHeight: this.props.minHeight, totalWidth: gridWidth, onViewportKeydown: this.onKeyDown, onViewportDragStart: this.onDragStart, onViewportDragEnd: this.handleDragEnd, onViewportDoubleClick: this.onViewportDoubleClick, onColumnResize: this.onColumnResize })) ) ); }, renderToolbar: function renderToolbar() { var Toolbar = this.props.toolbar; if (React.isValidElement(Toolbar)) { return cloneWithProps(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount }); } }, onSelect: function onSelect(selected) { if (this.props.enableCellSelect) { if (this.state.selected.rowIdx === selected.rowIdx && this.state.selected.idx === selected.idx && this.state.selected.active === true) {} else { var idx = selected.idx; var rowIdx = selected.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && rowIdx < this.props.rowsCount) { this.setState({ selected: selected }); } } } }, onCellClick: function onCellClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); }, onCellDoubleClick: function onCellDoubleClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); this.setActive('Enter'); }, onViewportDoubleClick: function onViewportDoubleClick(e) { this.setActive(); }, onPressArrowUp: function onPressArrowUp(e) { this.moveSelectedCell(e, -1, 0); }, onPressArrowDown: function onPressArrowDown(e) { this.moveSelectedCell(e, 1, 0); }, onPressArrowLeft: function onPressArrowLeft(e) { this.moveSelectedCell(e, 0, -1); }, onPressArrowRight: function onPressArrowRight(e) { this.moveSelectedCell(e, 0, 1); }, onPressTab: function onPressTab(e) { this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1); }, onPressEnter: function onPressEnter(e) { this.setActive(e.key); }, onPressDelete: function onPressDelete(e) { this.setActive(e.key); }, onPressEscape: function onPressEscape(e) { this.setInactive(e.key); }, onPressBackspace: function onPressBackspace(e) { this.setActive(e.key); }, onPressChar: function onPressChar(e) { if (this.isKeyPrintable(e.keyCode)) { this.setActive(e.keyCode); } }, onPressKeyWithCtrl: function onPressKeyWithCtrl(e) { var keys = { KeyCode_c: 99, KeyCode_C: 67, KeyCode_V: 86, KeyCode_v: 118 }; var idx = this.state.selected.idx; if (this.canEdit(idx)) { if (e.keyCode == keys.KeyCode_c || e.keyCode == keys.KeyCode_C) { var value = this.getSelectedValue(); this.handleCopy({ value: value }); } else if (e.keyCode == keys.KeyCode_v || e.keyCode == keys.KeyCode_V) { this.handlePaste(); } } }, onDragStart: function onDragStart(e) { var value = this.getSelectedValue(); this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value }); //need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) { // we need to prevent default as we control grid scroll //otherwise it moves every time you left/right which is janky e.preventDefault(); var rowIdx = this.state.selected.rowIdx + rowDelta; var idx = this.state.selected.idx + cellDelta; this.onSelect({ idx: idx, rowIdx: rowIdx }); }, getSelectedValue: function getSelectedValue() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; var cellKey = this.getColumn(this.state.columnMetrics.columns, idx).key; var row = this.props.rowGetter(rowIdx); return RowUtils.get(row, cellKey); }, setActive: function setActive(keyPressed) { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && !this.isActive()) { var selected = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed }); this.setState({ selected: selected }); } }, setInactive: function setInactive() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && this.isActive()) { var selected = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false }); this.setState({ selected: selected }); } }, canEdit: function canEdit(idx) { var col = this.getColumn(this.props.columns, idx); return this.props.enableCellSelect === true && (col.editor != null || col.editable); }, isActive: function isActive() { return this.state.selected.active === true; }, onCellCommit: function onCellCommit(commit) { var selected = _Object$assign({}, this.state.selected); selected.active = false; if (commit.key === 'Tab') { selected.idx += 1; } var expandedRows = this.state.expandedRows; // if(commit.changed && commit.changed.expandedHeight){ // expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight); // } this.setState({ selected: selected, expandedRows: expandedRows }); this.props.onRowUpdated(commit); }, setupGridColumns: function setupGridColumns() { var cols = this.props.columns.slice(0); if (this.props.enableRowSelect) { var selectColumn = { key: 'select-row', name: '', formatter: React.createElement(CheckboxEditor, null), onCellChange: this.handleRowSelect, filterable: false, headerRenderer: React.createElement('input', { type: 'checkbox', onChange: this.handleCheckboxChange }), width: 60, locked: true }; var unshiftedCols = cols.unshift(selectColumn); cols = unshiftedCols > 0 ? cols : unshiftedCols; } return cols; }, handleCheckboxChange: function handleCheckboxChange(e) { var allRowsSelected; if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) { allRowsSelected = true; } else { allRowsSelected = false; } var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(allRowsSelected); } this.setState({ selectedRows: selectedRows }); }, // columnKey not used here as this function will select the whole row, // but needed to match the function signature in the CheckboxEditor handleRowSelect: function handleRowSelect(rowIdx, columnKey, e) { e.stopPropagation(); if (this.state.selectedRows != null && this.state.selectedRows.length > 0) { var selectedRows = this.state.selectedRows.slice(); if (selectedRows[rowIdx] == null || selectedRows[rowIdx] == false) { selectedRows[rowIdx] = true; } else { selectedRows[rowIdx] = false; } this.setState({ selectedRows: selectedRows }); } }, //EXPAND ROW Functionality - removing for now till we decide on how best to implement // expandRow(row: Row, newHeight: number): Array<Row>{ // var expandedRows = this.state.expandedRows; // if(expandedRows[row]){ // if(expandedRows[row]== null || expandedRows[row] < newHeight){ // expandedRows[row] = newHeight; // } // }else{ // expandedRows[row] = newHeight; // } // return expandedRows; // }, // // handleShowMore(row: Row, newHeight: number) { // var expandedRows = this.expandRow(row, newHeight); // this.setState({expandedRows : expandedRows}); // }, // // handleShowLess(row: Row){ // var expandedRows = this.state.expandedRows; // if(expandedRows[row]){ // expandedRows[row] = false; // } // this.setState({expandedRows : expandedRows}); // }, // // expandAllRows(){ // // }, // // collapseAllRows(){ // // }, onAfterAddRow: function onAfterAddRow(numberOfRows) { this.setState({ selected: { idx: 1, rowIdx: numberOfRows - 2 } }); }, onToggleFilter: function onToggleFilter() { this.setState({ canFilter: !this.state.canFilter }); }, getHeaderRows: function getHeaderRows() { var rows = [{ ref: "row", height: this.props.rowHeight }]; if (this.state.canFilter === true) { rows.push({ ref: "filterRow", headerCellRenderer: React.createElement(FilterableHeaderCell, { onChange: this.props.onAddFilter, column: this.props.column }), height: 45 }); } return rows; }, getRowOffsetHeight: function getRowOffsetHeight() { var offsetHeight = 0; this.getHeaderRows().forEach(function (row) { return offsetHeight += parseFloat(row.height, 10); }); return offsetHeight; }, handleSort: function handleSort(columnKey, direction) { this.setState({ sortDirection: direction, sortColumn: columnKey }, function () { this.props.onGridSort(columnKey, direction); }); }, copyPasteEnabled: function copyPasteEnabled() { return this.props.onCellCopyPaste !== null; }, handleCopy: function handleCopy(args) { if (!this.copyPasteEnabled()) { return; } var textToCopy = args.value; var selected = this.state.selected; var copied = { idx: selected.idx, rowIdx: selected.rowIdx }; this.setState({ textToCopy: textToCopy, copied: copied }); }, handlePaste: function handlePaste() { if (!this.copyPasteEnabled()) { return; } var selected = this.state.selected; var cellKey = this.getColumn(this.state.columnMetrics.columns, this.state.selected.idx).key; if (this.props.onCellCopyPaste) { this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: selected.rowIdx, value: this.state.textToCopy, fromRow: this.state.copied.rowIdx, toRow: selected.rowIdx }); } this.setState({ copied: null }); }, dragEnabled: function dragEnabled() { return this.props.onCellsDragged !== null; }, handleDragStart: function handleDragStart(dragged) { if (!this.dragEnabled()) { return; } var idx = dragged.idx; var rowIdx = dragged.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) { this.setState({ dragged: dragged }); } }, handleDragEnter: function handleDragEnter(row) { if (!this.dragEnabled()) { return; } var selected = this.state.selected; var dragged = this.state.dragged; dragged.overRowIdx = row; this.setState({ dragged: dragged }); }, handleDragEnd: function handleDragEnd() { if (!this.dragEnabled()) { return; } var fromRow, toRow; var selected = this.state.selected; var dragged = this.state.dragged; var cellKey = this.getColumn(this.state.columnMetrics.columns, this.state.selected.idx).key; fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; if (this.props.onCellsDragged) { this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value }); } this.setState({ dragged: { complete: true } }); }, handleTerminateDrag: function handleTerminateDrag() { if (!this.dragEnabled()) { return; } this.setState({ dragged: null }); } }); module.exports = ReactDataGrid; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$assign = __webpack_require__(3)["default"]; exports["default"] = _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; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(4), __esModule: true }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(5); module.exports = __webpack_require__(8).Object.assign; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $def = __webpack_require__(6); $def($def.S + $def.F, 'Object', {assign: __webpack_require__(9)}); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(7) , core = __webpack_require__(8) , PROTOTYPE = 'prototype'; var ctx = function(fn, that){ return function(){ return fn.apply(that, arguments); }; }; var $def = function(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 && typeof target[key] != 'function')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 && typeof out == 'function' ? ctx(Function.call, out) : out; // export exports[key] = exp; if(isProto)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // 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 module.exports = $def; /***/ }, /* 7 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var UNDEFINED = 'undefined'; var global = module.exports = typeof window != UNDEFINED && window.Math == Math ? window : typeof self != UNDEFINED && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 8 */ /***/ function(module, exports) { var core = module.exports = {version: '1.2.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var toObject = __webpack_require__(10) , IObject = __webpack_require__(12) , enumKeys = __webpack_require__(14) , has = __webpack_require__(16); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(17)(function(){ var a = Object.assign , A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , l = arguments.length , i = 1; while(l > i){ var S = IObject(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(has(S, key = keys[j++]))T[key] = S[key]; } return T; } : Object.assign; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(11); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 11 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { // indexed object, fallback for non-array-like ES3 strings var cof = __webpack_require__(13); module.exports = 0 in Object('z') ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 13 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var $ = __webpack_require__(15); module.exports = function(it){ var keys = $.getKeys(it) , getSymbols = $.getSymbols; if(getSymbols){ var symbols = getSymbols(it) , isEnum = $.isEnum , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); } return keys; }; /***/ }, /* 15 */ /***/ function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }, /* 16 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 17 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 18 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_18__; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var Header = __webpack_require__(20); var Viewport = __webpack_require__(47); var ExcelColumn = __webpack_require__(41); var GridScrollMixin = __webpack_require__(81); var DOMMetrics = __webpack_require__(79); var Grid = React.createClass({ displayName: 'Grid', propTypes: { rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), minHeight: PropTypes.number, headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowHeight: PropTypes.number, rowRenderer: PropTypes.func, expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowsCount: PropTypes.number, onRows: PropTypes.func, sortColumn: React.PropTypes.string, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']), rowOffsetHeight: PropTypes.number.isRequired, onViewportKeydown: PropTypes.func.isRequired, onViewportDragStart: PropTypes.func.isRequired, onViewportDragEnd: PropTypes.func.isRequired, onViewportDoubleClick: PropTypes.func.isRequired }, mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin], getStyle: function getStyle() { return { overflow: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight }; }, render: function render() { var headerRows = this.props.headerRows || [{ ref: 'row' }]; return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }), React.createElement(Header, { ref: 'header', columnMetrics: this.props.columnMetrics, onColumnResize: this.props.onColumnResize, height: this.props.rowHeight, totalWidth: this.props.totalWidth, headerRows: headerRows, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort }), React.createElement( 'div', { ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd }, React.createElement(Viewport, { ref: 'viewport', width: this.props.columnMetrics.width, rowHeight: this.props.rowHeight, rowRenderer: this.props.rowRenderer, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columnMetrics: this.props.columnMetrics, totalWidth: this.props.totalWidth, onScroll: this.onScroll, onRows: this.props.onRows, cellMetaData: this.props.cellMetaData, rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length, minHeight: this.props.minHeight }) ) ); }, getDefaultProps: function getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; } }); module.exports = Grid; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var shallowCloneObject = __webpack_require__(22); var ColumnMetrics = __webpack_require__(23); var ColumnUtils = __webpack_require__(25); var HeaderRow = __webpack_require__(26); var Header = React.createClass({ displayName: 'Header', propTypes: { columnMetrics: React.PropTypes.shape({ width: React.PropTypes.number.isRequired }).isRequired, totalWidth: React.PropTypes.number, height: React.PropTypes.number.isRequired, headerRows: React.PropTypes.array.isRequired }, render: function render() { var state = this.state.resizing || this.props; var className = joinClasses({ 'react-grid-Header': true, 'react-grid-Header--resizing': !!this.state.resizing }); var headerRows = this.getHeaderRows(); return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: className }), headerRows ); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth != nextProps.totalWidth || this.props.headerRows.length != nextProps.headerRows.length || this.state.resizing != nextState.resizing || this.props.sortColumn != nextProps.sortColumn || this.props.sortDirection != nextProps.sortDirection; return update; }, getHeaderRows: function getHeaderRows() { var columnMetrics = this.getColumnMetrics(); var resizeColumn; if (this.state.resizing) { resizeColumn = this.state.resizing.column; } var headerRows = []; this.props.headerRows.forEach((function (row, index) { var headerRowStyle = { position: 'absolute', top: this.props.height * index, left: 0, width: this.props.totalWidth, overflow: 'hidden' }; headerRows.push(React.createElement(HeaderRow, { key: row.ref, ref: row.ref, style: headerRowStyle, onColumnResize: this.onColumnResize, onColumnResizeEnd: this.onColumnResizeEnd, width: columnMetrics.width, height: row.height || this.props.height, columns: columnMetrics.columns, resizing: resizeColumn, headerCellRenderer: row.headerCellRenderer, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort })); }).bind(this)); return headerRows; }, getInitialState: function getInitialState() { return { resizing: null }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ resizing: null }); }, onColumnResize: function onColumnResize(column, width) { var state = this.state.resizing || this.props; var pos = this.getColumnPosition(column); if (pos != null) { var resizing = { columnMetrics: shallowCloneObject(state.columnMetrics) }; resizing.columnMetrics = ColumnMetrics.resizeColumn(resizing.columnMetrics, pos, width); // we don't want to influence scrollLeft while resizing if (resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) { resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth; } resizing.column = ColumnUtils.getColumn(resizing.columnMetrics.columns, pos); this.setState({ resizing: resizing }); } }, getColumnMetrics: function getColumnMetrics() { var columnMetrics; if (this.state.resizing) { columnMetrics = this.state.resizing.columnMetrics; } else { columnMetrics = this.props.columnMetrics; } return columnMetrics; }, getColumnPosition: function getColumnPosition(column) { var columnMetrics = this.getColumnMetrics(); var pos = -1; columnMetrics.columns.forEach(function (c, idx) { if (c.key === column.key) { pos = idx; } }); return pos === -1 ? null : pos; }, onColumnResizeEnd: function onColumnResizeEnd(column, width) { var pos = this.getColumnPosition(column); if (pos !== null && this.props.onColumnResize) { this.props.onColumnResize(pos, width || column.width); } }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = this.refs.row.getDOMNode(); node.scrollLeft = scrollLeft; this.refs.row.setScrollLeft(scrollLeft); }, getStyle: function getStyle() { return { position: 'relative', height: this.props.height * this.props.headerRows.length, overflow: 'hidden' }; } }); module.exports = Header; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 22 */ /***/ function(module, exports) { /** * @jsx React.DOM */ 'use strict'; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _Object$assign = __webpack_require__(3)['default']; var shallowCloneObject = __webpack_require__(22); var isValidElement = __webpack_require__(18).isValidElement; var sameColumn = __webpack_require__(24); var ColumnUtils = __webpack_require__(25); /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = _Object$assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column, i, arr) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); metrics = shallowCloneObject(metrics); metrics.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metrics.minColumnWidth); metrics = ColumnUtils.spliceColumn(metrics, index, updatedColumn); return recalculate(metrics); } function areColumnsImmutable(prevColumns, nextColumns) { return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List; } function compareEachColumn(prevColumns, nextColumns, sameColumn) { var i, len, column; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !sameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, sameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } else { return compareEachColumn(prevColumns, nextColumns, sameColumn); } } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* TODO objects as a map */ 'use strict'; var isValidElement = __webpack_require__(18).isValidElement; module.exports = function sameColumn(a, b) { var k; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 25 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } } }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var shallowEqual = __webpack_require__(27); var HeaderCell = __webpack_require__(28); var getScrollbarSize = __webpack_require__(45); var ExcelColumn = __webpack_require__(41); var ColumnUtilsMixin = __webpack_require__(25); var SortableHeaderCell = __webpack_require__(46); var HeaderRowStyle = { overflow: React.PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: React.PropTypes.number, position: React.PropTypes.string }; var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var HeaderRow = React.createClass({ displayName: 'HeaderRow', propTypes: { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), onColumnResize: PropTypes.func, onSort: PropTypes.func.isRequired, style: PropTypes.shape(HeaderRowStyle) }, mixins: [ColumnUtilsMixin], render: function render() { var cellsStyle = { width: this.props.width ? this.props.width + getScrollbarSize() : '100%', height: this.props.height, whiteSpace: 'nowrap', overflowX: 'hidden', overflowY: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: 'react-grid-HeaderRow' }), React.createElement( 'div', { style: cellsStyle }, cells ) ); }, getHeaderRenderer: function getHeaderRenderer(column) { if (column.sortable) { var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE; return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection }); } else { return this.props.headerCellRenderer || column.headerRenderer || this.props.cellRenderer; } }, getCells: function getCells() { var cells = []; var lockedCells = []; for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) { var column = this.getColumn(this.props.columns, i); var cell = React.createElement(HeaderCell, { ref: i, key: i, height: this.props.height, column: column, renderer: this.getHeaderRenderer(column), resizing: this.props.resizing === column, onResize: this.props.onColumnResize, onResizeEnd: this.props.onColumnResizeEnd }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } } return cells.concat(lockedCells); }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this = this; this.props.columns.forEach(function (column, i) { if (column.locked) { _this.refs[i].setScrollLeft(scrollLeft); } }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn != nextProps.sortColumn || this.props.sortDirection != nextProps.sortDirection; }, getStyle: function getStyle() { return { overflow: 'hidden', width: '100%', height: this.props.height, position: 'absolute' }; } }); module.exports = HeaderRow; /***/ }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* TODO unkwon */ /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var cloneWithProps = __webpack_require__(29); var PropTypes = React.PropTypes; var ExcelColumn = __webpack_require__(41); var ResizeHandle = __webpack_require__(43); var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired }, render: function render() { var resizeHandle; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, { resizeHandle: resizeHandle } ); }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { return cloneWithProps(this.props.renderer, { column: this.props.column }); } else { var Renderer = this.props.renderer; return this.props.renderer({ column: this.props.column }); } }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = React.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', overflow: 'hidden', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); //need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; //for flows sake, doesnt recognise a null check direct if (resize) { var width = this.getWidthFromMouseEvent(e); if (width > 0) { resize(this.props.column, width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX; var left = React.findDOMNode(this).getBoundingClientRect().left; return right - left; } }); function simpleCellRenderer(props) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, props.column.name ); } var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, render: function render() { return React.createElement( 'span', null, this.props.value ); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return nextProps.value !== this.props.value; } }); module.exports = HeaderCell; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(31); var ReactPropTransferer = __webpack_require__(38); var keyOf = __webpack_require__(40); var warning = __webpack_require__(35); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30))) /***/ }, /* 30 */ /***/ 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; }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(32); var ReactCurrentOwner = __webpack_require__(37); var assign = __webpack_require__(33); var warning = __webpack_require__(35); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(33); var emptyObject = __webpack_require__(34); var warning = __webpack_require__(35); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30))) /***/ }, /* 33 */ /***/ function(module, exports) { /** * 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. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== process.env.NODE_ENV) { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(36); /** * 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 = emptyFunction; if ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); 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 (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // 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; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(30))) /***/ }, /* 36 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 37 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 38 */ /***/ 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. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(33); var emptyFunction = __webpack_require__(36); var joinClasses = __webpack_require__(39); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 39 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 40 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _classCallCheck = __webpack_require__(42)['default']; var React = __webpack_require__(18); var ExcelColumn = function ExcelColumn() { _classCallCheck(this, ExcelColumn); }; var ExcelColumnShape = { name: React.PropTypes.string.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired }; module.exports = ExcelColumnShape; /***/ }, /* 42 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.__esModule = true; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var Draggable = __webpack_require__(44); var cloneWithProps = __webpack_require__(29); var PropTypes = React.PropTypes; var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /* need */ /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var PropTypes = React.PropTypes; var emptyFunction = __webpack_require__(36); var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]) }, render: function render() { var Component = this.props.component; return React.createElement('div', _extends({}, this.props, { onMouseDown: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); }, getDefaultProps: function getDefaultProps() { return { onDragStart: emptyFunction.thatReturnsTrue, onDragEnd: emptyFunction, onDrag: emptyFunction }; }, getInitialState: function getInitialState() { return { drag: null }; }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); } }); module.exports = Draggable; /***/ }, /* 45 */ /***/ function(module, exports) { /* offsetWidth in HTMLElement */ "use strict"; var size; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.overflowY = 'scroll'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var outerWidth = outer.clientWidth; var innerWidth = inner.clientWidth; document.body.removeChild(outer); size = outerWidth - innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var ExcelColumn = __webpack_require__(41); var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var SortableHeaderCell = React.createClass({ displayName: 'SortableHeaderCell', propTypes: { columnKey: React.PropTypes.string.isRequired, onSort: React.PropTypes.func.isRequired, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']) }, onClick: function onClick() { var direction; switch (this.props.sortDirection) { case null: case undefined: case DEFINE_SORT.NONE: direction = DEFINE_SORT.ASC; break; case DEFINE_SORT.ASC: direction = DEFINE_SORT.DESC; break; case DEFINE_SORT.DESC: direction = DEFINE_SORT.NONE; break; } this.props.onSort(this.props.columnKey, direction); }, getSortByText: function getSortByText() { var unicodeKeys = { 'ASC': '9650', 'DESC': '9660', 'NONE': '' }; return String.fromCharCode(unicodeKeys[this.props.sortDirection]); }, render: function render() { return React.createElement( 'div', { onClick: this.onClick, style: { cursor: 'pointer' } }, this.props.column.name, React.createElement( 'span', { className: 'pull-right' }, this.getSortByText() ) ); } }); module.exports = SortableHeaderCell; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var Canvas = __webpack_require__(48); var PropTypes = React.PropTypes; var ViewportScroll = __webpack_require__(78); var Viewport = React.createClass({ displayName: 'Viewport', mixins: [ViewportScroll], propTypes: { rowOffsetHeight: PropTypes.number.isRequired, totalWidth: PropTypes.number.isRequired, columnMetrics: PropTypes.object.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, selectedRows: PropTypes.array, expandedRows: PropTypes.array, rowRenderer: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowHeight: PropTypes.number.isRequired, onRows: PropTypes.func, onScroll: PropTypes.func, minHeight: PropTypes.number }, render: function render() { var style = { padding: 0, bottom: 0, left: 0, right: 0, overflow: 'hidden', position: 'absolute', top: this.props.rowOffsetHeight }; return React.createElement( 'div', { className: 'react-grid-Viewport', style: style }, React.createElement(Canvas, { ref: 'canvas', totalWidth: this.props.totalWidth, width: this.props.columnMetrics.width, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columns: this.props.columnMetrics.columns, rowRenderer: this.props.rowRenderer, visibleStart: this.state.visibleStart, visibleEnd: this.state.visibleEnd, displayStart: this.state.displayStart, displayEnd: this.state.displayEnd, cellMetaData: this.props.cellMetaData, height: this.state.height, rowHeight: this.props.rowHeight, onScroll: this.onScroll, onRows: this.props.onRows }) ); }, getScroll: function getScroll() { return this.refs.canvas.getScroll(); }, onScroll: function onScroll(scroll) { this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount); if (this.props.onScroll) { this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft }); } }, setScrollLeft: function setScrollLeft(scrollLeft) { this.refs.canvas.setScrollLeft(scrollLeft); } }); module.exports = Viewport; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var PropTypes = React.PropTypes; var cloneWithProps = __webpack_require__(29); var shallowEqual = __webpack_require__(27); var emptyFunction = __webpack_require__(36); var ScrollShim = __webpack_require__(49); var Row = __webpack_require__(50); var ExcelColumn = __webpack_require__(41); var Canvas = React.createClass({ displayName: 'Canvas', mixins: [ScrollShim], propTypes: { rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), rowHeight: PropTypes.number.isRequired, height: PropTypes.number.isRequired, displayStart: PropTypes.number.isRequired, displayEnd: PropTypes.number.isRequired, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]), onRows: PropTypes.func, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired }, render: function render() { var _this = this; var displayStart = this.state.displayStart; var displayEnd = this.state.displayEnd; var rowHeight = this.props.rowHeight; var length = this.props.rowsCount; var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) { return _this.renderRow({ key: displayStart + idx, ref: idx, idx: displayStart + idx, row: row, height: rowHeight, columns: _this.props.columns, isSelected: _this.isRowSelected(displayStart + idx), expandedRows: _this.props.expandedRows, cellMetaData: _this.props.cellMetaData }); }); this._currentRowsLength = rows.length; if (displayStart > 0) { rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight)); } if (length - displayEnd > 0) { rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight)); } var style = { position: 'absolute', top: 0, left: 0, overflowX: 'auto', overflowY: 'scroll', width: this.props.totalWidth + this.state.scrollbarWidth, height: this.props.height, transform: 'translate3d(0, 0, 0)' }; return React.createElement( 'div', { style: style, onScroll: this.onScroll, className: joinClasses("react-grid-Canvas", this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) }, React.createElement( 'div', { style: { width: this.props.width, overflow: 'hidden' } }, rows ) ); }, renderRow: function renderRow(props) { var RowsRenderer = this.props.rowRenderer; if (typeof RowsRenderer === 'function') { return React.createElement(RowsRenderer, props); } else if (React.isValidElement(this.props.rowRenderer)) { return cloneWithProps(this.props.rowRenderer, props); } }, renderPlaceholder: function renderPlaceholder(key, height) { return React.createElement( 'div', { key: key, style: { height: height } }, this.props.columns.map(function (column, idx) { return React.createElement('div', { style: { width: column.width }, key: idx }); }) ); }, getDefaultProps: function getDefaultProps() { return { rowRenderer: Row, onRows: emptyFunction }; }, isRowSelected: function isRowSelected(rowIdx) { return this.props.selectedRows && this.props.selectedRows[rowIdx] === true; }, _currentRowsLength: 0, _currentRowsRange: { start: 0, end: 0 }, _scroll: { scrollTop: 0, scrollLeft: 0 }, getInitialState: function getInitialState() { return { shouldUpdate: true, displayStart: this.props.displayStart, displayEnd: this.props.displayEnd, scrollbarWidth: 0 }; }, componentWillMount: function componentWillMount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidMount: function componentDidMount() { this.onRows(); }, componentDidUpdate: function componentDidUpdate(nextProps) { if (this._scroll !== { start: 0, end: 0 }) { this.setScrollLeft(this._scroll.scrollLeft); } this.onRows(); }, componentWillUnmount: function componentWillUnmount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount > this.props.rowsCount) { React.findDOMNode(this).scrollTop = nextProps.rowsCount * this.props.rowHeight; } var scrollbarWidth = this.getScrollbarWidth(); var shouldUpdate = !(nextProps.visibleStart > this.state.displayStart && nextProps.visibleEnd < this.state.displayEnd) || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !shallowEqual(nextProps.style, this.props.style); if (shouldUpdate) { this.setState({ shouldUpdate: true, displayStart: nextProps.displayStart, displayEnd: nextProps.displayEnd, scrollbarWidth: scrollbarWidth }); } else { this.setState({ shouldUpdate: false, scrollbarWidth: scrollbarWidth }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !nextState || nextState.shouldUpdate; }, onRows: function onRows() { if (this._currentRowsRange !== { start: 0, end: 0 }) { this.props.onRows(this._currentRowsRange); this._currentRowsRange = { start: 0, end: 0 }; } }, getRows: function getRows(displayStart, displayEnd) { this._currentRowsRange = { start: displayStart, end: displayEnd }; if (Array.isArray(this.props.rowGetter)) { return this.props.rowGetter.slice(displayStart, displayEnd); } else { var rows = []; for (var i = displayStart; i < displayEnd; i++) { rows.push(this.props.rowGetter(i)); } return rows; } }, getScrollbarWidth: function getScrollbarWidth() { var scrollbarWidth = 0; // Get the scrollbar width var canvas = this.getDOMNode(); scrollbarWidth = canvas.offsetWidth - canvas.clientWidth; return scrollbarWidth; }, setScrollLeft: function setScrollLeft(scrollLeft) { if (this._currentRowsLength !== 0) { if (!this.refs) return; for (var i = 0, len = this._currentRowsLength; i < len; i++) { if (this.refs[i] && this.refs[i].setScrollLeft) { this.refs[i].setScrollLeft(scrollLeft); } } } }, getScroll: function getScroll() { var _React$findDOMNode = React.findDOMNode(this); var scrollTop = _React$findDOMNode.scrollTop; var scrollLeft = _React$findDOMNode.scrollLeft; return { scrollTop: scrollTop, scrollLeft: scrollLeft }; }, onScroll: function onScroll(e) { this.appendScrollShim(); var _e$target = e.target; var scrollTop = _e$target.scrollTop; var scrollLeft = _e$target.scrollLeft; var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft }; this._scroll = scroll; this.props.onScroll(scroll); } }); module.exports = Canvas; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixin not compatible and HTMLElement classList */ /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var ScrollShim = { appendScrollShim: function appendScrollShim() { if (!this._scrollShim) { var size = this._scrollShimSize(); var shim = document.createElement('div'); if (shim.classList) { shim.classList.add('react-grid-ScrollShim'); //flow - not compatible with HTMLElement } else { shim.className += ' react-grid-ScrollShim'; } shim.style.position = 'absolute'; shim.style.top = 0; shim.style.left = 0; shim.style.width = size.width + 'px'; shim.style.height = size.height + 'px'; React.findDOMNode(this).appendChild(shim); this._scrollShim = shim; } this._scheduleRemoveScrollShim(); }, _scrollShimSize: function _scrollShimSize() { return { width: this.props.width, height: this.props.length * this.props.rowHeight }; }, _scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() { if (this._scheduleRemoveScrollShimTimer) { clearTimeout(this._scheduleRemoveScrollShimTimer); } this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200); }, _removeScrollShim: function _removeScrollShim() { if (this._scrollShim) { this._scrollShim.parentNode.removeChild(this._scrollShim); this._scrollShim = undefined; } } }; module.exports = ScrollShim; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var Cell = __webpack_require__(51); var ColumnMetrics = __webpack_require__(23); var ColumnUtilsMixin = __webpack_require__(25); var Row = React.createClass({ displayName: 'Row', propTypes: { height: React.PropTypes.number.isRequired, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, row: React.PropTypes.object.isRequired, cellRenderer: React.PropTypes.func, isSelected: React.PropTypes.bool, idx: React.PropTypes.number.isRequired, expandedRows: React.PropTypes.arrayOf(React.PropTypes.object) }, mixins: [ColumnUtilsMixin], render: function render() { var className = joinClasses('react-grid-Row', "react-grid-Row--${this.props.idx % 2 === 0 ? 'even' : 'odd'}"); var style = { height: this.getRowHeight(this.props), overflow: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }), React.isValidElement(this.props.row) ? this.props.row : cells ); }, getCells: function getCells() { var _this = this; var cells = []; var lockedCells = []; var selectedColumn = this.getSelectedColumn(); this.props.columns.forEach(function (column, i) { var CellRenderer = _this.props.cellRenderer; var cell = React.createElement(CellRenderer, { ref: i, key: i, idx: i, rowIdx: _this.props.idx, value: _this.getCellValue(column.key || i), column: column, height: _this.getRowHeight(), formatter: column.formatter, cellMetaData: _this.props.cellMetaData, rowData: _this.props.row, selectedColumn: selectedColumn, isRowSelected: _this.props.isSelected }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } }); return cells.concat(lockedCells); }, getRowHeight: function getRowHeight() { var rows = this.props.expandedRows || null; if (rows && this.props.key) { var row = rows[this.props.key] || null; if (row) { return row.height; } } return this.props.height; }, getCellValue: function getCellValue(key) { var val; if (key === 'select-row') { return this.props.isSelected; } else if (typeof this.props.row.get === 'function') { val = this.props.row.get(key); } else { val = this.props.row[key]; } return val; }, renderCell: function renderCell(props) { if (typeof this.props.cellRenderer == 'function') { this.props.cellRenderer.call(this, props); } if (React.isValidElement(this.props.cellRenderer)) { return cloneWithProps(this.props.cellRenderer, props); } else { return this.props.cellRenderer(props); } }, getDefaultProps: function getDefaultProps() { return { cellRenderer: Cell, isSelected: false, height: 35 }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this2 = this; this.props.columns.forEach(function (column, i) { if (column.locked) { if (!_this2.refs[i]) return; _this2.refs[i].setScrollLeft(scrollLeft); } }); }, doesRowContainSelectedCell: function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } else { return false; } }, willRowBeDraggedOver: function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); }, hasRowBeenCopied: function hasRowBeenCopied() { var copied = this.props.cellMetaData.copied; return copied != null && copied.rowIdx === this.props.idx; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height; }, handleDragEnter: function handleDragEnter() { var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow; if (handleDragEnterRow) { handleDragEnterRow(this.props.idx); } }, getSelectedColumn: function getSelectedColumn() { var selected = this.props.cellMetaData.selected; if (selected && selected.idx) { return this.getColumn(this.props.columns, selected.idx); } } }); module.exports = Row; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(2)['default']; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var cloneWithProps = __webpack_require__(29); var EditorContainer = __webpack_require__(52); var ExcelColumn = __webpack_require__(41); var isFunction = __webpack_require__(76); var CellMetaDataShape = __webpack_require__(77); var Cell = React.createClass({ displayName: 'Cell', propTypes: { rowIdx: React.PropTypes.number.isRequired, idx: React.PropTypes.number.isRequired, selected: React.PropTypes.shape({ idx: React.PropTypes.number.isRequired }), tabIndex: React.PropTypes.number, ref: React.PropTypes.string, column: React.PropTypes.shape(ExcelColumn).isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, isExpanded: React.PropTypes.bool, cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired, handleDragStart: React.PropTypes.func, className: React.PropTypes.string, rowData: React.PropTypes.object.isRequired }, getDefaultProps: function getDefaultProps() { return { tabIndex: -1, ref: "cell", isExpanded: false }; }, getInitialState: function getInitialState() { return { isRowChanging: false, isCellValueChanging: false }; }, componentDidMount: function componentDidMount() { this.checkFocus(); }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { this.checkFocus(); var dragged = this.props.cellMetaData.dragged; if (dragged && dragged.complete === true) { this.props.cellMetaData.handleTerminateDrag(); } if (this.state.isRowChanging && this.props.selectedColumn != null) { this.applyUpdateClass(); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected(); }, getStyle: function getStyle() { var style = { position: 'absolute', width: this.props.column.width, height: this.props.height, left: this.props.column.left }; return style; }, render: function render() { var style = this.getStyle(); var className = this.getCellClass(); var cellContent = this.renderCellContent({ value: this.props.value, column: this.props.column, rowIdx: this.props.rowIdx, isExpanded: this.props.isExpanded }); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick }), cellContent, React.createElement('div', { className: 'drag-handle', draggable: 'true' }) ); }, renderCellContent: function renderCellContent(props) { var CellContent; var Formatter = this.getFormatter(); if (React.isValidElement(Formatter)) { props.dependentValues = this.getFormatterDependencies(); CellContent = cloneWithProps(Formatter, props); } else if (isFunction(Formatter)) { CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() }); } else { CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value }); } return React.createElement( 'div', { ref: 'cell', className: 'react-grid-Cell__value' }, CellContent, ' ', this.props.cellControls ); }, isColumnSelected: function isColumnSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.idx === this.props.idx; }, isSelected: function isSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx; }, isActive: function isActive() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return this.isSelected() && meta.selected.active === true; }, isCellSelectionChanging: function isCellSelectionChanging(nextProps) { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } var nextSelected = nextProps.cellMetaData.selected; if (meta.selected && nextSelected) { return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx; } else { return true; } }, getFormatter: function getFormatter() { var col = this.props.column; if (this.isActive()) { return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height }); } else { return this.props.column.formatter; } }, getRowData: function getRowData() { return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData; }, getFormatterDependencies: function getFormatterDependencies() { //clone row data so editor cannot actually change this var columnName = this.props.column.ItemId; //convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.getRowData(), this.props.column); } }, onCellClick: function onCellClick(e) { var meta = this.props.cellMetaData; if (meta != null && meta.onCellClick != null) { meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onCellDoubleClick: function onCellDoubleClick(e) { var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, checkFocus: function checkFocus() { if (this.isSelected() && !this.isActive()) { React.findDOMNode(this).focus(); } }, getCellClass: function getCellClass() { var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null); var extraClasses = joinClasses({ 'selected': this.isSelected() && !this.isActive(), 'editing': this.isActive(), 'copied': this.isCopied(), 'active-drag-cell': this.isSelected() || this.isDraggedOver(), 'is-dragged-over-up': this.isDraggedOverUpwards(), 'is-dragged-over-down': this.isDraggedOverDownwards(), 'was-dragged-over': this.wasDraggedOver() }); return joinClasses(className, extraClasses); }, getUpdateCellClass: function getUpdateCellClass() { return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : ''; }, applyUpdateClass: function applyUpdateClass() { var updateCellClass = this.getUpdateCellClass(); // -> removing the class if (updateCellClass != null && updateCellClass != "") { var cellDOMNode = this.getDOMNode(); if (cellDOMNode.classList) { cellDOMNode.classList.remove(updateCellClass); // -> and re-adding the class cellDOMNode.classList.add(updateCellClass); } else if (cellDOMNode.className.indexOf(updateCellClass) === -1) { // IE9 doesn't support classList, nor (I think) altering element.className // without replacing it wholesale. cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass; } } }, setScrollLeft: function setScrollLeft(scrollLeft) { var ctrl = this; //flow on windows has an outdated react declaration, once that gets updated, we can remove this if (ctrl.isMounted()) { var node = React.findDOMNode(this); var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.webkitTransform = transform; node.style.transform = transform; } }, isCopied: function isCopied() { var copied = this.props.cellMetaData.copied; return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx; }, isDraggedOver: function isDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx; }, wasDraggedOver: function wasDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx; }, isDraggedCellChanging: function isDraggedCellChanging(nextProps) { var isChanging; var dragged = this.props.cellMetaData.dragged; var nextDragged = nextProps.cellMetaData.dragged; if (dragged) { isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx; return isChanging; } else { return false; } }, isCopyCellChanging: function isCopyCellChanging(nextProps) { var isChanging; var copied = this.props.cellMetaData.copied; var nextCopied = nextProps.cellMetaData.copied; if (copied) { isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx; return isChanging; } else { return false; } }, isDraggedOverUpwards: function isDraggedOverUpwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx; }, isDraggedOverDownwards: function isDraggedOverDownwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx; } }); var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, render: function render() { return React.createElement( 'span', null, this.props.value ); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return nextProps.value !== this.props.value; } }); module.exports = Cell; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var joinClasses = __webpack_require__(21); var keyboardHandlerMixin = __webpack_require__(53); var SimpleTextEditor = __webpack_require__(54); var isFunction = __webpack_require__(76); var cloneWithProps = __webpack_require__(29); var EditorContainer = React.createClass({ displayName: 'EditorContainer', mixins: [keyboardHandlerMixin], propTypes: { rowData: React.PropTypes.object.isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, cellMetaData: React.PropTypes.shape({ selected: React.PropTypes.object.isRequired, copied: React.PropTypes.object, dragged: React.PropTypes.object, onCellClick: React.PropTypes.func, onCellDoubleClick: React.PropTypes.func }).isRequired, column: React.PropTypes.object.isRequired, height: React.PropTypes.number.isRequired }, changeCommitted: false, getInitialState: function getInitialState() { return { isInvalid: false }; }, componentDidMount: function componentDidMount() { var inputNode = this.getInputNode(); if (inputNode !== undefined) { this.setTextInputFocus(); if (!this.getEditor().disableContainerStyles) { inputNode.className += ' editor-main'; inputNode.style.height = this.props.height - 1 + 'px'; } } }, createEditor: function createEditor() { var _this = this; var editorRef = function editorRef(c) { return _this.editor = c; }; var editorProps = { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onCommit: this.commit, rowMetaData: this.getRowMetaData(), height: this.props.height, onBlur: this.commit, onOverrideKeyDown: this.onKeyDown }; var customEditor = this.props.column.editor; if (customEditor && React.isValidElement(customEditor)) { //return custom column editor or SimpleEditor if none specified return cloneWithProps(customEditor, editorProps); } else { return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, onKeyDown: this.onKeyDown, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData() }); } }, getRowMetaData: function getRowMetaData() { //clone row data so editor cannot actually change this var columnName = this.props.column.ItemId; //convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.props.rowData, this.props.column); } }, onPressEnter: function onPressEnter(e) { this.commit({ key: 'Enter' }); }, onPressTab: function onPressTab(e) { this.commit({ key: 'Tab' }); }, onPressEscape: function onPressEscape(e) { if (!this.editorIsSelectOpen()) { this.props.cellMetaData.onCommitCancel(); } else { // prevent event from bubbling if editor has results to select e.stopPropagation(); } }, onPressArrowDown: function onPressArrowDown(e) { if (this.editorHasResults()) { //dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowUp: function onPressArrowUp(e) { if (this.editorHasResults()) { //dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowLeft: function onPressArrowLeft(e) { //prevent event propogation. this disables left cell navigation if (!this.isCaretAtBeginningOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, onPressArrowRight: function onPressArrowRight(e) { //prevent event propogation. this disables right cell navigation if (!this.isCaretAtEndOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, editorHasResults: function editorHasResults() { if (isFunction(this.getEditor().hasResults)) { return this.getEditor().hasResults(); } else { return false; } }, editorIsSelectOpen: function editorIsSelectOpen() { if (isFunction(this.getEditor().isSelectOpen)) { return this.getEditor().isSelectOpen(); } else { return false; } }, getEditor: function getEditor() { return this.editor; }, commit: function commit(args) { var opts = args || {}; var updated = this.getEditor().getValue(); if (this.isNewValueValid(updated)) { var cellKey = this.props.column.key; this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key }); } this.changeCommitted = true; }, isNewValueValid: function isNewValueValid(value) { if (isFunction(this.getEditor().validate)) { var isValid = this.getEditor().validate(value); this.setState({ isInvalid: !isValid }); return isValid; } else { return true; } }, getInputNode: function getInputNode() { return this.getEditor().getInputNode(); }, getInitialValue: function getInitialValue() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; if (keyCode === 'Delete' || keyCode === 'Backspace') { return ''; } else if (keyCode === 'Enter') { return this.props.value; } else { var text = keyCode ? String.fromCharCode(keyCode) : this.props.value; return text; } }, getContainerClass: function getContainerClass() { return joinClasses({ 'has-error': this.state.isInvalid === true }); }, renderStatusIcon: function renderStatusIcon() { if (this.state.isInvalid === true) { return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' }); } }, render: function render() { return React.createElement( 'div', { className: this.getContainerClass(), onKeyDown: this.onKeyDown }, this.createEditor(), this.renderStatusIcon() ); }, setCaretAtEndOfInput: function setCaretAtEndOfInput() { var input = this.getInputNode(); //taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element var txtLength = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(txtLength, txtLength); } else if (input.createTextRange) { var fieldRange = input.createTextRange(); fieldRange.moveStart('character', txtLength); fieldRange.collapse(); fieldRange.select(); } }, isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0; }, isCaretAtEndOfInput: function isCaretAtEndOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.value.length; }, setTextInputFocus: function setTextInputFocus() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; var inputNode = this.getInputNode(); inputNode.focus(); if (inputNode.tagName === "INPUT") { if (!this.isKeyPrintable(keyCode)) { inputNode.focus(); inputNode.select(); } else { inputNode.select(); } } }, componentWillUnmount: function componentWillUnmount() { if (!this.changeCommitted && !this.hasEscapeBeenPressed()) { this.commit({ key: 'Enter' }); } }, hasEscapeBeenPressed: function hasEscapeBeenPressed() { var pressed = false; var escapeKey = 27; if (window.event) { if (window.event.keyCode === escapeKey) { pressed = true; } else if (window.event.which === escapeKey) { pressed = true; } } return pressed; } }); module.exports = EditorContainer; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /* TODO: mixins */ /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var KeyboardHandlerMixin = { onKeyDown: function onKeyDown(e) { if (this.isCtrlKeyHeldDown(e)) { this.checkAndCall('onPressKeyWithCtrl', e); } else if (this.isKeyExplicitlyHandled(e.key)) { //break up individual keyPress events to have their own specific callbacks //this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing var callBack = 'onPress' + e.key; this.checkAndCall(callBack, e); } else if (this.isKeyPrintable(e.keyCode)) { this.checkAndCall('onPressChar', e); } }, //taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character isKeyPrintable: function isKeyPrintable(keycode) { var valid = keycode > 47 && keycode < 58 || // number keys keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) keycode > 64 && keycode < 91 || // letter keys keycode > 95 && keycode < 112 || // numpad keys keycode > 185 && keycode < 193 || // ;=,-./` (in order) keycode > 218 && keycode < 223; // [\]' (in order) return valid; }, isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) { return typeof this['onPress' + key] === 'function'; }, isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) { return e.ctrlKey === true && e.key !== "Control"; }, checkAndCall: function checkAndCall(methodName, args) { if (typeof this[methodName] === 'function') { this[methodName](args); } } }; module.exports = KeyboardHandlerMixin; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _get = __webpack_require__(55)['default']; var _inherits = __webpack_require__(61)['default']; var _createClass = __webpack_require__(72)['default']; var _classCallCheck = __webpack_require__(42)['default']; var React = __webpack_require__(18); var keyboardHandlerMixin = __webpack_require__(53); var ExcelColumn = __webpack_require__(41); var EditorBase = __webpack_require__(75); var SimpleTextEditor = (function (_EditorBase) { _inherits(SimpleTextEditor, _EditorBase); function SimpleTextEditor() { _classCallCheck(this, SimpleTextEditor); _get(Object.getPrototypeOf(SimpleTextEditor.prototype), 'constructor', this).apply(this, arguments); } _createClass(SimpleTextEditor, [{ key: 'render', value: function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value, onKeyDown: this.props.onKeyDown }); } }]); return SimpleTextEditor; })(EditorBase); ; module.exports = SimpleTextEditor; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$getOwnPropertyDescriptor = __webpack_require__(56)["default"]; exports["default"] = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = _Object$getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; exports.__esModule = true; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(57), __esModule: true }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(15); __webpack_require__(58); module.exports = function getOwnPropertyDescriptor(it, key){ return $.getDesc(it, key); }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(59); __webpack_require__(60)('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(12) , defined = __webpack_require__(11); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives module.exports = function(KEY, exec){ var $def = __webpack_require__(6) , fn = (__webpack_require__(8).Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $def($def.S + $def.F * __webpack_require__(17)(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$create = __webpack_require__(62)["default"]; var _Object$setPrototypeOf = __webpack_require__(64)["default"]; exports["default"] = function (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; }; exports.__esModule = true; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(63), __esModule: true }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(15); module.exports = function create(P, D){ return $.create(P, D); }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(65), __esModule: true }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(66); module.exports = __webpack_require__(8).Object.setPrototypeOf; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = __webpack_require__(6); $def($def.S, 'Object', {setPrototypeOf: __webpack_require__(67).set}); /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var getDesc = __webpack_require__(15).getDesc , isObject = __webpack_require__(68) , anObject = __webpack_require__(69); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line no-proto function(test, buggy, set){ try { set = __webpack_require__(70)(Function.call, getDesc(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 68 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(68); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(71); module.exports = function(fn, that, length){ aFunction(fn); if(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); }; }; /***/ }, /* 71 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$defineProperty = __webpack_require__(73)["default"]; exports["default"] = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; _Object$defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports.__esModule = true; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(74), __esModule: true }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(15); module.exports = function defineProperty(it, key, desc){ return $.setDesc(it, key, desc); }; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _get = __webpack_require__(55)['default']; var _inherits = __webpack_require__(61)['default']; var _createClass = __webpack_require__(72)['default']; var _classCallCheck = __webpack_require__(42)['default']; var React = __webpack_require__(18); var keyboardHandlerMixin = __webpack_require__(53); var ExcelColumn = __webpack_require__(41); var EditorBase = (function (_React$Component) { _inherits(EditorBase, _React$Component); function EditorBase() { _classCallCheck(this, EditorBase); _get(Object.getPrototypeOf(EditorBase.prototype), 'constructor', this).apply(this, arguments); } _createClass(EditorBase, [{ key: 'getStyle', value: function getStyle() { return { width: '100%' }; } }, { key: 'getValue', value: function getValue() { var updated = {}; updated[this.props.column.key] = this.getInputNode().value; return updated; } }, { key: 'getInputNode', value: function getInputNode() { var domNode = React.findDOMNode(this); if (domNode.tagName === 'INPUT') { return domNode; } else { return domNode.querySelector("input:not([type=hidden])"); } } }, { key: 'inheritContainerStyles', value: function inheritContainerStyles() { return true; } }]); return EditorBase; })(React.Component); EditorBase.propTypes = { onKeyDown: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired, commit: React.PropTypes.func.isRequired }; module.exports = EditorBase; /***/ }, /* 76 */ /***/ function(module, exports) { "use strict"; var isFunction = function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; module.exports = isFunction; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var PropTypes = __webpack_require__(18).PropTypes; module.exports = { selected: PropTypes.object.isRequired, copied: PropTypes.object, dragged: PropTypes.object, onCellClick: PropTypes.func.isRequired }; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixins */ 'use strict'; var React = __webpack_require__(18); var DOMMetrics = __webpack_require__(79); var getWindowSize = __webpack_require__(80); var PropTypes = React.PropTypes; var min = Math.min; var max = Math.max; var floor = Math.floor; var ceil = Math.ceil; module.exports = { mixins: [DOMMetrics.MetricsMixin], DOMMetrics: { viewportHeight: function viewportHeight() { return React.findDOMNode(this).offsetHeight; } }, propTypes: { rowHeight: React.PropTypes.number, rowsCount: React.PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() { return { rowHeight: 30 }; }, getInitialState: function getInitialState() { return this.getGridState(this.props); }, getGridState: function getGridState(props) { var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight); var totalRowCount = min(renderedRowsCount * 2, props.rowsCount); return { displayStart: 0, displayEnd: totalRowCount, height: props.minHeight, scrollTop: 0, scrollLeft: 0 }; }, updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) { var renderedRowsCount = ceil(height / rowHeight); var visibleStart = floor(scrollTop / rowHeight); var visibleEnd = min(visibleStart + renderedRowsCount, length); var displayStart = max(0, visibleStart - renderedRowsCount * 2); var displayEnd = min(visibleStart + renderedRowsCount * 2, length); var nextScrollState = { visibleStart: visibleStart, visibleEnd: visibleEnd, displayStart: displayStart, displayEnd: displayEnd, height: height, scrollTop: scrollTop, scrollLeft: scrollLeft }; this.setState(nextScrollState); }, metricsUpdated: function metricsUpdated() { var height = this.DOMMetrics.viewportHeight(); if (height) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.rowHeight !== nextProps.rowHeight) { this.setState(this.getGridState(nextProps)); } else if (this.props.rowsCount !== nextProps.rowsCount) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount); } } }; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixin and invarient splat */ /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var emptyFunction = __webpack_require__(36); var shallowCloneObject = __webpack_require__(22); var contextTypes = { metricsComputator: React.PropTypes.object }; var MetricsComputatorMixin = { childContextTypes: contextTypes, getChildContext: function getChildContext() { return { metricsComputator: this }; }, getMetricImpl: function getMetricImpl(name) { return this._DOMMetrics.metrics[name].value; }, registerMetricsImpl: function registerMetricsImpl(component, metrics) { var getters = {}; var s = this._DOMMetrics; for (var name in metrics) { if (s.metrics[name] !== undefined) { throw new Error('DOM metric ' + name + ' is already defined'); } s.metrics[name] = { component: component, computator: metrics[name].bind(component) }; getters[name] = this.getMetricImpl.bind(null, name); } if (s.components.indexOf(component) === -1) { s.components.push(component); } return getters; }, unregisterMetricsFor: function unregisterMetricsFor(component) { var s = this._DOMMetrics; var idx = s.components.indexOf(component); if (idx > -1) { s.components.splice(idx, 1); var name; var metricsToDelete = {}; for (name in s.metrics) { if (s.metrics[name].component === component) { metricsToDelete[name] = true; } } for (name in metricsToDelete) { delete s.metrics[name]; } } }, updateMetrics: function updateMetrics() { var s = this._DOMMetrics; var needUpdate = false; for (var name in s.metrics) { var newMetric = s.metrics[name].computator(); if (newMetric !== s.metrics[name].value) { needUpdate = true; } s.metrics[name].value = newMetric; } if (needUpdate) { for (var i = 0, len = s.components.length; i < len; i++) { if (s.components[i].metricsUpdated) { s.components[i].metricsUpdated(); } } } }, componentWillMount: function componentWillMount() { this._DOMMetrics = { metrics: {}, components: [] }; }, componentDidMount: function componentDidMount() { if (window.addEventListener) { window.addEventListener('resize', this.updateMetrics); } else { window.attachEvent('resize', this.updateMetrics); } this.updateMetrics(); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.updateMetrics); } }; var MetricsMixin = { contextTypes: contextTypes, componentWillMount: function componentWillMount() { if (this.DOMMetrics) { this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics); this.DOMMetrics = {}; for (var name in this._DOMMetricsDefs) { this.DOMMetrics[name] = emptyFunction; } } }, componentDidMount: function componentDidMount() { if (this.DOMMetrics) { this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs); } }, componentWillUnmount: function componentWillUnmount() { if (!this.registerMetricsImpl) { return this.context.metricsComputator.unregisterMetricsFor(this); } if (this.hasOwnProperty('DOMMetrics')) { delete this.DOMMetrics; } }, registerMetrics: function registerMetrics(metrics) { if (this.registerMetricsImpl) { return this.registerMetricsImpl(this, metrics); } else { return this.context.metricsComputator.registerMetricsImpl(this, metrics); } }, getMetric: function getMetric(name) { if (this.getMetricImpl) { return this.getMetricImpl(name); } else { return this.context.metricsComputator.getMetricImpl(name); } } }; module.exports = { MetricsComputatorMixin: MetricsComputatorMixin, MetricsMixin: MetricsMixin }; /***/ }, /* 80 */ /***/ function(module, exports) { /** * @jsx React.DOM */ 'use strict'; /** * Return window's height and width * * @return {Object} height and width of the window */ function getWindowSize() { var width = window.innerWidth; var height = window.innerHeight; if (!width || !height) { width = document.documentElement.clientWidth; height = document.documentElement.clientHeight; } if (!width || !height) { width = document.body.clientWidth; height = document.body.clientHeight; } return { width: width, height: height }; } module.exports = getWindowSize; /***/ }, /* 81 */ /***/ function(module, exports) { /* TODO mixins */ "use strict"; module.exports = { componentDidMount: function componentDidMount() { this._scrollLeft = this.refs.viewport.getScroll().scrollLeft; this._onScroll(); }, componentDidUpdate: function componentDidUpdate() { this._onScroll(); }, componentWillMount: function componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount: function componentWillUnmount() { this._scrollLeft = undefined; }, onScroll: function onScroll(props) { if (this._scrollLeft !== props.scrollLeft) { this._scrollLeft = props.scrollLeft; this._onScroll(); } }, _onScroll: function _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); this.refs.viewport.setScrollLeft(this._scrollLeft); } } }; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var CheckboxEditor = React.createClass({ displayName: 'CheckboxEditor', PropTypes: { value: React.PropTypes.bool.isRequired, rowIdx: React.PropTypes.number.isRequired, column: React.PropTypes.shape({ key: React.PropTypes.string.isRequired, onCellChange: React.PropTypes.func.isRequired }).isRequired }, render: function render() { var checked = this.props.value != null ? this.props.value : false; return React.createElement('input', { className: 'react-grid-CheckBox', type: 'checkbox', checked: checked, onClick: this.handleChange }); }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, e); } }); module.exports = CheckboxEditor; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(18); var ExcelColumn = __webpack_require__(41); var FilterableHeaderCell = React.createClass({ displayName: 'FilterableHeaderCell', propTypes: { onChange: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired }, getInitialState: function getInitialState() { return { filterTerm: '' }; }, handleChange: function handleChange(e) { var val = e.target.value; this.setState({ filterTerm: val }); this.props.onChange({ filterTerm: val, columnKey: this.props.column.key }); }, componentDidUpdate: function componentDidUpdate(nextProps) { var ele = React.findDOMNode(this); if (ele) ele.focus(); }, render: function render() { return React.createElement( 'div', null, React.createElement( 'div', { className: 'form-group' }, React.createElement(this.renderInput, null) ) ); }, renderInput: function renderInput() { if (this.props.column.filterable === false) { return React.createElement('span', null); } else { return React.createElement('input', { type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange }); } } }); module.exports = FilterableHeaderCell; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixins */ 'use strict'; var _classCallCheck = __webpack_require__(42)['default']; var ColumnMetrics = __webpack_require__(23); var DOMMetrics = __webpack_require__(79); Object.assign = __webpack_require__(85); var PropTypes = __webpack_require__(18).PropTypes; var ColumnUtils = __webpack_require__(25); var React = __webpack_require__(18); var Column = function Column() { _classCallCheck(this, Column); }; ; module.exports = { mixins: [DOMMetrics.MetricsMixin], propTypes: { columns: PropTypes.arrayOf(Column), minColumnWidth: PropTypes.number, columnEquality: PropTypes.func }, DOMMetrics: { gridWidth: function gridWidth() { return React.findDOMNode(this).offsetWidth - 2; } }, getDefaultProps: function getDefaultProps() { return { minColumnWidth: 80, columnEquality: ColumnMetrics.sameColumn }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.columns) { if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality)) { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); } } }, getTotalWidth: function getTotalWidth() { var totalWidth = 0; if (this.isMounted()) { totalWidth = this.DOMMetrics.gridWidth(); } else { totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth; } return totalWidth; }, getColumnMetricsType: function getColumnMetricsType(metrics) { var totalWidth = this.getTotalWidth(); var currentMetrics = { columns: metrics.columns, totalWidth: totalWidth, minColumnWidth: metrics.minColumnWidth }; var updatedMetrics = ColumnMetrics.recalculate(currentMetrics); return updatedMetrics; }, getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, getSize: function getSize() { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, metricsUpdated: function metricsUpdated() { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); }, createColumnMetrics: function createColumnMetrics(initialRun) { var gridColumns = this.setupGridColumns(); return this.getColumnMetricsType({ columns: gridColumns, minColumnWidth: this.props.minColumnWidth }, initialRun); }, onColumnResize: function onColumnResize(index, width) { var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width); this.setState({ columnMetrics: columnMetrics }); } }; /***/ }, /* 85 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 86 */ /***/ function(module, exports) { 'use strict'; var RowUtils = { get: function get(row, property) { if (typeof row.get === 'function') { return row.get(property); } else { return row[property]; } } }; module.exports = RowUtils; /***/ } /******/ ]) }); ;
index.js
caesai/sushka-chat
import React from 'react'; import { render } from 'react-dom' import Chat from './App'; import { Provider } from 'react-redux'; import store from './store/store'; import * as style from './scss/main.scss'; console.log(store.getState()); let unsubscribe = store.subscribe(() => console.log(store.getState()) ); render( <Provider store={store}> <Chat/> </Provider>, document.getElementById('Chat') );
ui/src/js/profile/edit/FileChooseAndUploadButton.js
Dica-Developer/weplantaforest
import counterpart from 'counterpart'; import React, { Component } from 'react'; import FileUploadProgress from 'react-fileupload-progress'; import IconButton from '../../common/components/IconButton'; import { createProfileImageUrl } from '../../common/ImageHelper'; import Notification from '../../common/components/Notification'; export default class FileChooseAndUploadButton extends Component { constructor(props) { super(props); this.state = { fileName: '', fileWarning: '', }; this.styles = { progressWrapper: { height: '15px', marginTop: '10px', width: '100%', float: 'left', overflow: 'hidden', backgroundColor: '#f5f5f5', borderRadius: '4px', WebkitBoxShadow: 'inset 0 1px 2px rgba(0,0,0,.1)', boxShadow: 'inset 0 1px 2px rgba(0,0,0,.1)', }, progressBar: { float: 'left', height: '100%', textAlign: 'center', backgroundColor: '#82AB1f', WebkitBoxShadow: 'inset 0 -1px 0 rgba(0,0,0,.15)', boxShadow: 'inset 0 -1px 0 rgba(0,0,0,.15)', WebkitTransition: 'width .6s ease', Otransition: 'width .6s ease', transition: 'width .6s ease', }, }; } componentDidMount() { this.loadImage(this.props.imageFileName); } beforeSend(req) { req.setRequestHeader('X-AUTH-TOKEN', localStorage.getItem('jwt')); return req; } formGetter() { let data = new FormData(document.getElementById('userIamgeForm')); data.append('userName', localStorage.getItem('username')); return data; } customFormRenderer(onSubmit) { let uploadButton; if (this.state.fileName != '') { uploadButton = <IconButton text="Upload" glyphIcon="glyphicon-upload" onClick={onSubmit} />; } else { uploadButton = ''; } return ( <form id="userIamgeForm" className="file-choser-form"> <label className="fileContainer"> <span className="glyphicon glyphicon-search" aria-hidden="true"></span> {counterpart.translate('CHOOSE_FILE')} <input type="file" name="file" id="exampleInputFile" ref="fileChooser" onChange={(e) => this.fileChanged(e.target.files)} accept="image/png, image/jpeg" /> </label> <div> <label className="file-name">{this.state.fileName}</label> <label className="file-error">{this.state.fileWarning}</label> {uploadButton} </div> </form> ); } customProgressRenderer(progress, hasError, cancelHandler) { if (hasError || progress > -1) { let barStyle = Object.assign({}, this.styles.progressBar); barStyle.width = progress + '%'; let message = <span>{barStyle.width}</span>; if (progress === 100 && !hasError) { message = <span>{counterpart.translate('UPLOAD_FINISHED')}</span>; } return ( <div> <div style={this.styles.progressWrapper}> <div style={barStyle}></div> </div> <div style={{ clear: 'left' }}>{message}</div> </div> ); } else { return; } } fileChanged(files) { let acceptedTypes = ['image/png', 'image/jpeg']; if (files && files.length > 0) { if (files[0].size > 1048576) { this.setState({ fileName: '', fileWarning: counterpart.translate('FILE_TOO_BIG'), }); } else if (!acceptedTypes.includes(files[0].type)) { this.setState({ fileName: '', fileWarning: counterpart.translate('WRONG_IMAGE_TYPE'), }); } else { this.setState({ fileName: files[0].name, fileWarning: '', }); } } } loadImage(imageName) { const component = this; const img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function () { var canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; var ctx = canvas.getContext('2d'); ctx.drawImage(this, 0, 0); var dataURL = canvas.toDataURL(); component.setState({ liveImage: dataURL, }); }; img.src = createProfileImageUrl(imageName, 80, 80); this.setState({ loadingImage: img, }); this.props.updateImageName(imageName); } render() { let image; if (this.props.imageFileName) { image = <img id={this.props.imageId} src={this.state.liveImage} alt="profile" width="80" height="80" />; } else { image = ''; } return ( <div className="file-choser row"> <div className="col-md-2"> <label>{counterpart.translate('IMG_LOGO')}:</label> {image} </div> <div className="col-md-10"> <FileUploadProgress ref="fileupload" key="ex1" url="http://localhost:8081/user/image/upload" method="POST" onProgress={(e, request, progress) => {}} onLoad={(e, request) => { this.loadImage(request.responseText); }} onError={(e, request) => { let error = JSON.parse(e.target.response); this.refs.notification.addNotification(counterpart.translate('UPLOAD_FAILED'), counterpart.translate(error.errorInfos[0].errorCode), 'error'); }} onAbort={(e, request) => {}} beforeSend={this.beforeSend.bind(this)} formGetter={this.formGetter.bind(this)} formRenderer={this.customFormRenderer.bind(this)} progressRenderer={this.customProgressRenderer.bind(this)} /> </div> <Notification ref="notification" /> </div> ); } }
loc_frontend/node_modules/react-router/es6/IndexRoute.js
marka2g/loc
'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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; } import warning from 'warning'; import invariant from 'invariant'; import React, { Component } from 'react'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './PropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = (function (_Component) { _inherits(IndexRoute, _Component); function IndexRoute() { _classCallCheck(this, IndexRoute); _Component.apply(this, arguments); } /* istanbul ignore next: sanity check */ IndexRoute.prototype.render = function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; }; return IndexRoute; })(Component); IndexRoute.propTypes = { path: falsy, component: component, components: components, getComponent: func, getComponents: func }; IndexRoute.createRouteFromReactElement = function (element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : undefined; } }; export default IndexRoute;
client-portal/src/components/Body/Table/ReactBootstrapTable/index.js
choiboi/web-scraper-architecture
import React, { Component } from 'react'; import classnames from 'classnames'; import './react_boottable.css'; import { Table, Button } from 'react-bootstrap'; 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', }, ]; class ReactBootstrapTable extends Component { render() { const { className, ...props } = this.props; return ( <div className={classnames('boot-table', className)} {...props}> <div className="table-title"> <p>{this.props.title}</p> <Button bsStyle="info" className="boot-button">REFRESH</Button> </div> <Table striped bordered condensed hover> <thead> <tr> <th>ID</th> <th>Name</th> <th>Employement Status</th> </tr> </thead> <tbody> { tableData.map((row, index) => ( <tr key={index + 1}> <td>{index + 1}</td> <td>{row.name}</td> <td>{row.status}</td> </tr> )) } </tbody> </Table> </div> ); } } export default ReactBootstrapTable;
ajax/libs/yui/3.14.1/scrollview-base/scrollview-base-coverage.js
SanaNasar/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/scrollview-base/scrollview-base.js']) { __coverage__['build/scrollview-base/scrollview-base.js'] = {"path":"build/scrollview-base/scrollview-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0,0],"52":[0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0,0,0,0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":27},"end":{"line":1,"column":46}}},"2":{"name":"(anonymous_2)","line":49,"loc":{"start":{"line":49,"column":17},"end":{"line":49,"column":42}}},"3":{"name":"ScrollView","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":22}}},"4":{"name":"(anonymous_4)","line":168,"loc":{"start":{"line":168,"column":17},"end":{"line":168,"column":29}}},"5":{"name":"(anonymous_5)","line":189,"loc":{"start":{"line":189,"column":12},"end":{"line":189,"column":24}}},"6":{"name":"(anonymous_6)","line":237,"loc":{"start":{"line":237,"column":16},"end":{"line":237,"column":28}}},"7":{"name":"(anonymous_7)","line":265,"loc":{"start":{"line":265,"column":15},"end":{"line":265,"column":31}}},"8":{"name":"(anonymous_8)","line":285,"loc":{"start":{"line":285,"column":16},"end":{"line":285,"column":33}}},"9":{"name":"(anonymous_9)","line":308,"loc":{"start":{"line":308,"column":21},"end":{"line":308,"column":43}}},"10":{"name":"(anonymous_10)","line":330,"loc":{"start":{"line":330,"column":12},"end":{"line":330,"column":24}}},"11":{"name":"(anonymous_11)","line":374,"loc":{"start":{"line":374,"column":20},"end":{"line":374,"column":32}}},"12":{"name":"(anonymous_12)","line":417,"loc":{"start":{"line":417,"column":25},"end":{"line":417,"column":37}}},"13":{"name":"(anonymous_13)","line":459,"loc":{"start":{"line":459,"column":16},"end":{"line":459,"column":34}}},"14":{"name":"(anonymous_14)","line":476,"loc":{"start":{"line":476,"column":16},"end":{"line":476,"column":28}}},"15":{"name":"(anonymous_15)","line":499,"loc":{"start":{"line":499,"column":14},"end":{"line":499,"column":54}}},"16":{"name":"(anonymous_16)","line":579,"loc":{"start":{"line":579,"column":16},"end":{"line":579,"column":32}}},"17":{"name":"(anonymous_17)","line":599,"loc":{"start":{"line":599,"column":14},"end":{"line":599,"column":35}}},"18":{"name":"(anonymous_18)","line":616,"loc":{"start":{"line":616,"column":17},"end":{"line":616,"column":29}}},"19":{"name":"(anonymous_19)","line":641,"loc":{"start":{"line":641,"column":25},"end":{"line":641,"column":38}}},"20":{"name":"(anonymous_20)","line":707,"loc":{"start":{"line":707,"column":20},"end":{"line":707,"column":33}}},"21":{"name":"(anonymous_21)","line":749,"loc":{"start":{"line":749,"column":23},"end":{"line":749,"column":36}}},"22":{"name":"(anonymous_22)","line":804,"loc":{"start":{"line":804,"column":12},"end":{"line":804,"column":25}}},"23":{"name":"(anonymous_23)","line":837,"loc":{"start":{"line":837,"column":17},"end":{"line":837,"column":63}}},"24":{"name":"(anonymous_24)","line":900,"loc":{"start":{"line":900,"column":18},"end":{"line":900,"column":30}}},"25":{"name":"(anonymous_25)","line":920,"loc":{"start":{"line":920,"column":17},"end":{"line":920,"column":30}}},"26":{"name":"(anonymous_26)","line":970,"loc":{"start":{"line":970,"column":20},"end":{"line":970,"column":36}}},"27":{"name":"(anonymous_27)","line":993,"loc":{"start":{"line":993,"column":15},"end":{"line":993,"column":27}}},"28":{"name":"(anonymous_28)","line":1025,"loc":{"start":{"line":1025,"column":24},"end":{"line":1025,"column":37}}},"29":{"name":"(anonymous_29)","line":1062,"loc":{"start":{"line":1062,"column":23},"end":{"line":1062,"column":36}}},"30":{"name":"(anonymous_30)","line":1073,"loc":{"start":{"line":1073,"column":26},"end":{"line":1073,"column":39}}},"31":{"name":"(anonymous_31)","line":1085,"loc":{"start":{"line":1085,"column":22},"end":{"line":1085,"column":35}}},"32":{"name":"(anonymous_32)","line":1096,"loc":{"start":{"line":1096,"column":22},"end":{"line":1096,"column":35}}},"33":{"name":"(anonymous_33)","line":1107,"loc":{"start":{"line":1107,"column":21},"end":{"line":1107,"column":33}}},"34":{"name":"(anonymous_34)","line":1118,"loc":{"start":{"line":1118,"column":21},"end":{"line":1118,"column":33}}},"35":{"name":"(anonymous_35)","line":1140,"loc":{"start":{"line":1140,"column":17},"end":{"line":1140,"column":32}}},"36":{"name":"(anonymous_36)","line":1161,"loc":{"start":{"line":1161,"column":17},"end":{"line":1161,"column":31}}},"37":{"name":"(anonymous_37)","line":1179,"loc":{"start":{"line":1179,"column":17},"end":{"line":1179,"column":31}}},"38":{"name":"(anonymous_38)","line":1191,"loc":{"start":{"line":1191,"column":17},"end":{"line":1191,"column":31}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1457,"column":113}},"2":{"start":{"line":11,"column":0},"end":{"line":51,"column":6}},"3":{"start":{"line":50,"column":8},"end":{"line":50,"column":49}},"4":{"start":{"line":62,"column":0},"end":{"line":64,"column":1}},"5":{"start":{"line":63,"column":4},"end":{"line":63,"column":61}},"6":{"start":{"line":66,"column":0},"end":{"line":1454,"column":3}},"7":{"start":{"line":169,"column":8},"end":{"line":169,"column":22}},"8":{"start":{"line":172,"column":8},"end":{"line":172,"column":38}},"9":{"start":{"line":173,"column":8},"end":{"line":173,"column":37}},"10":{"start":{"line":176,"column":8},"end":{"line":176,"column":33}},"11":{"start":{"line":177,"column":8},"end":{"line":177,"column":37}},"12":{"start":{"line":178,"column":8},"end":{"line":178,"column":48}},"13":{"start":{"line":179,"column":8},"end":{"line":179,"column":49}},"14":{"start":{"line":180,"column":8},"end":{"line":180,"column":52}},"15":{"start":{"line":190,"column":8},"end":{"line":190,"column":22}},"16":{"start":{"line":193,"column":8},"end":{"line":193,"column":37}},"17":{"start":{"line":194,"column":8},"end":{"line":194,"column":35}},"18":{"start":{"line":195,"column":8},"end":{"line":195,"column":33}},"19":{"start":{"line":198,"column":8},"end":{"line":198,"column":24}},"20":{"start":{"line":201,"column":8},"end":{"line":203,"column":9}},"21":{"start":{"line":202,"column":12},"end":{"line":202,"column":44}},"22":{"start":{"line":206,"column":8},"end":{"line":208,"column":9}},"23":{"start":{"line":207,"column":12},"end":{"line":207,"column":60}},"24":{"start":{"line":210,"column":8},"end":{"line":212,"column":9}},"25":{"start":{"line":211,"column":12},"end":{"line":211,"column":56}},"26":{"start":{"line":214,"column":8},"end":{"line":216,"column":9}},"27":{"start":{"line":215,"column":12},"end":{"line":215,"column":46}},"28":{"start":{"line":218,"column":8},"end":{"line":220,"column":9}},"29":{"start":{"line":219,"column":12},"end":{"line":219,"column":58}},"30":{"start":{"line":222,"column":8},"end":{"line":224,"column":9}},"31":{"start":{"line":223,"column":12},"end":{"line":223,"column":58}},"32":{"start":{"line":238,"column":8},"end":{"line":240,"column":50}},"33":{"start":{"line":243,"column":8},"end":{"line":253,"column":11}},"34":{"start":{"line":266,"column":8},"end":{"line":267,"column":24}},"35":{"start":{"line":270,"column":8},"end":{"line":270,"column":31}},"36":{"start":{"line":272,"column":8},"end":{"line":274,"column":9}},"37":{"start":{"line":273,"column":12},"end":{"line":273,"column":89}},"38":{"start":{"line":286,"column":8},"end":{"line":287,"column":24}},"39":{"start":{"line":290,"column":8},"end":{"line":290,"column":32}},"40":{"start":{"line":292,"column":8},"end":{"line":297,"column":9}},"41":{"start":{"line":293,"column":12},"end":{"line":293,"column":69}},"42":{"start":{"line":296,"column":12},"end":{"line":296,"column":39}},"43":{"start":{"line":309,"column":8},"end":{"line":310,"column":24}},"44":{"start":{"line":314,"column":8},"end":{"line":314,"column":37}},"45":{"start":{"line":317,"column":8},"end":{"line":320,"column":9}},"46":{"start":{"line":319,"column":12},"end":{"line":319,"column":71}},"47":{"start":{"line":331,"column":8},"end":{"line":336,"column":51}},"48":{"start":{"line":339,"column":8},"end":{"line":348,"column":9}},"49":{"start":{"line":342,"column":12},"end":{"line":345,"column":14}},"50":{"start":{"line":347,"column":12},"end":{"line":347,"column":37}},"51":{"start":{"line":351,"column":8},"end":{"line":351,"column":66}},"52":{"start":{"line":354,"column":8},"end":{"line":354,"column":41}},"53":{"start":{"line":357,"column":8},"end":{"line":357,"column":33}},"54":{"start":{"line":360,"column":8},"end":{"line":362,"column":9}},"55":{"start":{"line":361,"column":12},"end":{"line":361,"column":27}},"56":{"start":{"line":375,"column":8},"end":{"line":385,"column":17}},"57":{"start":{"line":388,"column":8},"end":{"line":391,"column":9}},"58":{"start":{"line":389,"column":12},"end":{"line":389,"column":46}},"59":{"start":{"line":390,"column":12},"end":{"line":390,"column":47}},"60":{"start":{"line":393,"column":8},"end":{"line":393,"column":48}},"61":{"start":{"line":394,"column":8},"end":{"line":394,"column":38}},"62":{"start":{"line":396,"column":8},"end":{"line":396,"column":29}},"63":{"start":{"line":397,"column":8},"end":{"line":402,"column":10}},"64":{"start":{"line":403,"column":8},"end":{"line":403,"column":43}},"65":{"start":{"line":405,"column":8},"end":{"line":405,"column":48}},"66":{"start":{"line":407,"column":8},"end":{"line":407,"column":20}},"67":{"start":{"line":418,"column":8},"end":{"line":430,"column":60}},"68":{"start":{"line":432,"column":8},"end":{"line":434,"column":9}},"69":{"start":{"line":433,"column":12},"end":{"line":433,"column":48}},"70":{"start":{"line":436,"column":8},"end":{"line":438,"column":9}},"71":{"start":{"line":437,"column":12},"end":{"line":437,"column":46}},"72":{"start":{"line":440,"column":8},"end":{"line":445,"column":11}},"73":{"start":{"line":460,"column":8},"end":{"line":460,"column":22}},"74":{"start":{"line":464,"column":8},"end":{"line":464,"column":43}},"75":{"start":{"line":465,"column":8},"end":{"line":465,"column":43}},"76":{"start":{"line":466,"column":8},"end":{"line":466,"column":43}},"77":{"start":{"line":467,"column":8},"end":{"line":467,"column":43}},"78":{"start":{"line":477,"column":8},"end":{"line":477,"column":22}},"79":{"start":{"line":479,"column":8},"end":{"line":484,"column":10}},"80":{"start":{"line":501,"column":8},"end":{"line":503,"column":9}},"81":{"start":{"line":502,"column":12},"end":{"line":502,"column":19}},"82":{"start":{"line":505,"column":8},"end":{"line":512,"column":22}},"83":{"start":{"line":515,"column":8},"end":{"line":515,"column":33}},"84":{"start":{"line":516,"column":8},"end":{"line":516,"column":42}},"85":{"start":{"line":517,"column":8},"end":{"line":517,"column":26}},"86":{"start":{"line":519,"column":8},"end":{"line":522,"column":9}},"87":{"start":{"line":520,"column":12},"end":{"line":520,"column":42}},"88":{"start":{"line":521,"column":12},"end":{"line":521,"column":24}},"89":{"start":{"line":524,"column":8},"end":{"line":527,"column":9}},"90":{"start":{"line":525,"column":12},"end":{"line":525,"column":42}},"91":{"start":{"line":526,"column":12},"end":{"line":526,"column":24}},"92":{"start":{"line":529,"column":8},"end":{"line":529,"column":46}},"93":{"start":{"line":531,"column":8},"end":{"line":534,"column":9}},"94":{"start":{"line":533,"column":12},"end":{"line":533,"column":80}},"95":{"start":{"line":537,"column":8},"end":{"line":567,"column":9}},"96":{"start":{"line":538,"column":12},"end":{"line":550,"column":13}},"97":{"start":{"line":539,"column":16},"end":{"line":539,"column":54}},"98":{"start":{"line":544,"column":16},"end":{"line":546,"column":17}},"99":{"start":{"line":545,"column":20},"end":{"line":545,"column":51}},"100":{"start":{"line":547,"column":16},"end":{"line":549,"column":17}},"101":{"start":{"line":548,"column":20},"end":{"line":548,"column":50}},"102":{"start":{"line":555,"column":12},"end":{"line":555,"column":39}},"103":{"start":{"line":556,"column":12},"end":{"line":556,"column":50}},"104":{"start":{"line":558,"column":12},"end":{"line":564,"column":13}},"105":{"start":{"line":559,"column":16},"end":{"line":559,"column":49}},"106":{"start":{"line":562,"column":16},"end":{"line":562,"column":44}},"107":{"start":{"line":563,"column":16},"end":{"line":563,"column":43}},"108":{"start":{"line":566,"column":12},"end":{"line":566,"column":50}},"109":{"start":{"line":581,"column":8},"end":{"line":581,"column":57}},"110":{"start":{"line":583,"column":8},"end":{"line":585,"column":9}},"111":{"start":{"line":584,"column":12},"end":{"line":584,"column":37}},"112":{"start":{"line":587,"column":8},"end":{"line":587,"column":20}},"113":{"start":{"line":600,"column":8},"end":{"line":605,"column":9}},"114":{"start":{"line":601,"column":12},"end":{"line":601,"column":62}},"115":{"start":{"line":603,"column":12},"end":{"line":603,"column":40}},"116":{"start":{"line":604,"column":12},"end":{"line":604,"column":39}},"117":{"start":{"line":617,"column":8},"end":{"line":617,"column":22}},"118":{"start":{"line":620,"column":8},"end":{"line":631,"column":9}},"119":{"start":{"line":621,"column":12},"end":{"line":621,"column":27}},"120":{"start":{"line":630,"column":12},"end":{"line":630,"column":35}},"121":{"start":{"line":643,"column":8},"end":{"line":645,"column":9}},"122":{"start":{"line":644,"column":12},"end":{"line":644,"column":25}},"123":{"start":{"line":647,"column":8},"end":{"line":652,"column":32}},"124":{"start":{"line":654,"column":8},"end":{"line":656,"column":9}},"125":{"start":{"line":655,"column":12},"end":{"line":655,"column":31}},"126":{"start":{"line":659,"column":8},"end":{"line":662,"column":9}},"127":{"start":{"line":660,"column":12},"end":{"line":660,"column":30}},"128":{"start":{"line":661,"column":12},"end":{"line":661,"column":29}},"129":{"start":{"line":665,"column":8},"end":{"line":665,"column":31}},"130":{"start":{"line":668,"column":8},"end":{"line":697,"column":10}},"131":{"start":{"line":708,"column":8},"end":{"line":718,"column":32}},"132":{"start":{"line":720,"column":8},"end":{"line":722,"column":9}},"133":{"start":{"line":721,"column":12},"end":{"line":721,"column":31}},"134":{"start":{"line":724,"column":8},"end":{"line":724,"column":48}},"135":{"start":{"line":725,"column":8},"end":{"line":725,"column":48}},"136":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"137":{"start":{"line":730,"column":12},"end":{"line":730,"column":97}},"138":{"start":{"line":734,"column":8},"end":{"line":739,"column":9}},"139":{"start":{"line":735,"column":12},"end":{"line":735,"column":54}},"140":{"start":{"line":737,"column":13},"end":{"line":739,"column":9}},"141":{"start":{"line":738,"column":12},"end":{"line":738,"column":54}},"142":{"start":{"line":750,"column":8},"end":{"line":755,"column":18}},"143":{"start":{"line":757,"column":8},"end":{"line":759,"column":9}},"144":{"start":{"line":758,"column":12},"end":{"line":758,"column":31}},"145":{"start":{"line":762,"column":8},"end":{"line":762,"column":37}},"146":{"start":{"line":763,"column":8},"end":{"line":763,"column":37}},"147":{"start":{"line":766,"column":8},"end":{"line":766,"column":39}},"148":{"start":{"line":767,"column":8},"end":{"line":767,"column":42}},"149":{"start":{"line":770,"column":8},"end":{"line":794,"column":9}},"150":{"start":{"line":776,"column":12},"end":{"line":793,"column":13}},"151":{"start":{"line":778,"column":16},"end":{"line":778,"column":44}},"152":{"start":{"line":781,"column":16},"end":{"line":792,"column":17}},"153":{"start":{"line":782,"column":20},"end":{"line":782,"column":35}},"154":{"start":{"line":789,"column":20},"end":{"line":791,"column":21}},"155":{"start":{"line":790,"column":24},"end":{"line":790,"column":41}},"156":{"start":{"line":805,"column":8},"end":{"line":807,"column":9}},"157":{"start":{"line":806,"column":12},"end":{"line":806,"column":25}},"158":{"start":{"line":809,"column":8},"end":{"line":815,"column":45}},"159":{"start":{"line":818,"column":8},"end":{"line":820,"column":9}},"160":{"start":{"line":819,"column":12},"end":{"line":819,"column":38}},"161":{"start":{"line":823,"column":8},"end":{"line":825,"column":9}},"162":{"start":{"line":824,"column":12},"end":{"line":824,"column":68}},"163":{"start":{"line":839,"column":8},"end":{"line":864,"column":20}},"164":{"start":{"line":867,"column":8},"end":{"line":869,"column":9}},"165":{"start":{"line":868,"column":12},"end":{"line":868,"column":34}},"166":{"start":{"line":872,"column":8},"end":{"line":872,"column":61}},"167":{"start":{"line":875,"column":8},"end":{"line":897,"column":9}},"168":{"start":{"line":877,"column":12},"end":{"line":879,"column":13}},"169":{"start":{"line":878,"column":16},"end":{"line":878,"column":34}},"170":{"start":{"line":882,"column":12},"end":{"line":889,"column":13}},"171":{"start":{"line":883,"column":16},"end":{"line":883,"column":33}},"172":{"start":{"line":888,"column":16},"end":{"line":888,"column":31}},"173":{"start":{"line":895,"column":12},"end":{"line":895,"column":109}},"174":{"start":{"line":896,"column":12},"end":{"line":896,"column":42}},"175":{"start":{"line":901,"column":8},"end":{"line":901,"column":22}},"176":{"start":{"line":903,"column":8},"end":{"line":909,"column":9}},"177":{"start":{"line":905,"column":12},"end":{"line":905,"column":35}},"178":{"start":{"line":908,"column":12},"end":{"line":908,"column":33}},"179":{"start":{"line":921,"column":8},"end":{"line":927,"column":72}},"180":{"start":{"line":929,"column":8},"end":{"line":929,"column":80}},"181":{"start":{"line":935,"column":8},"end":{"line":958,"column":9}},"182":{"start":{"line":938,"column":12},"end":{"line":938,"column":35}},"183":{"start":{"line":941,"column":12},"end":{"line":941,"column":40}},"184":{"start":{"line":945,"column":12},"end":{"line":951,"column":13}},"185":{"start":{"line":947,"column":16},"end":{"line":947,"column":40}},"186":{"start":{"line":948,"column":16},"end":{"line":948,"column":38}},"187":{"start":{"line":954,"column":12},"end":{"line":954,"column":29}},"188":{"start":{"line":957,"column":12},"end":{"line":957,"column":31}},"189":{"start":{"line":971,"column":8},"end":{"line":981,"column":37}},"190":{"start":{"line":983,"column":8},"end":{"line":983,"column":118}},"191":{"start":{"line":994,"column":8},"end":{"line":1005,"column":41}},"192":{"start":{"line":1007,"column":8},"end":{"line":1015,"column":9}},"193":{"start":{"line":1008,"column":12},"end":{"line":1008,"column":71}},"194":{"start":{"line":1010,"column":13},"end":{"line":1015,"column":9}},"195":{"start":{"line":1011,"column":12},"end":{"line":1011,"column":71}},"196":{"start":{"line":1014,"column":12},"end":{"line":1014,"column":29}},"197":{"start":{"line":1026,"column":8},"end":{"line":1028,"column":9}},"198":{"start":{"line":1027,"column":12},"end":{"line":1027,"column":25}},"199":{"start":{"line":1030,"column":8},"end":{"line":1034,"column":30}},"200":{"start":{"line":1037,"column":8},"end":{"line":1037,"column":73}},"201":{"start":{"line":1040,"column":8},"end":{"line":1047,"column":9}},"202":{"start":{"line":1041,"column":12},"end":{"line":1041,"column":35}},"203":{"start":{"line":1042,"column":12},"end":{"line":1042,"column":48}},"204":{"start":{"line":1045,"column":12},"end":{"line":1045,"column":48}},"205":{"start":{"line":1046,"column":12},"end":{"line":1046,"column":35}},"206":{"start":{"line":1049,"column":8},"end":{"line":1049,"column":36}},"207":{"start":{"line":1050,"column":8},"end":{"line":1050,"column":34}},"208":{"start":{"line":1052,"column":8},"end":{"line":1052,"column":44}},"209":{"start":{"line":1063,"column":8},"end":{"line":1063,"column":34}},"210":{"start":{"line":1075,"column":8},"end":{"line":1075,"column":35}},"211":{"start":{"line":1086,"column":8},"end":{"line":1086,"column":31}},"212":{"start":{"line":1097,"column":8},"end":{"line":1097,"column":33}},"213":{"start":{"line":1108,"column":8},"end":{"line":1108,"column":35}},"214":{"start":{"line":1119,"column":8},"end":{"line":1119,"column":22}},"215":{"start":{"line":1121,"column":8},"end":{"line":1123,"column":9}},"216":{"start":{"line":1122,"column":12},"end":{"line":1122,"column":30}},"217":{"start":{"line":1143,"column":8},"end":{"line":1148,"column":9}},"218":{"start":{"line":1144,"column":12},"end":{"line":1147,"column":14}},"219":{"start":{"line":1164,"column":8},"end":{"line":1166,"column":9}},"220":{"start":{"line":1165,"column":12},"end":{"line":1165,"column":44}},"221":{"start":{"line":1168,"column":8},"end":{"line":1168,"column":19}},"222":{"start":{"line":1180,"column":8},"end":{"line":1180,"column":43}},"223":{"start":{"line":1192,"column":8},"end":{"line":1192,"column":43}}},"branchMap":{"1":{"line":78,"type":"cond-expr","locations":[{"start":{"line":78,"column":38},"end":{"line":78,"column":42}},{"start":{"line":78,"column":45},"end":{"line":78,"column":50}}]},"2":{"line":201,"type":"if","locations":[{"start":{"line":201,"column":8},"end":{"line":201,"column":8}},{"start":{"line":201,"column":8},"end":{"line":201,"column":8}}]},"3":{"line":206,"type":"if","locations":[{"start":{"line":206,"column":8},"end":{"line":206,"column":8}},{"start":{"line":206,"column":8},"end":{"line":206,"column":8}}]},"4":{"line":210,"type":"if","locations":[{"start":{"line":210,"column":8},"end":{"line":210,"column":8}},{"start":{"line":210,"column":8},"end":{"line":210,"column":8}}]},"5":{"line":214,"type":"if","locations":[{"start":{"line":214,"column":8},"end":{"line":214,"column":8}},{"start":{"line":214,"column":8},"end":{"line":214,"column":8}}]},"6":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":8},"end":{"line":218,"column":8}},{"start":{"line":218,"column":8},"end":{"line":218,"column":8}}]},"7":{"line":222,"type":"if","locations":[{"start":{"line":222,"column":8},"end":{"line":222,"column":8}},{"start":{"line":222,"column":8},"end":{"line":222,"column":8}}]},"8":{"line":272,"type":"if","locations":[{"start":{"line":272,"column":8},"end":{"line":272,"column":8}},{"start":{"line":272,"column":8},"end":{"line":272,"column":8}}]},"9":{"line":292,"type":"if","locations":[{"start":{"line":292,"column":8},"end":{"line":292,"column":8}},{"start":{"line":292,"column":8},"end":{"line":292,"column":8}}]},"10":{"line":317,"type":"if","locations":[{"start":{"line":317,"column":8},"end":{"line":317,"column":8}},{"start":{"line":317,"column":8},"end":{"line":317,"column":8}}]},"11":{"line":339,"type":"if","locations":[{"start":{"line":339,"column":8},"end":{"line":339,"column":8}},{"start":{"line":339,"column":8},"end":{"line":339,"column":8}}]},"12":{"line":360,"type":"if","locations":[{"start":{"line":360,"column":8},"end":{"line":360,"column":8}},{"start":{"line":360,"column":8},"end":{"line":360,"column":8}}]},"13":{"line":388,"type":"if","locations":[{"start":{"line":388,"column":8},"end":{"line":388,"column":8}},{"start":{"line":388,"column":8},"end":{"line":388,"column":8}}]},"14":{"line":427,"type":"cond-expr","locations":[{"start":{"line":427,"column":32},"end":{"line":427,"column":67}},{"start":{"line":427,"column":70},"end":{"line":427,"column":71}}]},"15":{"line":428,"type":"cond-expr","locations":[{"start":{"line":428,"column":32},"end":{"line":428,"column":33}},{"start":{"line":428,"column":36},"end":{"line":428,"column":68}}]},"16":{"line":432,"type":"if","locations":[{"start":{"line":432,"column":8},"end":{"line":432,"column":8}},{"start":{"line":432,"column":8},"end":{"line":432,"column":8}}]},"17":{"line":432,"type":"binary-expr","locations":[{"start":{"line":432,"column":12},"end":{"line":432,"column":18}},{"start":{"line":432,"column":22},"end":{"line":432,"column":30}}]},"18":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":8},"end":{"line":436,"column":8}},{"start":{"line":436,"column":8},"end":{"line":436,"column":8}}]},"19":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":18}},{"start":{"line":436,"column":22},"end":{"line":436,"column":30}}]},"20":{"line":501,"type":"if","locations":[{"start":{"line":501,"column":8},"end":{"line":501,"column":8}},{"start":{"line":501,"column":8},"end":{"line":501,"column":8}}]},"21":{"line":515,"type":"binary-expr","locations":[{"start":{"line":515,"column":19},"end":{"line":515,"column":27}},{"start":{"line":515,"column":31},"end":{"line":515,"column":32}}]},"22":{"line":516,"type":"binary-expr","locations":[{"start":{"line":516,"column":17},"end":{"line":516,"column":23}},{"start":{"line":516,"column":27},"end":{"line":516,"column":41}}]},"23":{"line":517,"type":"binary-expr","locations":[{"start":{"line":517,"column":15},"end":{"line":517,"column":19}},{"start":{"line":517,"column":23},"end":{"line":517,"column":25}}]},"24":{"line":519,"type":"if","locations":[{"start":{"line":519,"column":8},"end":{"line":519,"column":8}},{"start":{"line":519,"column":8},"end":{"line":519,"column":8}}]},"25":{"line":524,"type":"if","locations":[{"start":{"line":524,"column":8},"end":{"line":524,"column":8}},{"start":{"line":524,"column":8},"end":{"line":524,"column":8}}]},"26":{"line":531,"type":"if","locations":[{"start":{"line":531,"column":8},"end":{"line":531,"column":8}},{"start":{"line":531,"column":8},"end":{"line":531,"column":8}}]},"27":{"line":537,"type":"if","locations":[{"start":{"line":537,"column":8},"end":{"line":537,"column":8}},{"start":{"line":537,"column":8},"end":{"line":537,"column":8}}]},"28":{"line":538,"type":"if","locations":[{"start":{"line":538,"column":12},"end":{"line":538,"column":12}},{"start":{"line":538,"column":12},"end":{"line":538,"column":12}}]},"29":{"line":544,"type":"if","locations":[{"start":{"line":544,"column":16},"end":{"line":544,"column":16}},{"start":{"line":544,"column":16},"end":{"line":544,"column":16}}]},"30":{"line":547,"type":"if","locations":[{"start":{"line":547,"column":16},"end":{"line":547,"column":16}},{"start":{"line":547,"column":16},"end":{"line":547,"column":16}}]},"31":{"line":558,"type":"if","locations":[{"start":{"line":558,"column":12},"end":{"line":558,"column":12}},{"start":{"line":558,"column":12},"end":{"line":558,"column":12}}]},"32":{"line":583,"type":"if","locations":[{"start":{"line":583,"column":8},"end":{"line":583,"column":8}},{"start":{"line":583,"column":8},"end":{"line":583,"column":8}}]},"33":{"line":600,"type":"if","locations":[{"start":{"line":600,"column":8},"end":{"line":600,"column":8}},{"start":{"line":600,"column":8},"end":{"line":600,"column":8}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":643,"type":"if","locations":[{"start":{"line":643,"column":8},"end":{"line":643,"column":8}},{"start":{"line":643,"column":8},"end":{"line":643,"column":8}}]},"36":{"line":654,"type":"if","locations":[{"start":{"line":654,"column":8},"end":{"line":654,"column":8}},{"start":{"line":654,"column":8},"end":{"line":654,"column":8}}]},"37":{"line":659,"type":"if","locations":[{"start":{"line":659,"column":8},"end":{"line":659,"column":8}},{"start":{"line":659,"column":8},"end":{"line":659,"column":8}}]},"38":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":8},"end":{"line":720,"column":8}},{"start":{"line":720,"column":8},"end":{"line":720,"column":8}}]},"39":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"40":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":83},"end":{"line":730,"column":88}},{"start":{"line":730,"column":91},"end":{"line":730,"column":96}}]},"41":{"line":734,"type":"if","locations":[{"start":{"line":734,"column":8},"end":{"line":734,"column":8}},{"start":{"line":734,"column":8},"end":{"line":734,"column":8}}]},"42":{"line":734,"type":"binary-expr","locations":[{"start":{"line":734,"column":12},"end":{"line":734,"column":34}},{"start":{"line":734,"column":38},"end":{"line":734,"column":45}}]},"43":{"line":737,"type":"if","locations":[{"start":{"line":737,"column":13},"end":{"line":737,"column":13}},{"start":{"line":737,"column":13},"end":{"line":737,"column":13}}]},"44":{"line":737,"type":"binary-expr","locations":[{"start":{"line":737,"column":17},"end":{"line":737,"column":39}},{"start":{"line":737,"column":43},"end":{"line":737,"column":50}}]},"45":{"line":757,"type":"if","locations":[{"start":{"line":757,"column":8},"end":{"line":757,"column":8}},{"start":{"line":757,"column":8},"end":{"line":757,"column":8}}]},"46":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"47":{"line":776,"type":"if","locations":[{"start":{"line":776,"column":12},"end":{"line":776,"column":12}},{"start":{"line":776,"column":12},"end":{"line":776,"column":12}}]},"48":{"line":776,"type":"binary-expr","locations":[{"start":{"line":776,"column":16},"end":{"line":776,"column":39}},{"start":{"line":776,"column":43},"end":{"line":776,"column":66}}]},"49":{"line":781,"type":"if","locations":[{"start":{"line":781,"column":16},"end":{"line":781,"column":16}},{"start":{"line":781,"column":16},"end":{"line":781,"column":16}}]},"50":{"line":789,"type":"if","locations":[{"start":{"line":789,"column":20},"end":{"line":789,"column":20}},{"start":{"line":789,"column":20},"end":{"line":789,"column":20}}]},"51":{"line":789,"type":"binary-expr","locations":[{"start":{"line":789,"column":24},"end":{"line":789,"column":33}},{"start":{"line":789,"column":38},"end":{"line":789,"column":46}},{"start":{"line":789,"column":50},"end":{"line":789,"column":83}}]},"52":{"line":805,"type":"if","locations":[{"start":{"line":805,"column":8},"end":{"line":805,"column":8}},{"start":{"line":805,"column":8},"end":{"line":805,"column":8}}]},"53":{"line":814,"type":"cond-expr","locations":[{"start":{"line":814,"column":45},"end":{"line":814,"column":53}},{"start":{"line":814,"column":56},"end":{"line":814,"column":64}}]},"54":{"line":818,"type":"if","locations":[{"start":{"line":818,"column":8},"end":{"line":818,"column":8}},{"start":{"line":818,"column":8},"end":{"line":818,"column":8}}]},"55":{"line":823,"type":"if","locations":[{"start":{"line":823,"column":8},"end":{"line":823,"column":8}},{"start":{"line":823,"column":8},"end":{"line":823,"column":8}}]},"56":{"line":840,"type":"cond-expr","locations":[{"start":{"line":840,"column":45},"end":{"line":840,"column":53}},{"start":{"line":840,"column":56},"end":{"line":840,"column":64}}]},"57":{"line":854,"type":"cond-expr","locations":[{"start":{"line":854,"column":40},"end":{"line":854,"column":57}},{"start":{"line":854,"column":60},"end":{"line":854,"column":77}}]},"58":{"line":855,"type":"cond-expr","locations":[{"start":{"line":855,"column":40},"end":{"line":855,"column":57}},{"start":{"line":855,"column":60},"end":{"line":855,"column":77}}]},"59":{"line":861,"type":"binary-expr","locations":[{"start":{"line":861,"column":30},"end":{"line":861,"column":38}},{"start":{"line":861,"column":43},"end":{"line":861,"column":76}}]},"60":{"line":862,"type":"binary-expr","locations":[{"start":{"line":862,"column":30},"end":{"line":862,"column":38}},{"start":{"line":862,"column":43},"end":{"line":862,"column":76}}]},"61":{"line":867,"type":"if","locations":[{"start":{"line":867,"column":8},"end":{"line":867,"column":8}},{"start":{"line":867,"column":8},"end":{"line":867,"column":8}}]},"62":{"line":867,"type":"binary-expr","locations":[{"start":{"line":867,"column":12},"end":{"line":867,"column":26}},{"start":{"line":867,"column":30},"end":{"line":867,"column":44}}]},"63":{"line":875,"type":"if","locations":[{"start":{"line":875,"column":8},"end":{"line":875,"column":8}},{"start":{"line":875,"column":8},"end":{"line":875,"column":8}}]},"64":{"line":875,"type":"binary-expr","locations":[{"start":{"line":875,"column":12},"end":{"line":875,"column":19}},{"start":{"line":875,"column":23},"end":{"line":875,"column":36}},{"start":{"line":875,"column":40},"end":{"line":875,"column":53}}]},"65":{"line":877,"type":"if","locations":[{"start":{"line":877,"column":12},"end":{"line":877,"column":12}},{"start":{"line":877,"column":12},"end":{"line":877,"column":12}}]},"66":{"line":882,"type":"if","locations":[{"start":{"line":882,"column":12},"end":{"line":882,"column":12}},{"start":{"line":882,"column":12},"end":{"line":882,"column":12}}]},"67":{"line":882,"type":"binary-expr","locations":[{"start":{"line":882,"column":16},"end":{"line":882,"column":24}},{"start":{"line":882,"column":28},"end":{"line":882,"column":36}}]},"68":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"69":{"line":927,"type":"cond-expr","locations":[{"start":{"line":927,"column":48},"end":{"line":927,"column":49}},{"start":{"line":927,"column":52},"end":{"line":927,"column":54}}]},"70":{"line":935,"type":"if","locations":[{"start":{"line":935,"column":8},"end":{"line":935,"column":8}},{"start":{"line":935,"column":8},"end":{"line":935,"column":8}}]},"71":{"line":935,"type":"binary-expr","locations":[{"start":{"line":935,"column":12},"end":{"line":935,"column":33}},{"start":{"line":935,"column":37},"end":{"line":935,"column":53}}]},"72":{"line":945,"type":"if","locations":[{"start":{"line":945,"column":12},"end":{"line":945,"column":12}},{"start":{"line":945,"column":12},"end":{"line":945,"column":12}}]},"73":{"line":975,"type":"binary-expr","locations":[{"start":{"line":975,"column":23},"end":{"line":975,"column":24}},{"start":{"line":975,"column":28},"end":{"line":975,"column":44}}]},"74":{"line":976,"type":"binary-expr","locations":[{"start":{"line":976,"column":23},"end":{"line":976,"column":24}},{"start":{"line":976,"column":28},"end":{"line":976,"column":44}}]},"75":{"line":983,"type":"binary-expr","locations":[{"start":{"line":983,"column":16},"end":{"line":983,"column":23}},{"start":{"line":983,"column":28},"end":{"line":983,"column":43}},{"start":{"line":983,"column":47},"end":{"line":983,"column":62}},{"start":{"line":983,"column":69},"end":{"line":983,"column":76}},{"start":{"line":983,"column":81},"end":{"line":983,"column":96}},{"start":{"line":983,"column":100},"end":{"line":983,"column":115}}]},"76":{"line":1007,"type":"if","locations":[{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}},{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}}]},"77":{"line":1010,"type":"if","locations":[{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}},{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}}]},"78":{"line":1026,"type":"if","locations":[{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}},{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}}]},"79":{"line":1040,"type":"if","locations":[{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}},{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}}]},"80":{"line":1121,"type":"if","locations":[{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}},{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}}]},"81":{"line":1143,"type":"if","locations":[{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}},{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}}]},"82":{"line":1145,"type":"cond-expr","locations":[{"start":{"line":1145,"column":37},"end":{"line":1145,"column":41}},{"start":{"line":1145,"column":44},"end":{"line":1145,"column":49}}]},"83":{"line":1146,"type":"cond-expr","locations":[{"start":{"line":1146,"column":37},"end":{"line":1146,"column":41}},{"start":{"line":1146,"column":44},"end":{"line":1146,"column":49}}]},"84":{"line":1164,"type":"if","locations":[{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}},{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}}]},"85":{"line":1393,"type":"cond-expr","locations":[{"start":{"line":1393,"column":34},"end":{"line":1393,"column":69}},{"start":{"line":1393,"column":72},"end":{"line":1393,"column":92}}]},"86":{"line":1394,"type":"cond-expr","locations":[{"start":{"line":1394,"column":34},"end":{"line":1394,"column":69}},{"start":{"line":1394,"column":72},"end":{"line":1394,"column":92}}]}},"code":["(function () { YUI.add('scrollview-base', function (Y, NAME) {","","/**"," * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators"," *"," * @module scrollview"," * @submodule scrollview-base"," */",""," // Local vars","var getClassName = Y.ClassNameManager.getClassName,"," DOCUMENT = Y.config.doc,"," IE = Y.UA.ie,"," NATIVE_TRANSITIONS = Y.Transition.useNative,"," vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated"," SCROLLVIEW = 'scrollview',"," CLASS_NAMES = {"," vertical: getClassName(SCROLLVIEW, 'vert'),"," horizontal: getClassName(SCROLLVIEW, 'horiz')"," },"," EV_SCROLL_END = 'scrollEnd',"," FLICK = 'flick',"," DRAG = 'drag',"," MOUSEWHEEL = 'mousewheel',"," UI = 'ui',"," TOP = 'top',"," LEFT = 'left',"," PX = 'px',"," AXIS = 'axis',"," SCROLL_Y = 'scrollY',"," SCROLL_X = 'scrollX',"," BOUNCE = 'bounce',"," DISABLED = 'disabled',"," DECELERATION = 'deceleration',"," DIM_X = 'x',"," DIM_Y = 'y',"," BOUNDING_BOX = 'boundingBox',"," CONTENT_BOX = 'contentBox',"," GESTURE_MOVE = 'gesturemove',"," START = 'start',"," END = 'end',"," EMPTY = '',"," ZERO = '0s',"," SNAP_DURATION = 'snapDuration',"," SNAP_EASING = 'snapEasing',"," EASING = 'easing',"," FRAME_DURATION = 'frameDuration',"," BOUNCE_RANGE = 'bounceRange',"," _constrain = function (val, min, max) {"," return Math.min(Math.max(val, min), max);"," };","","/**"," * ScrollView provides a scrollable widget, supporting flick gestures,"," * across both touch and mouse based devices."," *"," * @class ScrollView"," * @param config {Object} Object literal with initial attribute values"," * @extends Widget"," * @constructor"," */","function ScrollView() {"," ScrollView.superclass.constructor.apply(this, arguments);","}","","Y.ScrollView = Y.extend(ScrollView, Y.Widget, {",""," // *** Y.ScrollView prototype",""," /**"," * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit."," * Used by the _transform method."," *"," * @property _forceHWTransforms"," * @type boolean"," * @protected"," */"," _forceHWTransforms: Y.UA.webkit ? true : false,",""," /**"," * <p>Used to control whether or not ScrollView's internal"," * gesturemovestart, gesturemove and gesturemoveend"," * event listeners should preventDefault. The value is an"," * object, with \"start\", \"move\" and \"end\" properties used to"," * specify which events should preventDefault and which shouldn't:</p>"," *"," * <pre>"," * {"," * start: false,"," * move: true,"," * end: false"," * }"," * </pre>"," *"," * <p>The default values are set up in order to prevent panning,"," * on touch devices, while allowing click listeners on elements inside"," * the ScrollView to be notified as expected.</p>"," *"," * @property _prevent"," * @type Object"," * @protected"," */"," _prevent: {"," start: false,"," move: true,"," end: false"," },",""," /**"," * Contains the distance (postive or negative) in pixels by which"," * the scrollview was last scrolled. This is useful when setting up"," * click listeners on the scrollview content, which on mouse based"," * devices are always fired, even after a drag/flick."," *"," * <p>Touch based devices don't currently fire a click event,"," * if the finger has been moved (beyond a threshold) so this"," * check isn't required, if working in a purely touch based environment</p>"," *"," * @property lastScrolledAmt"," * @type Number"," * @public"," * @default 0"," */"," lastScrolledAmt: 0,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis"," *"," * @property _minScrollX"," * @type number"," * @protected"," */"," _minScrollX: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis"," *"," * @property _maxScrollX"," * @type number"," * @protected"," */"," _maxScrollX: null,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _minScrollY"," * @type number"," * @protected"," */"," _minScrollY: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _maxScrollY"," * @type number"," * @protected"," */"," _maxScrollY: null,",""," /**"," * Designated initializer"," *"," * @method initializer"," * @param {config} Configuration object for the plugin"," */"," initializer: function () {"," var sv = this;",""," // Cache these values, since they aren't going to change."," sv._bb = sv.get(BOUNDING_BOX);"," sv._cb = sv.get(CONTENT_BOX);",""," // Cache some attributes"," sv._cAxis = sv.get(AXIS);"," sv._cBounce = sv.get(BOUNCE);"," sv._cBounceRange = sv.get(BOUNCE_RANGE);"," sv._cDeceleration = sv.get(DECELERATION);"," sv._cFrameDuration = sv.get(FRAME_DURATION);"," },",""," /**"," * bindUI implementation"," *"," * Hooks up events for the widget"," * @method bindUI"," */"," bindUI: function () {"," var sv = this;",""," // Bind interaction listers"," sv._bindFlick(sv.get(FLICK));"," sv._bindDrag(sv.get(DRAG));"," sv._bindMousewheel(true);",""," // Bind change events"," sv._bindAttrs();",""," // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release."," if (IE) {"," sv._fixIESelect(sv._bb, sv._cb);"," }",""," // Set any deprecated static properties"," if (ScrollView.SNAP_DURATION) {"," sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);"," }",""," if (ScrollView.SNAP_EASING) {"," sv.set(SNAP_EASING, ScrollView.SNAP_EASING);"," }",""," if (ScrollView.EASING) {"," sv.set(EASING, ScrollView.EASING);"," }",""," if (ScrollView.FRAME_STEP) {"," sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);"," }",""," if (ScrollView.BOUNCE_RANGE) {"," sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);"," }",""," // Recalculate dimension properties"," // TODO: This should be throttled."," // Y.one(WINDOW).after('resize', sv._afterDimChange, sv);"," },",""," /**"," * Bind event listeners"," *"," * @method _bindAttrs"," * @private"," */"," _bindAttrs: function () {"," var sv = this,"," scrollChangeHandler = sv._afterScrollChange,"," dimChangeHandler = sv._afterDimChange;",""," // Bind any change event listeners"," sv.after({"," 'scrollEnd': sv._afterScrollEnd,"," 'disabledChange': sv._afterDisabledChange,"," 'flickChange': sv._afterFlickChange,"," 'dragChange': sv._afterDragChange,"," 'axisChange': sv._afterAxisChange,"," 'scrollYChange': scrollChangeHandler,"," 'scrollXChange': scrollChangeHandler,"," 'heightChange': dimChangeHandler,"," 'widthChange': dimChangeHandler"," });"," },",""," /**"," * Bind (or unbind) gesture move listeners required for drag support"," *"," * @method _bindDrag"," * @param drag {boolean} If true, the method binds listener to enable"," * drag (gesturemovestart). If false, the method unbinds gesturemove"," * listeners for drag support."," * @private"," */"," _bindDrag: function (drag) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'drag' listeners"," bb.detach(DRAG + '|*');",""," if (drag) {"," bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));"," }"," },",""," /**"," * Bind (or unbind) flick listeners."," *"," * @method _bindFlick"," * @param flick {Object|boolean} If truthy, the method binds listeners for"," * flick support. If false, the method unbinds flick listeners."," * @private"," */"," _bindFlick: function (flick) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'flick' listeners"," bb.detach(FLICK + '|*');",""," if (flick) {"," bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);",""," // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick"," sv._bindDrag(sv.get(DRAG));"," }"," },",""," /**"," * Bind (or unbind) mousewheel listeners."," *"," * @method _bindMousewheel"," * @param mousewheel {Object|boolean} If truthy, the method binds listeners for"," * mousewheel support. If false, the method unbinds mousewheel listeners."," * @private"," */"," _bindMousewheel: function (mousewheel) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'mousewheel' listeners"," // TODO: This doesn't actually appear to work properly. Fix. #2532743"," bb.detach(MOUSEWHEEL + '|*');",""," // Only enable for vertical scrollviews"," if (mousewheel) {"," // Bound to document, because that's where mousewheel events fire off of."," Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));"," }"," },",""," /**"," * syncUI implementation."," *"," * Update the scroll position, based on the current value of scrollX/scrollY."," *"," * @method syncUI"," */"," syncUI: function () {"," var sv = this,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight;",""," // If the axis is undefined, auto-calculate it"," if (sv._cAxis === undefined) {"," // This should only ever be run once (for now)."," // In the future SV might post-load axis changes"," sv._cAxis = {"," x: (scrollWidth > width),"," y: (scrollHeight > height)"," };",""," sv._set(AXIS, sv._cAxis);"," }",""," // get text direction on or inherited by scrollview node"," sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');",""," // Cache the disabled value"," sv._cDisabled = sv.get(DISABLED);",""," // Run this to set initial values"," sv._uiDimensionsChange();",""," // If we're out-of-bounds, snap back."," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," },",""," /**"," * Utility method to obtain widget dimensions"," *"," * @method _getScrollDims"," * @return {Object} The offsetWidth, offsetHeight, scrollWidth and"," * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,"," * scrollHeight]"," * @private"," */"," _getScrollDims: function () {"," var sv = this,"," cb = sv._cb,"," bb = sv._bb,"," TRANS = ScrollView._TRANSITION,"," // Ideally using CSSMatrix - don't think we have it normalized yet though."," // origX = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).e,"," // origY = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).f,"," origX = sv.get(SCROLL_X),"," origY = sv.get(SCROLL_Y),"," origHWTransform,"," dims;",""," // TODO: Is this OK? Just in case it's called 'during' a transition."," if (NATIVE_TRANSITIONS) {"," cb.setStyle(TRANS.DURATION, ZERO);"," cb.setStyle(TRANS.PROPERTY, EMPTY);"," }",""," origHWTransform = sv._forceHWTransforms;"," sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.",""," sv._moveTo(cb, 0, 0);"," dims = {"," 'offsetWidth': bb.get('offsetWidth'),"," 'offsetHeight': bb.get('offsetHeight'),"," 'scrollWidth': bb.get('scrollWidth'),"," 'scrollHeight': bb.get('scrollHeight')"," };"," sv._moveTo(cb, -(origX), -(origY));",""," sv._forceHWTransforms = origHWTransform;",""," return dims;"," },",""," /**"," * This method gets invoked whenever the height or width attributes change,"," * allowing us to determine which scrolling axes need to be enabled."," *"," * @method _uiDimensionsChange"," * @protected"," */"," _uiDimensionsChange: function () {"," var sv = this,"," bb = sv._bb,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight,"," rtl = sv.rtl,"," svAxis = sv._cAxis,"," minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),"," maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),"," minScrollY = 0,"," maxScrollY = Math.max(0, scrollHeight - height);",""," if (svAxis && svAxis.x) {"," bb.addClass(CLASS_NAMES.horizontal);"," }",""," if (svAxis && svAxis.y) {"," bb.addClass(CLASS_NAMES.vertical);"," }",""," sv._setBounds({"," minScrollX: minScrollX,"," maxScrollX: maxScrollX,"," minScrollY: minScrollY,"," maxScrollY: maxScrollY"," });"," },",""," /**"," * Set the bounding dimensions of the ScrollView"," *"," * @method _setBounds"," * @protected"," * @param bounds {Object} [duration] ms of the scroll animation. (default is 0)"," * @param {Number} [bounds.minScrollX] The minimum scroll X value"," * @param {Number} [bounds.maxScrollX] The maximum scroll X value"," * @param {Number} [bounds.minScrollY] The minimum scroll Y value"," * @param {Number} [bounds.maxScrollY] The maximum scroll Y value"," */"," _setBounds: function (bounds) {"," var sv = this;",""," // TODO: Do a check to log if the bounds are invalid",""," sv._minScrollX = bounds.minScrollX;"," sv._maxScrollX = bounds.maxScrollX;"," sv._minScrollY = bounds.minScrollY;"," sv._maxScrollY = bounds.maxScrollY;"," },",""," /**"," * Get the bounding dimensions of the ScrollView"," *"," * @method _getBounds"," * @protected"," */"," _getBounds: function () {"," var sv = this;",""," return {"," minScrollX: sv._minScrollX,"," maxScrollX: sv._maxScrollX,"," minScrollY: sv._minScrollY,"," maxScrollY: sv._maxScrollY"," };",""," },",""," /**"," * Scroll the element to a given xy coordinate"," *"," * @method scrollTo"," * @param x {Number} The x-position to scroll to. (null for no movement)"," * @param y {Number} The y-position to scroll to. (null for no movement)"," * @param {Number} [duration] ms of the scroll animation. (default is 0)"," * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)"," * @param {String} [node] The node to transform. Setting this can be useful in"," * dual-axis paginated instances. (default is the instance's contentBox)"," */"," scrollTo: function (x, y, duration, easing, node) {"," // Check to see if widget is disabled"," if (this._cDisabled) {"," return;"," }",""," var sv = this,"," cb = sv._cb,"," TRANS = ScrollView._TRANSITION,"," callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this"," newX = 0,"," newY = 0,"," transition = {},"," transform;",""," // default the optional arguments"," duration = duration || 0;"," easing = easing || sv.get(EASING); // @TODO: Cache this"," node = node || cb;",""," if (x !== null) {"," sv.set(SCROLL_X, x, {src:UI});"," newX = -(x);"," }",""," if (y !== null) {"," sv.set(SCROLL_Y, y, {src:UI});"," newY = -(y);"," }",""," transform = sv._transform(newX, newY);",""," if (NATIVE_TRANSITIONS) {"," // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one."," node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);"," }",""," // Move"," if (duration === 0) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', transform);"," }"," else {"," // TODO: If both set, batch them in the same update"," // Update: Nope, setStyles() just loops through each property and applies it."," if (x !== null) {"," node.setStyle(LEFT, newX + PX);"," }"," if (y !== null) {"," node.setStyle(TOP, newY + PX);"," }"," }"," }",""," // Animate"," else {"," transition.easing = easing;"," transition.duration = duration / 1000;",""," if (NATIVE_TRANSITIONS) {"," transition.transform = transform;"," }"," else {"," transition.left = newX + PX;"," transition.top = newY + PX;"," }",""," node.transition(transition, callback);"," }"," },",""," /**"," * Utility method, to create the translate transform string with the"," * x, y translation amounts provided."," *"," * @method _transform"," * @param {Number} x Number of pixels to translate along the x axis"," * @param {Number} y Number of pixels to translate along the y axis"," * @private"," */"," _transform: function (x, y) {"," // TODO: Would we be better off using a Matrix for this?"," var prop = 'translate(' + x + 'px, ' + y + 'px)';",""," if (this._forceHWTransforms) {"," prop += ' translateZ(0)';"," }",""," return prop;"," },",""," /**"," * Utility method, to move the given element to the given xy position"," *"," * @method _moveTo"," * @param node {Node} The node to move"," * @param x {Number} The x-position to move to"," * @param y {Number} The y-position to move to"," * @private"," */"," _moveTo : function(node, x, y) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', this._transform(x, y));"," } else {"," node.setStyle(LEFT, x + PX);"," node.setStyle(TOP, y + PX);"," }"," },","",""," /**"," * Content box transition callback"," *"," * @method _onTransEnd"," * @param {Event.Facade} e The event facade"," * @private"," */"," _onTransEnd: function () {"," var sv = this;",""," // If for some reason we're OOB, snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," else {"," /**"," * Notification event fired at the end of a scroll transition"," *"," * @event scrollEnd"," * @param e {EventFacade} The default event facade."," */"," sv.fire(EV_SCROLL_END);"," }"," },",""," /**"," * gesturemovestart event handler"," *"," * @method _onGestureMoveStart"," * @param e {Event.Facade} The gesturemovestart event facade"," * @private"," */"," _onGestureMoveStart: function (e) {",""," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," bb = sv._bb,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.start) {"," e.preventDefault();"," }",""," // if a flick animation is in progress, cancel it"," if (sv._flickAnim) {"," sv._cancelFlick();"," sv._onTransEnd();"," }",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Stores data for this gesture cycle. Cleaned up later"," sv._gesture = {",""," // Will hold the axis value"," axis: null,",""," // The current attribute values"," startX: currentX,"," startY: currentY,",""," // The X/Y coordinates where the event began"," startClientX: clientX,"," startClientY: clientY,",""," // The X/Y coordinates where the event will end"," endClientX: null,"," endClientY: null,",""," // The current delta of the event"," deltaX: null,"," deltaY: null,",""," // Will be populated for flicks"," flick: null,",""," // Create some listeners for the rest of the gesture cycle"," onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),",""," // @TODO: Don't bind gestureMoveEnd if it's a Flick?"," onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))"," };"," },",""," /**"," * gesturemove event handler"," *"," * @method _onGestureMove"," * @param e {Event.Facade} The gesturemove event facade"," * @private"," */"," _onGestureMove: function (e) {"," var sv = this,"," gesture = sv._gesture,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," startX = gesture.startX,"," startY = gesture.startY,"," startClientX = gesture.startClientX,"," startClientY = gesture.startClientY,"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.move) {"," e.preventDefault();"," }",""," gesture.deltaX = startClientX - clientX;"," gesture.deltaY = startClientY - clientY;",""," // Determine if this is a vertical or horizontal movement"," // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent"," if (gesture.axis === null) {"," gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;"," }",""," // Move X or Y. @TODO: Move both if dualaxis."," if (gesture.axis === DIM_X && svAxisX) {"," sv.set(SCROLL_X, startX + gesture.deltaX);"," }"," else if (gesture.axis === DIM_Y && svAxisY) {"," sv.set(SCROLL_Y, startY + gesture.deltaY);"," }"," },",""," /**"," * gesturemoveend event handler"," *"," * @method _onGestureMoveEnd"," * @param e {Event.Facade} The gesturemoveend event facade"," * @private"," */"," _onGestureMoveEnd: function (e) {"," var sv = this,"," gesture = sv._gesture,"," flick = gesture.flick,"," clientX = e.clientX,"," clientY = e.clientY,"," isOOB;",""," if (sv._prevent.end) {"," e.preventDefault();"," }",""," // Store the end X/Y coordinates"," gesture.endClientX = clientX;"," gesture.endClientY = clientY;",""," // Cleanup the event handlers"," gesture.onGestureMove.detach();"," gesture.onGestureMoveEnd.detach();",""," // If this wasn't a flick, wrap up the gesture cycle"," if (!flick) {"," // @TODO: Be more intelligent about this. Look at the Flick attribute to see"," // if it is safe to assume _flick did or didn't fire."," // Then, the order _flick and _onGestureMoveEnd fire doesn't matter?",""," // If there was movement (_onGestureMove fired)"," if (gesture.deltaX !== null && gesture.deltaY !== null) {",""," isOOB = sv._isOutOfBounds();",""," // If we're out-out-bounds, then snapback"," if (isOOB) {"," sv._snapBack();"," }",""," // Inbounds"," else {"," // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's"," // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit"," if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {"," sv._onTransEnd();"," }"," }"," }"," }"," },",""," /**"," * Execute a flick at the end of a scroll action"," *"," * @method _flick"," * @param e {Event.Facade} The Flick event facade"," * @private"," */"," _flick: function (e) {"," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," svAxis = sv._cAxis,"," flick = e.flick,"," flickAxis = flick.axis,"," flickVelocity = flick.velocity,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," startPosition = sv.get(axisAttr);",""," // Sometimes flick is enabled, but drag is disabled"," if (sv._gesture) {"," sv._gesture.flick = flick;"," }",""," // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis"," if (svAxis[flickAxis]) {"," sv._flickFrame(flickVelocity, flickAxis, startPosition);"," }"," },",""," /**"," * Execute a single frame in the flick animation"," *"," * @method _flickFrame"," * @param velocity {Number} The velocity of this animated frame"," * @param flickAxis {String} The axis on which to animate"," * @param startPosition {Number} The starting X/Y point to flick from"," * @protected"," */"," _flickFrame: function (velocity, flickAxis, startPosition) {",""," var sv = this,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," bounds = sv._getBounds(),",""," // Localize cached values"," bounce = sv._cBounce,"," bounceRange = sv._cBounceRange,"," deceleration = sv._cDeceleration,"," frameDuration = sv._cFrameDuration,",""," // Calculate"," newVelocity = velocity * deceleration,"," newPosition = startPosition - (frameDuration * newVelocity),",""," // Some convinience conditions"," min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,"," max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,"," belowMin = (newPosition < min),"," belowMax = (newPosition < max),"," aboveMin = (newPosition > min),"," aboveMax = (newPosition > max),"," belowMinRange = (newPosition < (min - bounceRange)),"," withinMinRange = (belowMin && (newPosition > (min - bounceRange))),"," withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),"," aboveMaxRange = (newPosition > (max + bounceRange)),"," tooSlow;",""," // If we're within the range but outside min/max, dampen the velocity"," if (withinMinRange || withinMaxRange) {"," newVelocity *= bounce;"," }",""," // Is the velocity too slow to bother?"," tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);",""," // If the velocity is too slow or we're outside the range"," if (tooSlow || belowMinRange || aboveMaxRange) {"," // Cancel and delete sv._flickAnim"," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // If we're inside the scroll area, just end"," if (aboveMin && belowMax) {"," sv._onTransEnd();"," }",""," // We're outside the scroll area, so we need to snap back"," else {"," sv._snapBack();"," }"," }",""," // Otherwise, animate to the next frame"," else {"," // @TODO: maybe use requestAnimationFrame instead"," sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);"," sv.set(axisAttr, newPosition);"," }"," },",""," _cancelFlick: function () {"," var sv = this;",""," if (sv._flickAnim) {"," // Cancel the flick (if it exists)"," sv._flickAnim.cancel();",""," // Also delete it, otherwise _onGestureMoveStart will think we're still flicking"," delete sv._flickAnim;"," }",""," },",""," /**"," * Handle mousewheel events on the widget"," *"," * @method _mousewheel"," * @param e {Event.Facade} The mousewheel event facade"," * @private"," */"," _mousewheel: function (e) {"," var sv = this,"," scrollY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," bb = sv._bb,"," scrollOffset = 10, // 10px"," isForward = (e.wheelDelta > 0),"," scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);",""," scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);",""," // Because Mousewheel events fire off 'document', every ScrollView widget will react"," // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently"," // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,"," // becuase otherwise the 'prevent' will block page scrolling."," if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Jump to the new offset"," sv.set(SCROLL_Y, scrollToY);",""," // if we have scrollbars plugin, update & set the flash timer on the scrollbar"," // @TODO: This probably shouldn't be in this module"," if (sv.scrollbars) {"," // @TODO: The scrollbars should handle this themselves"," sv.scrollbars._update();"," sv.scrollbars.flash();"," // or just this"," // sv.scrollbars._hostDimensionsChange();"," }",""," // Fire the 'scrollEnd' event"," sv._onTransEnd();",""," // prevent browser default behavior on mouse scroll"," e.preventDefault();"," }"," },",""," /**"," * Checks to see the current scrollX/scrollY position beyond the min/max boundary"," *"," * @method _isOutOfBounds"," * @param x {Number} [optional] The X position to check"," * @param y {Number} [optional] The Y position to check"," * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false)"," * @private"," */"," _isOutOfBounds: function (x, y) {"," var sv = this,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," currentX = x || sv.get(SCROLL_X),"," currentY = y || sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY;",""," return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));"," },",""," /**"," * Bounces back"," * @TODO: Should be more generalized and support both X and Y detection"," *"," * @method _snapBack"," * @private"," */"," _snapBack: function () {"," var sv = this,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY,"," newY = _constrain(currentY, minY, maxY),"," newX = _constrain(currentX, minX, maxX),"," duration = sv.get(SNAP_DURATION),"," easing = sv.get(SNAP_EASING);",""," if (newX !== currentX) {"," sv.set(SCROLL_X, newX, {duration:duration, easing:easing});"," }"," else if (newY !== currentY) {"," sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});"," }"," else {"," sv._onTransEnd();"," }"," },",""," /**"," * After listener for changes to the scrollX or scrollY attribute"," *"," * @method _afterScrollChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollChange: function (e) {"," if (e.src === ScrollView.UI_SRC) {"," return false;"," }",""," var sv = this,"," duration = e.duration,"," easing = e.easing,"," val = e.newVal,"," scrollToArgs = [];",""," // Set the scrolled value"," sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);",""," // Generate the array of args to pass to scrollTo()"," if (e.attrName === SCROLL_X) {"," scrollToArgs.push(val);"," scrollToArgs.push(sv.get(SCROLL_Y));"," }"," else {"," scrollToArgs.push(sv.get(SCROLL_X));"," scrollToArgs.push(val);"," }",""," scrollToArgs.push(duration);"," scrollToArgs.push(easing);",""," sv.scrollTo.apply(sv, scrollToArgs);"," },",""," /**"," * After listener for changes to the flick attribute"," *"," * @method _afterFlickChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterFlickChange: function (e) {"," this._bindFlick(e.newVal);"," },",""," /**"," * After listener for changes to the disabled attribute"," *"," * @method _afterDisabledChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDisabledChange: function (e) {"," // Cache for performance - we check during move"," this._cDisabled = e.newVal;"," },",""," /**"," * After listener for the axis attribute"," *"," * @method _afterAxisChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterAxisChange: function (e) {"," this._cAxis = e.newVal;"," },",""," /**"," * After listener for changes to the drag attribute"," *"," * @method _afterDragChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDragChange: function (e) {"," this._bindDrag(e.newVal);"," },",""," /**"," * After listener for the height or width attribute"," *"," * @method _afterDimChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDimChange: function () {"," this._uiDimensionsChange();"," },",""," /**"," * After listener for scrollEnd, for cleanup"," *"," * @method _afterScrollEnd"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollEnd: function () {"," var sv = this;",""," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // Ideally this should be removed, but doing so causing some JS errors with fast swiping"," // because _gesture is being deleted after the previous one has been overwritten"," // delete sv._gesture; // TODO: Move to sv.prevGesture?"," },",""," /**"," * Setter for 'axis' attribute"," *"," * @method _axisSetter"," * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on"," * @param name {String} The attribute name"," * @return {Object} An object to specify scrollability on the x & y axes"," *"," * @protected"," */"," _axisSetter: function (val) {",""," // Turn a string into an axis object"," if (Y.Lang.isString(val)) {"," return {"," x: val.match(/x/i) ? true : false,"," y: val.match(/y/i) ? true : false"," };"," }"," },",""," /**"," * The scrollX, scrollY setter implementation"," *"," * @method _setScroll"," * @private"," * @param {Number} val"," * @param {String} dim"," *"," * @return {Number} The value"," */"," _setScroll : function(val) {",""," // Just ensure the widget is not disabled"," if (this._cDisabled) {"," val = Y.Attribute.INVALID_VALUE;"," }",""," return val;"," },",""," /**"," * Setter for the scrollX attribute"," *"," * @method _setScrollX"," * @param val {Number} The new scrollX value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollX: function(val) {"," return this._setScroll(val, DIM_X);"," },",""," /**"," * Setter for the scrollY ATTR"," *"," * @method _setScrollY"," * @param val {Number} The new scrollY value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollY: function(val) {"," return this._setScroll(val, DIM_Y);"," }",""," // End prototype properties","","}, {",""," // Static properties",""," /**"," * The identity of the widget."," *"," * @property NAME"," * @type String"," * @default 'scrollview'"," * @readOnly"," * @protected"," * @static"," */"," NAME: 'scrollview',",""," /**"," * Static property used to define the default attribute configuration of"," * the Widget."," *"," * @property ATTRS"," * @type {Object}"," * @protected"," * @static"," */"," ATTRS: {",""," /**"," * Specifies ability to scroll on x, y, or x and y axis/axes."," *"," * @attribute axis"," * @type String"," */"," axis: {"," setter: '_axisSetter',"," writeOnce: 'initOnly'"," },",""," /**"," * The current scroll position in the x-axis"," *"," * @attribute scrollX"," * @type Number"," * @default 0"," */"," scrollX: {"," value: 0,"," setter: '_setScrollX'"," },",""," /**"," * The current scroll position in the y-axis"," *"," * @attribute scrollY"," * @type Number"," * @default 0"," */"," scrollY: {"," value: 0,"," setter: '_setScrollY'"," },",""," /**"," * Drag coefficent for inertial scrolling. The closer to 1 this"," * value is, the less friction during scrolling."," *"," * @attribute deceleration"," * @default 0.93"," */"," deceleration: {"," value: 0.93"," },",""," /**"," * Drag coefficient for intertial scrolling at the upper"," * and lower boundaries of the scrollview. Set to 0 to"," * disable \"rubber-banding\"."," *"," * @attribute bounce"," * @type Number"," * @default 0.1"," */"," bounce: {"," value: 0.1"," },",""," /**"," * The minimum distance and/or velocity which define a flick. Can be set to false,"," * to disable flick support (note: drag support is enabled/disabled separately)"," *"," * @attribute flick"," * @type Object"," * @default Object with properties minDistance = 10, minVelocity = 0.3."," */"," flick: {"," value: {"," minDistance: 10,"," minVelocity: 0.3"," }"," },",""," /**"," * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)"," * @attribute drag"," * @type boolean"," * @default true"," */"," drag: {"," value: true"," },",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @attribute snapDuration"," * @type Number"," * @default 400"," */"," snapDuration: {"," value: 400"," },",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @attribute snapEasing"," * @type String"," * @default 'ease-out'"," */"," snapEasing: {"," value: 'ease-out'"," },",""," /**"," * The default easing used when animating the flick"," *"," * @attribute easing"," * @type String"," * @default 'cubic-bezier(0, 0.1, 0, 1.0)'"," */"," easing: {"," value: 'cubic-bezier(0, 0.1, 0, 1.0)'"," },",""," /**"," * The interval (ms) used when animating the flick for JS-timer animations"," *"," * @attribute frameDuration"," * @type Number"," * @default 15"," */"," frameDuration: {"," value: 15"," },",""," /**"," * The default bounce distance in pixels"," *"," * @attribute bounceRange"," * @type Number"," * @default 150"," */"," bounceRange: {"," value: 150"," }"," },",""," /**"," * List of class names used in the scrollview's DOM"," *"," * @property CLASS_NAMES"," * @type Object"," * @static"," */"," CLASS_NAMES: CLASS_NAMES,",""," /**"," * Flag used to source property changes initiated from the DOM"," *"," * @property UI_SRC"," * @type String"," * @static"," * @default 'ui'"," */"," UI_SRC: UI,",""," /**"," * Object map of style property names used to set transition properties."," * Defaults to the vendor prefix established by the Transition module."," * The configured property names are `_TRANSITION.DURATION` (e.g. \"WebkitTransitionDuration\") and"," * `_TRANSITION.PROPERTY (e.g. \"WebkitTransitionProperty\")."," *"," * @property _TRANSITION"," * @private"," */"," _TRANSITION: {"," DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),"," PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')"," },",""," /**"," * The default bounce distance in pixels"," *"," * @property BOUNCE_RANGE"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," BOUNCE_RANGE: false,",""," /**"," * The interval (ms) used when animating the flick"," *"," * @property FRAME_STEP"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," FRAME_STEP: false,",""," /**"," * The default easing used when animating the flick"," *"," * @property EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," EASING: false,",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @property SNAP_EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_EASING: false,",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @property SNAP_DURATION"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_DURATION: false",""," // End static properties","","});","","","}, '@VERSION@', {\"requires\": [\"widget\", \"event-gestures\", \"event-mousewheel\", \"transition\"], \"skinnable\": true});","","}());"]}; } var __cov_cyIK2vRXoVgOuWid4NBKqw = __coverage__['build/scrollview-base/scrollview-base.js']; __cov_cyIK2vRXoVgOuWid4NBKqw.s['1']++;YUI.add('scrollview-base',function(Y,NAME){__cov_cyIK2vRXoVgOuWid4NBKqw.f['1']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['2']++;var getClassName=Y.ClassNameManager.getClassName,DOCUMENT=Y.config.doc,IE=Y.UA.ie,NATIVE_TRANSITIONS=Y.Transition.useNative,vendorPrefix=Y.Transition._VENDOR_PREFIX,SCROLLVIEW='scrollview',CLASS_NAMES={vertical:getClassName(SCROLLVIEW,'vert'),horizontal:getClassName(SCROLLVIEW,'horiz')},EV_SCROLL_END='scrollEnd',FLICK='flick',DRAG='drag',MOUSEWHEEL='mousewheel',UI='ui',TOP='top',LEFT='left',PX='px',AXIS='axis',SCROLL_Y='scrollY',SCROLL_X='scrollX',BOUNCE='bounce',DISABLED='disabled',DECELERATION='deceleration',DIM_X='x',DIM_Y='y',BOUNDING_BOX='boundingBox',CONTENT_BOX='contentBox',GESTURE_MOVE='gesturemove',START='start',END='end',EMPTY='',ZERO='0s',SNAP_DURATION='snapDuration',SNAP_EASING='snapEasing',EASING='easing',FRAME_DURATION='frameDuration',BOUNCE_RANGE='bounceRange',_constrain=function(val,min,max){__cov_cyIK2vRXoVgOuWid4NBKqw.f['2']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['3']++;return Math.min(Math.max(val,min),max);};__cov_cyIK2vRXoVgOuWid4NBKqw.s['4']++;function ScrollView(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['3']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['5']++;ScrollView.superclass.constructor.apply(this,arguments);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['6']++;Y.ScrollView=Y.extend(ScrollView,Y.Widget,{_forceHWTransforms:Y.UA.webkit?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][1]++,false),_prevent:{start:false,move:true,end:false},lastScrolledAmt:0,_minScrollX:null,_maxScrollX:null,_minScrollY:null,_maxScrollY:null,initializer:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['4']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['7']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['8']++;sv._bb=sv.get(BOUNDING_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['9']++;sv._cb=sv.get(CONTENT_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['10']++;sv._cAxis=sv.get(AXIS);__cov_cyIK2vRXoVgOuWid4NBKqw.s['11']++;sv._cBounce=sv.get(BOUNCE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['12']++;sv._cBounceRange=sv.get(BOUNCE_RANGE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['13']++;sv._cDeceleration=sv.get(DECELERATION);__cov_cyIK2vRXoVgOuWid4NBKqw.s['14']++;sv._cFrameDuration=sv.get(FRAME_DURATION);},bindUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['5']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['15']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['16']++;sv._bindFlick(sv.get(FLICK));__cov_cyIK2vRXoVgOuWid4NBKqw.s['17']++;sv._bindDrag(sv.get(DRAG));__cov_cyIK2vRXoVgOuWid4NBKqw.s['18']++;sv._bindMousewheel(true);__cov_cyIK2vRXoVgOuWid4NBKqw.s['19']++;sv._bindAttrs();__cov_cyIK2vRXoVgOuWid4NBKqw.s['20']++;if(IE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['21']++;sv._fixIESelect(sv._bb,sv._cb);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['22']++;if(ScrollView.SNAP_DURATION){__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['23']++;sv.set(SNAP_DURATION,ScrollView.SNAP_DURATION);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['24']++;if(ScrollView.SNAP_EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['25']++;sv.set(SNAP_EASING,ScrollView.SNAP_EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['26']++;if(ScrollView.EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['27']++;sv.set(EASING,ScrollView.EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['28']++;if(ScrollView.FRAME_STEP){__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['29']++;sv.set(FRAME_DURATION,ScrollView.FRAME_STEP);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['30']++;if(ScrollView.BOUNCE_RANGE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['31']++;sv.set(BOUNCE_RANGE,ScrollView.BOUNCE_RANGE);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][1]++;}},_bindAttrs:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['6']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['32']++;var sv=this,scrollChangeHandler=sv._afterScrollChange,dimChangeHandler=sv._afterDimChange;__cov_cyIK2vRXoVgOuWid4NBKqw.s['33']++;sv.after({'scrollEnd':sv._afterScrollEnd,'disabledChange':sv._afterDisabledChange,'flickChange':sv._afterFlickChange,'dragChange':sv._afterDragChange,'axisChange':sv._afterAxisChange,'scrollYChange':scrollChangeHandler,'scrollXChange':scrollChangeHandler,'heightChange':dimChangeHandler,'widthChange':dimChangeHandler});},_bindDrag:function(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.f['7']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['34']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['35']++;bb.detach(DRAG+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['36']++;if(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['37']++;bb.on(DRAG+'|'+GESTURE_MOVE+START,Y.bind(sv._onGestureMoveStart,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][1]++;}},_bindFlick:function(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.f['8']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['38']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['39']++;bb.detach(FLICK+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['40']++;if(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['41']++;bb.on(FLICK+'|'+FLICK,Y.bind(sv._flick,sv),flick);__cov_cyIK2vRXoVgOuWid4NBKqw.s['42']++;sv._bindDrag(sv.get(DRAG));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][1]++;}},_bindMousewheel:function(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.f['9']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['43']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['44']++;bb.detach(MOUSEWHEEL+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['45']++;if(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['46']++;Y.one(DOCUMENT).on(MOUSEWHEEL,Y.bind(sv._mousewheel,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][1]++;}},syncUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['10']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['47']++;var sv=this,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight;__cov_cyIK2vRXoVgOuWid4NBKqw.s['48']++;if(sv._cAxis===undefined){__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['49']++;sv._cAxis={x:scrollWidth>width,y:scrollHeight>height};__cov_cyIK2vRXoVgOuWid4NBKqw.s['50']++;sv._set(AXIS,sv._cAxis);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['51']++;sv.rtl=sv._cb.getComputedStyle('direction')==='rtl';__cov_cyIK2vRXoVgOuWid4NBKqw.s['52']++;sv._cDisabled=sv.get(DISABLED);__cov_cyIK2vRXoVgOuWid4NBKqw.s['53']++;sv._uiDimensionsChange();__cov_cyIK2vRXoVgOuWid4NBKqw.s['54']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['55']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][1]++;}},_getScrollDims:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['11']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['56']++;var sv=this,cb=sv._cb,bb=sv._bb,TRANS=ScrollView._TRANSITION,origX=sv.get(SCROLL_X),origY=sv.get(SCROLL_Y),origHWTransform,dims;__cov_cyIK2vRXoVgOuWid4NBKqw.s['57']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['58']++;cb.setStyle(TRANS.DURATION,ZERO);__cov_cyIK2vRXoVgOuWid4NBKqw.s['59']++;cb.setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['60']++;origHWTransform=sv._forceHWTransforms;__cov_cyIK2vRXoVgOuWid4NBKqw.s['61']++;sv._forceHWTransforms=false;__cov_cyIK2vRXoVgOuWid4NBKqw.s['62']++;sv._moveTo(cb,0,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['63']++;dims={'offsetWidth':bb.get('offsetWidth'),'offsetHeight':bb.get('offsetHeight'),'scrollWidth':bb.get('scrollWidth'),'scrollHeight':bb.get('scrollHeight')};__cov_cyIK2vRXoVgOuWid4NBKqw.s['64']++;sv._moveTo(cb,-origX,-origY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['65']++;sv._forceHWTransforms=origHWTransform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['66']++;return dims;},_uiDimensionsChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['12']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['67']++;var sv=this,bb=sv._bb,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight,rtl=sv.rtl,svAxis=sv._cAxis,minScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][0]++,Math.min(0,-(scrollWidth-width))):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][1]++,0),maxScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][0]++,0):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][1]++,Math.max(0,scrollWidth-width)),minScrollY=0,maxScrollY=Math.max(0,scrollHeight-height);__cov_cyIK2vRXoVgOuWid4NBKqw.s['68']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][1]++,svAxis.x)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['69']++;bb.addClass(CLASS_NAMES.horizontal);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['70']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][1]++,svAxis.y)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['71']++;bb.addClass(CLASS_NAMES.vertical);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['72']++;sv._setBounds({minScrollX:minScrollX,maxScrollX:maxScrollX,minScrollY:minScrollY,maxScrollY:maxScrollY});},_setBounds:function(bounds){__cov_cyIK2vRXoVgOuWid4NBKqw.f['13']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['73']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['74']++;sv._minScrollX=bounds.minScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['75']++;sv._maxScrollX=bounds.maxScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['76']++;sv._minScrollY=bounds.minScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['77']++;sv._maxScrollY=bounds.maxScrollY;},_getBounds:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['14']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['78']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['79']++;return{minScrollX:sv._minScrollX,maxScrollX:sv._maxScrollX,minScrollY:sv._minScrollY,maxScrollY:sv._maxScrollY};},scrollTo:function(x,y,duration,easing,node){__cov_cyIK2vRXoVgOuWid4NBKqw.f['15']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['80']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['81']++;return;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['82']++;var sv=this,cb=sv._cb,TRANS=ScrollView._TRANSITION,callback=Y.bind(sv._onTransEnd,sv),newX=0,newY=0,transition={},transform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['83']++;duration=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][0]++,duration)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][1]++,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['84']++;easing=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][0]++,easing)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][1]++,sv.get(EASING));__cov_cyIK2vRXoVgOuWid4NBKqw.s['85']++;node=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][0]++,node)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][1]++,cb);__cov_cyIK2vRXoVgOuWid4NBKqw.s['86']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['87']++;sv.set(SCROLL_X,x,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['88']++;newX=-x;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['89']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['90']++;sv.set(SCROLL_Y,y,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['91']++;newY=-y;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['92']++;transform=sv._transform(newX,newY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['93']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['94']++;node.setStyle(TRANS.DURATION,ZERO).setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['95']++;if(duration===0){__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['96']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['97']++;node.setStyle('transform',transform);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['98']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['99']++;node.setStyle(LEFT,newX+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['100']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['101']++;node.setStyle(TOP,newY+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['102']++;transition.easing=easing;__cov_cyIK2vRXoVgOuWid4NBKqw.s['103']++;transition.duration=duration/1000;__cov_cyIK2vRXoVgOuWid4NBKqw.s['104']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['105']++;transition.transform=transform;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['106']++;transition.left=newX+PX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['107']++;transition.top=newY+PX;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['108']++;node.transition(transition,callback);}},_transform:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['16']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['109']++;var prop='translate('+x+'px, '+y+'px)';__cov_cyIK2vRXoVgOuWid4NBKqw.s['110']++;if(this._forceHWTransforms){__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['111']++;prop+=' translateZ(0)';}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['112']++;return prop;},_moveTo:function(node,x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['17']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['113']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['114']++;node.setStyle('transform',this._transform(x,y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['115']++;node.setStyle(LEFT,x+PX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['116']++;node.setStyle(TOP,y+PX);}},_onTransEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['18']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['117']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['118']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['119']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['120']++;sv.fire(EV_SCROLL_END);}},_onGestureMoveStart:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['19']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['121']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['122']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['123']++;var sv=this,bb=sv._bb,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['124']++;if(sv._prevent.start){__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['125']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['126']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['127']++;sv._cancelFlick();__cov_cyIK2vRXoVgOuWid4NBKqw.s['128']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['129']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['130']++;sv._gesture={axis:null,startX:currentX,startY:currentY,startClientX:clientX,startClientY:clientY,endClientX:null,endClientY:null,deltaX:null,deltaY:null,flick:null,onGestureMove:bb.on(DRAG+'|'+GESTURE_MOVE,Y.bind(sv._onGestureMove,sv)),onGestureMoveEnd:bb.on(DRAG+'|'+GESTURE_MOVE+END,Y.bind(sv._onGestureMoveEnd,sv))};},_onGestureMove:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['20']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['131']++;var sv=this,gesture=sv._gesture,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,startX=gesture.startX,startY=gesture.startY,startClientX=gesture.startClientX,startClientY=gesture.startClientY,clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['132']++;if(sv._prevent.move){__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['133']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['134']++;gesture.deltaX=startClientX-clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['135']++;gesture.deltaY=startClientY-clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['136']++;if(gesture.axis===null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['137']++;gesture.axis=Math.abs(gesture.deltaX)>Math.abs(gesture.deltaY)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][0]++,DIM_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][1]++,DIM_Y);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['138']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][0]++,gesture.axis===DIM_X)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][1]++,svAxisX)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['139']++;sv.set(SCROLL_X,startX+gesture.deltaX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['140']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][0]++,gesture.axis===DIM_Y)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][1]++,svAxisY)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['141']++;sv.set(SCROLL_Y,startY+gesture.deltaY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][1]++;}}},_onGestureMoveEnd:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['21']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['142']++;var sv=this,gesture=sv._gesture,flick=gesture.flick,clientX=e.clientX,clientY=e.clientY,isOOB;__cov_cyIK2vRXoVgOuWid4NBKqw.s['143']++;if(sv._prevent.end){__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['144']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['145']++;gesture.endClientX=clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['146']++;gesture.endClientY=clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['147']++;gesture.onGestureMove.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['148']++;gesture.onGestureMoveEnd.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['149']++;if(!flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['150']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][0]++,gesture.deltaX!==null)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][1]++,gesture.deltaY!==null)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['151']++;isOOB=sv._isOutOfBounds();__cov_cyIK2vRXoVgOuWid4NBKqw.s['152']++;if(isOOB){__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['153']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['154']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][0]++,!sv.pages)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][1]++,sv.pages)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][2]++,!sv.pages.get(AXIS)[gesture.axis])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['155']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][1]++;}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][1]++;}},_flick:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['22']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['156']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['157']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['158']++;var sv=this,svAxis=sv._cAxis,flick=e.flick,flickAxis=flick.axis,flickVelocity=flick.velocity,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][1]++,SCROLL_Y),startPosition=sv.get(axisAttr);__cov_cyIK2vRXoVgOuWid4NBKqw.s['159']++;if(sv._gesture){__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['160']++;sv._gesture.flick=flick;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['161']++;if(svAxis[flickAxis]){__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['162']++;sv._flickFrame(flickVelocity,flickAxis,startPosition);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][1]++;}},_flickFrame:function(velocity,flickAxis,startPosition){__cov_cyIK2vRXoVgOuWid4NBKqw.f['23']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['163']++;var sv=this,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][1]++,SCROLL_Y),bounds=sv._getBounds(),bounce=sv._cBounce,bounceRange=sv._cBounceRange,deceleration=sv._cDeceleration,frameDuration=sv._cFrameDuration,newVelocity=velocity*deceleration,newPosition=startPosition-frameDuration*newVelocity,min=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][0]++,bounds.minScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][1]++,bounds.minScrollY),max=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][0]++,bounds.maxScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][1]++,bounds.maxScrollY),belowMin=newPosition<min,belowMax=newPosition<max,aboveMin=newPosition>min,aboveMax=newPosition>max,belowMinRange=newPosition<min-bounceRange,withinMinRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][0]++,belowMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][1]++,newPosition>min-bounceRange),withinMaxRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][0]++,aboveMax)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][1]++,newPosition<max+bounceRange),aboveMaxRange=newPosition>max+bounceRange,tooSlow;__cov_cyIK2vRXoVgOuWid4NBKqw.s['164']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][0]++,withinMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][1]++,withinMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['165']++;newVelocity*=bounce;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['166']++;tooSlow=Math.abs(newVelocity).toFixed(4)<0.015;__cov_cyIK2vRXoVgOuWid4NBKqw.s['167']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][0]++,tooSlow)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][1]++,belowMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][2]++,aboveMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['168']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['169']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['170']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][0]++,aboveMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][1]++,belowMax)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['171']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['172']++;sv._snapBack();}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['173']++;sv._flickAnim=Y.later(frameDuration,sv,'_flickFrame',[newVelocity,flickAxis,newPosition]);__cov_cyIK2vRXoVgOuWid4NBKqw.s['174']++;sv.set(axisAttr,newPosition);}},_cancelFlick:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['24']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['175']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['176']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['177']++;sv._flickAnim.cancel();__cov_cyIK2vRXoVgOuWid4NBKqw.s['178']++;delete sv._flickAnim;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][1]++;}},_mousewheel:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['25']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['179']++;var sv=this,scrollY=sv.get(SCROLL_Y),bounds=sv._getBounds(),bb=sv._bb,scrollOffset=10,isForward=e.wheelDelta>0,scrollToY=scrollY-(isForward?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][0]++,1):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][1]++,-1))*scrollOffset;__cov_cyIK2vRXoVgOuWid4NBKqw.s['180']++;scrollToY=_constrain(scrollToY,bounds.minScrollY,bounds.maxScrollY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['181']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][0]++,bb.contains(e.target))&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][1]++,sv._cAxis[DIM_Y])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['182']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['183']++;sv.set(SCROLL_Y,scrollToY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['184']++;if(sv.scrollbars){__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['185']++;sv.scrollbars._update();__cov_cyIK2vRXoVgOuWid4NBKqw.s['186']++;sv.scrollbars.flash();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['187']++;sv._onTransEnd();__cov_cyIK2vRXoVgOuWid4NBKqw.s['188']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][1]++;}},_isOutOfBounds:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['26']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['189']++;var sv=this,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,currentX=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][0]++,x)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][1]++,sv.get(SCROLL_X)),currentY=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][0]++,y)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][1]++,sv.get(SCROLL_Y)),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['190']++;return(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][0]++,svAxisX)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][1]++,currentX<minX)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][2]++,currentX>maxX))||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][3]++,svAxisY)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][4]++,currentY<minY)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][5]++,currentY>maxY));},_snapBack:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['27']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['191']++;var sv=this,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY,newY=_constrain(currentY,minY,maxY),newX=_constrain(currentX,minX,maxX),duration=sv.get(SNAP_DURATION),easing=sv.get(SNAP_EASING);__cov_cyIK2vRXoVgOuWid4NBKqw.s['192']++;if(newX!==currentX){__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['193']++;sv.set(SCROLL_X,newX,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['194']++;if(newY!==currentY){__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['195']++;sv.set(SCROLL_Y,newY,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['196']++;sv._onTransEnd();}}},_afterScrollChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['28']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['197']++;if(e.src===ScrollView.UI_SRC){__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['198']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['199']++;var sv=this,duration=e.duration,easing=e.easing,val=e.newVal,scrollToArgs=[];__cov_cyIK2vRXoVgOuWid4NBKqw.s['200']++;sv.lastScrolledAmt=sv.lastScrolledAmt+(e.newVal-e.prevVal);__cov_cyIK2vRXoVgOuWid4NBKqw.s['201']++;if(e.attrName===SCROLL_X){__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['202']++;scrollToArgs.push(val);__cov_cyIK2vRXoVgOuWid4NBKqw.s['203']++;scrollToArgs.push(sv.get(SCROLL_Y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['204']++;scrollToArgs.push(sv.get(SCROLL_X));__cov_cyIK2vRXoVgOuWid4NBKqw.s['205']++;scrollToArgs.push(val);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['206']++;scrollToArgs.push(duration);__cov_cyIK2vRXoVgOuWid4NBKqw.s['207']++;scrollToArgs.push(easing);__cov_cyIK2vRXoVgOuWid4NBKqw.s['208']++;sv.scrollTo.apply(sv,scrollToArgs);},_afterFlickChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['29']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['209']++;this._bindFlick(e.newVal);},_afterDisabledChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['30']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['210']++;this._cDisabled=e.newVal;},_afterAxisChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['31']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['211']++;this._cAxis=e.newVal;},_afterDragChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['32']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['212']++;this._bindDrag(e.newVal);},_afterDimChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['33']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['213']++;this._uiDimensionsChange();},_afterScrollEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['34']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['214']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['215']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['216']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][1]++;}},_axisSetter:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['35']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['217']++;if(Y.Lang.isString(val)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['218']++;return{x:val.match(/x/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][1]++,false),y:val.match(/y/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][1]++,false)};}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][1]++;}},_setScroll:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['36']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['219']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['220']++;val=Y.Attribute.INVALID_VALUE;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['221']++;return val;},_setScrollX:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['37']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['222']++;return this._setScroll(val,DIM_X);},_setScrollY:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['38']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['223']++;return this._setScroll(val,DIM_Y);}},{NAME:'scrollview',ATTRS:{axis:{setter:'_axisSetter',writeOnce:'initOnly'},scrollX:{value:0,setter:'_setScrollX'},scrollY:{value:0,setter:'_setScrollY'},deceleration:{value:0.93},bounce:{value:0.1},flick:{value:{minDistance:10,minVelocity:0.3}},drag:{value:true},snapDuration:{value:400},snapEasing:{value:'ease-out'},easing:{value:'cubic-bezier(0, 0.1, 0, 1.0)'},frameDuration:{value:15},bounceRange:{value:150}},CLASS_NAMES:CLASS_NAMES,UI_SRC:UI,_TRANSITION:{DURATION:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][0]++,vendorPrefix+'TransitionDuration'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][1]++,'transitionDuration'),PROPERTY:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][0]++,vendorPrefix+'TransitionProperty'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][1]++,'transitionProperty')},BOUNCE_RANGE:false,FRAME_STEP:false,EASING:false,SNAP_EASING:false,SNAP_DURATION:false});},'@VERSION@',{'requires':['widget','event-gestures','event-mousewheel','transition'],'skinnable':true});
blueocean-material-icons/src/js/components/svg-icons/action/toc.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionToc = (props) => ( <SvgIcon {...props}> <path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/> </SvgIcon> ); ActionToc.displayName = 'ActionToc'; ActionToc.muiName = 'SvgIcon'; export default ActionToc;
ajax/libs/maple.js/1.2.3/maple-polyfill.min.js
emmy41124/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(a,s){if(!t[a]){if(!e[a]){var o="function"==typeof require&&require;if(!s&&o)return o(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=t[a]={exports:{}};e[a][0].call(c.exports,function(t){var n=e[a][1][t];return l(n?n:t)},c,c.exports,r,e,t,n)}return t[a].exports}for(var i="function"==typeof require&&require,a=0;a<n.length;a++)l(n[a]);return l}({1:[function(e,t,n){"use strict";var r=e(".."),l=r.Parser.prototype,i=r.tokTypes;l.isRelational=function(e){return this.type===i.relational&&this.value===e},l.expectRelational=function(e){this.isRelational(e)?this.next():this.unexpected()},l.flow_parseDeclareClass=function(e){return this.next(),this.flow_parseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},l.flow_parseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdent(),n=this.startNode(),r=this.startNode();n.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,this.expect(i.parenL);var l=this.flow_parseFunctionTypeParams();return n.params=l.params,n.rest=l.rest,this.expect(i.parenR),this.expect(i.colon),n.returnType=this.flow_parseType(),r.typeAnnotation=this.finishNode(n,"FunctionTypeAnnotation"),t.typeAnnotation=this.finishNode(r,"TypeAnnotation"),this.finishNode(t,t.type),this.semicolon(),this.finishNode(e,"DeclareFunction")},l.flow_parseDeclare=function(e){return this.type===i._class?this.flow_parseDeclareClass(e):this.type===i._function?this.flow_parseDeclareFunction(e):this.type===i._var?this.flow_parseDeclareVariable(e):this.isContextual("module")?this.flow_parseDeclareModule(e):void this.unexpected()},l.flow_parseDeclareVariable=function(e){return this.next(),e.id=this.flow_parseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},l.flow_parseDeclareModule=function(e){this.next(),e.id=this.type===i.string?this.parseExprAtom():this.parseIdent();var t=e.body=this.startNode(),n=t.body=[];for(this.expect(i.braceL);this.type!==i.braceR;){var r=this.startNode();this.next(),n.push(this.flow_parseDeclare(r))}return this.expect(i.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},l.flow_parseInterfaceish=function(e,t){if(e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,e["extends"]=[],this.eat(i._extends))do e["extends"].push(this.flow_parseInterfaceExtends());while(this.eat(i.comma));e.body=this.flow_parseObjectType(t)},l.flow_parseInterfaceExtends=function(){var e=this.startNode();return e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterInstantiation():null,this.finishNode(e,"InterfaceExtends")},l.flow_parseInterface=function(e){return this.flow_parseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},l.flow_parseTypeAlias=function(e){return e.id=this.parseIdent(),e.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterDeclaration():null,this.expect(i.eq),e.right=this.flow_parseType(),this.semicolon(),this.finishNode(e,"TypeAlias")},l.flow_parseTypeParameterDeclaration=function(){var e=this.startNode();for(e.params=[],this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flow_parseTypeAnnotatableIdentifier()),this.isRelational(">")||this.expect(i.comma);return this.expectRelational(">"),this.finishNode(e,"TypeParameterDeclaration")},l.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(i.comma);return this.expectRelational(">"),this.inType=t,this.finishNode(e,"TypeParameterInstantiation")},l.flow_parseObjectPropertyKey=function(){return this.type===i.num||this.type===i.string?this.parseExprAtom():this.parseIdent(!0)},l.flow_parseObjectTypeIndexer=function(e,t){return e["static"]=t,this.expect(i.bracketL),e.id=this.flow_parseObjectPropertyKey(),this.expect(i.colon),e.key=this.flow_parseType(),this.expect(i.bracketR),this.expect(i.colon),e.value=this.flow_parseType(),this.flow_objectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},l.flow_parseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flow_parseTypeParameterDeclaration()),this.expect(i.parenL);this.type===i.name;)e.params.push(this.flow_parseFunctionTypeParam()),this.type!==i.parenR&&this.expect(i.comma);return this.eat(i.ellipsis)&&(e.rest=this.flow_parseFunctionTypeParam()),this.expect(i.parenR),this.expect(i.colon),e.returnType=this.flow_parseType(),this.finishNode(e,"FunctionTypeAnnotation")},l.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")},l.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")},l.flow_parseObjectType=function(e){var t,n,r,l=this.startNode(),a=!1;for(l.callProperties=[],l.properties=[],l.indexers=[],this.expect(i.braceL);this.type!==i.braceR;){var s=this.markPosition();t=this.startNode(),e&&this.isContextual("static")&&(this.next(),r=!0),this.type===i.bracketL?l.indexers.push(this.flow_parseObjectTypeIndexer(t,r)):this.type===i.parenL||this.isRelational("<")?l.callProperties.push(this.flow_parseObjectTypeCallProperty(t,e)):(n=r&&this.type===i.colon?this.parseIdent():this.flow_parseObjectPropertyKey(),this.isRelational("<")||this.type===i.parenL?l.properties.push(this.flow_parseObjectTypeMethod(s,r,n)):(this.eat(i.question)&&(a=!0),this.expect(i.colon),t.key=n,t.value=this.flow_parseType(),t.optional=a,t["static"]=r,this.flow_objectTypeSemicolon(),l.properties.push(this.finishNode(t,"ObjectTypeProperty"))))}return this.expect(i.braceR),this.finishNode(l,"ObjectTypeAnnotation")},l.flow_objectTypeSemicolon=function(){this.eat(i.semi)||this.type===i.braceR||this.unexpected()},l.flow_parseGenericType=function(e,t){var n=this.startNodeAt(e);for(n.typeParameters=null,n.id=t;this.eat(i.dot);){var r=this.startNodeAt(e);r.qualification=n.id,r.id=this.parseIdent(),n.id=this.finishNode(r,"QualifiedTypeIdentifier")}return this.isRelational("<")&&(n.typeParameters=this.flow_parseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},l.flow_parseVoidType=function(){var e=this.startNode();return this.expect(i._void),this.finishNode(e,"VoidTypeAnnotation")},l.flow_parseTypeofType=function(){var e=this.startNode();return this.expect(i._typeof),e.argument=this.flow_parsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},l.flow_parseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(i.bracketL);this.pos<this.input.length&&this.type!==i.bracketR&&(e.types.push(this.flow_parseType()),this.type!==i.bracketR);)this.expect(i.comma);return this.expect(i.bracketR),this.finishNode(e,"TupleTypeAnnotation")},l.flow_parseFunctionTypeParam=function(){var e=!1,t=this.startNode();return t.name=this.parseIdent(),this.eat(i.question)&&(e=!0),this.expect(i.colon),t.optional=e,t.typeAnnotation=this.flow_parseType(),this.finishNode(t,"FunctionTypeParam")},l.flow_parseFunctionTypeParams=function(){for(var e={params:[],rest:null};this.type===i.name;)e.params.push(this.flow_parseFunctionTypeParam()),this.type!==i.parenR&&this.expect(i.comma);return this.eat(i.ellipsis)&&(e.rest=this.flow_parseFunctionTypeParam()),e},l.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)}},l.flow_parsePrimaryType=function(){var e,t,n,r=this.markPosition(),l=this.startNode(),a=!1;switch(this.type){case i.name:return this.flow_identToTypeAnnotation(r,l,this.parseIdent());case i.braceL:return this.flow_parseObjectType();case i.bracketL:return this.flow_parseTupleType();case i.relational:if("<"===this.value)return l.typeParameters=this.flow_parseTypeParameterDeclaration(),this.expect(i.parenL),e=this.flow_parseFunctionTypeParams(),l.params=e.params,l.rest=e.rest,this.expect(i.parenR),this.expect(i.arrow),l.returnType=this.flow_parseType(),this.finishNode(l,"FunctionTypeAnnotation");case i.parenL:if(this.next(),this.type!==i.parenR&&this.type!==i.ellipsis)if(this.type===i.name){var t=this.lookahead().type;a=t!==i.question&&t!==i.colon}else a=!0;return a?(n=this.flow_parseType(),this.expect(i.parenR),this.eat(i.arrow)&&this.raise(l,"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(),l.params=e.params,l.rest=e.rest,this.expect(i.parenR),this.expect(i.arrow),l.returnType=this.flow_parseType(),l.typeParameters=null,this.finishNode(l,"FunctionTypeAnnotation"));case i.string:return l.value=this.value,l.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(l,"StringLiteralTypeAnnotation");default:if(this.type.keyword)switch(this.type.keyword){case"void":return this.flow_parseVoidType();case"typeof":return this.flow_parseTypeofType()}}this.unexpected()},l.flow_parsePostfixType=function(){var e=this.startNode(),t=e.elementType=this.flow_parsePrimaryType();return this.type===i.bracketL?(this.expect(i.bracketL),this.expect(i.bracketR),this.finishNode(e,"ArrayTypeAnnotation")):t},l.flow_parsePrefixType=function(){var e=this.startNode();return this.eat(i.question)?(e.typeAnnotation=this.flow_parsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flow_parsePostfixType()},l.flow_parseIntersectionType=function(){var e=this.startNode(),t=this.flow_parsePrefixType();for(e.types=[t];this.eat(i.bitwiseAND);)e.types.push(this.flow_parsePrefixType());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},l.flow_parseUnionType=function(){var e=this.startNode(),t=this.flow_parseIntersectionType();for(e.types=[t];this.eat(i.bitwiseOR);)e.types.push(this.flow_parseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},l.flow_parseType=function(){var e=this.inType;this.inType=!0;var t=this.flow_parseUnionType();return this.inType=e,t},l.flow_parseTypeAnnotation=function(){var e=this.startNode(),t=this.inType;return this.inType=!0,this.expect(i.colon),e.typeAnnotation=this.flow_parseType(),this.inType=t,this.finishNode(e,"TypeAnnotation")},l.flow_parseTypeAnnotatableIdentifier=function(e,t){var n=(this.startNode(),this.parseIdent()),r=!1;return t&&this.eat(i.question)&&(this.expect(i.question),r=!0),(e||this.type===i.colon)&&(n.typeAnnotation=this.flow_parseTypeAnnotation(),this.finishNode(n,n.type)),r&&(n.optional=!0,this.finishNode(n,n.type)),n},r.plugins.flow=function(e){e.extend("parseFunctionBody",function(e){return function(t,n){return this.type===i.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===i.name&&"interface"===this.value){var r=this.startNode();return this.next(),this.flow_parseInterface(r)}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===i._class||this.type===i.name||this.type===i._function||this.type===i._var)return this.flow_parseDeclare(t)}else if(this.type===i.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(e){return function(e,t){if(this.type===i.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(i.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 a=i.expression;a.typeAnnotation=i.typeAnnotation,n[l]=a}}return e.call(this,t,n,r)}}),e.extend("parseClassProperty",function(e){return function(t){return this.type===i.colon&&(t.typeAnnotation=this.flow_parseTypeAnnotation()),e.call(this,t)}}),e.extend("isClassProperty",function(e){return function(){return this.type===i.colon||e.call(this)}}),e.extend("parseClassMethod",function(e){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 r=t["implements"]=[];do{var t=this.startNode();t.id=this.parseIdent(),t.typeParameters=this.isRelational("<")?this.flow_parseTypeParameterInstantiation():null,r.push(this.finishNode(t,"ClassImplements"))}while(this.eat(i.comma))}}}),e.extend("parseObjPropValue",function(e){return function(t){var n;this.isRelational("<")&&(n=this.flow_parseTypeParameterDeclaration(),this.type!==i.parenL&&this.unexpected()),e.apply(this,arguments),t.value.typeParameters=n}}),e.extend("parseAssignableListItemTypes",function(e){return function(e){return this.eat(i.question)&&(e.optional=!0),this.type===i.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(),r=this.parseIdent();if(this.type===i.name&&"from"!==this.value||this.type===i.braceL||this.type===i.star)t.isType=!0;else{if(t.specifiers.push(this.parseImportSpecifierDefault(r,n)),this.isContextual("from"))return;this.eat(i.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===i.colon&&(t.id.typeAnnotation=this.flow_parseTypeAnnotation(),this.finishNode(t.id,t.id.type))}})}},{"..":5}],2:[function(e,t,n){"use strict";function r(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?r(e.object)+"."+r(e.property):void 0}var l=e(".."),i=l.tokTypes,a=l.tokContexts;a.j_oTag=new l.TokContext("<tag",!1),a.j_cTag=new l.TokContext("</tag",!1),a.j_expr=new l.TokContext("<tag>...</tag>",!0,!0),i.jsxName=new l.TokenType("jsxName"),i.jsxText=new l.TokenType("jsxText",{beforeExpr:!0}),i.jsxTagStart=new l.TokenType("jsxTagStart"),i.jsxTagEnd=new l.TokenType("jsxTagEnd"),i.jsxTagStart.updateContext=function(){this.context.push(a.j_expr),this.context.push(a.j_oTag),this.exprAllowed=!1},i.jsxTagEnd.updateContext=function(e){var t=this.context.pop();t===a.j_oTag&&e===i.slash||t===a.j_cTag?(this.context.pop(),this.exprAllowed=this.curContext()===a.j_expr):this.exprAllowed=!0};var s=l.Parser.prototype;s.jsx_readToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated JSX contents");var n=this.input.charCodeAt(this.pos);switch(n){case 60:case 123:return this.pos===this.start?60===n&&this.exprAllowed?(++this.pos,this.finishToken(i.jsxTagStart)):this.getTokenFromCode(n):(e+=this.input.slice(t,this.pos),this.finishToken(i.jsxText,e));case 38:e+=this.input.slice(t,this.pos),e+=this.jsx_readEntity(),t=this.pos;break;default:l.isNewLine(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}}},s.jsx_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;38===r?(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(i.string,t)};var o={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:"♦"},u=/^[\da-fA-F]+$/,c=/^\d+$/;s.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),u.test(t)&&(e=String.fromCharCode(parseInt(t,16)))):(t=t.substr(1),c.test(t)&&(e=String.fromCharCode(parseInt(t,10)))):e=o[t];break}t+=r}return e?e:(this.pos=l,"&")},s.jsx_readWord=function(){var e,t=this.pos;do e=this.input.charCodeAt(++this.pos);while(l.isIdentifierChar(e)||45===e);return this.finishToken(i.jsxName,this.input.slice(t,this.pos))},s.jsx_parseIdentifier=function(){var e=this.startNode();return this.type===i.jsxName?e.name=this.value:this.type.keyword?e.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")},s.jsx_parseNamespacedName=function(){var e=this.markPosition(),t=this.jsx_parseIdentifier();if(!this.eat(i.colon))return t;var n=this.startNodeAt(e);return n.namespace=t,n.name=this.jsx_parseIdentifier(),this.finishNode(n,"JSXNamespacedName")},s.jsx_parseElementName=function(){for(var e=this.markPosition(),t=this.jsx_parseNamespacedName();this.eat(i.dot);){var n=this.startNodeAt(e);n.object=t,n.property=this.jsx_parseIdentifier(),t=this.finishNode(n,"JSXMemberExpression")}return t},s.jsx_parseAttributeValue=function(){switch(this.type){case i.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 i.jsxTagStart:case i.string:return this.parseExprAtom();default:this.raise(this.start,"JSX value should be either an expression or a quoted JSX text")}},s.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")},s.jsx_parseExpressionContainer=function(){var e=this.startNode();return this.next(),e.expression=this.type===i.braceR?this.jsx_parseEmptyExpression():this.parseExpression(),this.expect(i.braceR),this.finishNode(e,"JSXExpressionContainer")},s.jsx_parseAttribute=function(){var e=this.startNode();return this.eat(i.braceL)?(this.expect(i.ellipsis),e.argument=this.parseMaybeAssign(),this.expect(i.braceR),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsx_parseNamespacedName(),e.value=this.eat(i.eq)?this.jsx_parseAttributeValue():null,this.finishNode(e,"JSXAttribute"))},s.jsx_parseOpeningElementAt=function(e){var t=this.startNodeAt(e);for(t.attributes=[],t.name=this.jsx_parseElementName();this.type!==i.slash&&this.type!==i.jsxTagEnd;)t.attributes.push(this.jsx_parseAttribute());return t.selfClosing=this.eat(i.slash),this.expect(i.jsxTagEnd),this.finishNode(t,"JSXOpeningElement")},s.jsx_parseClosingElementAt=function(e){var t=this.startNodeAt(e);return t.name=this.jsx_parseElementName(),this.expect(i.jsxTagEnd),this.finishNode(t,"JSXClosingElement")},s.jsx_parseElementAt=function(e){var t=this.startNodeAt(e),n=[],l=this.jsx_parseOpeningElementAt(e),a=null;if(!l.selfClosing){e:for(;;)switch(this.type){case i.jsxTagStart:if(e=this.markPosition(),this.next(),this.eat(i.slash)){a=this.jsx_parseClosingElementAt(e);break e}n.push(this.jsx_parseElementAt(e));break;case i.jsxText:n.push(this.parseExprAtom());break;case i.braceL:n.push(this.jsx_parseExpressionContainer());break;default:this.unexpected()}r(a.name)!==r(l.name)&&this.raise(a.start,"Expected corresponding JSX closing tag for <"+r(l.name)+">")}return t.openingElement=l,t.closingElement=a,t.children=n,this.finishNode(t,"JSXElement")},s.jsx_parseElement=function(){var e=this.markPosition();return this.next(),this.jsx_parseElementAt(e)},l.plugins.jsx=function(e){e.extend("parseExprAtom",function(e){return function(t){return this.type===i.jsxText?this.parseLiteral(this.value):this.type===i.jsxTagStart?this.jsx_parseElement():e.call(this,t)}}),e.extend("readToken",function(e){return function(t){var n=this.curContext();if(n===a.j_expr)return this.jsx_readToken();if(n===a.j_oTag||n===a.j_cTag){if(l.isIdentifierStart(t))return this.jsx_readWord();if(62==t)return++this.pos,this.finishToken(i.jsxTagEnd);if((34===t||39===t)&&n==a.j_oTag)return this.jsx_readString(t)}return 60===t&&this.exprAllowed?(++this.pos,this.finishToken(i.jsxTagStart)):e.call(this,t)}}),e.extend("updateContext",function(e){return function(t){if(this.type==i.braceL){var n=this.curContext();n==a.j_oTag?this.context.push(a.b_expr):n==a.j_expr?this.context.push(a.b_tmpl):e.call(this,t),this.exprAllowed=!0}else{if(this.type!==i.slash||t!==i.jsxTagStart)return e.call(this,t);this.context.length-=2,this.context.push(a.j_cTag),this.exprAllowed=!1}}})}},{"..":5}],3:[function(e,t,n){"use strict";var r=e("./tokentype").types,l=e("./state").Parser,i=e("./identifier").reservedWords,a=e("./util").has,s=l.prototype;s.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 l=e.kind||"init",i=void 0;if(a(t,r)){i=t[r];var s="init"!==l;((this.strict||s)&&i[l]||!(s^i.init))&&this.raise(n.start,"Redefinition of property")}else i=t[r]={init:!1,get:!1,set:!1};i[l]=!0}},s.parseExpression=function(e,t){var n=this.markPosition(),l=this.parseMaybeAssign(e,t);if(this.type===r.comma){var i=this.startNodeAt(n);for(i.expressions=[l];this.eat(r.comma);)i.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(i,"SequenceExpression")}return l},s.parseMaybeAssign=function(e,t,n){if(this.type==r._yield&&this.inGenerator)return this.parseYield();var l=void 0;t?l=!1:(t={start:0},l=!0);var i=this.markPosition(),a=this.parseMaybeConditional(e,t);if(n&&(a=n.call(this,a,i)),this.type.isAssign){var s=this.startNodeAt(i);return s.operator=this.value,s.left=this.type===r.eq?this.toAssignable(a):a,t.start=0,this.checkLVal(a),a.parenthesizedExpression&&("ObjectPattern"===a.type?this.raise(a.start,"You're trying to assign to a parenthesized expression, instead of `({ foo }) = {}` use `({ foo } = {})`"):this.raise(a.start,"Parenthesized left hand expressions are illegal")),this.next(),s.right=this.parseMaybeAssign(e),this.finishNode(s,"AssignmentExpression")}return l&&t.start&&this.unexpected(t.start),a},s.parseMaybeConditional=function(e,t){var n=this.markPosition(),l=this.parseExprOps(e,t);if(t&&t.start)return l;if(this.eat(r.question)){var i=this.startNodeAt(n);return i.test=l,i.consequent=this.parseMaybeAssign(),this.expect(r.colon),i.alternate=this.parseMaybeAssign(e),this.finishNode(i,"ConditionalExpression")}return l},s.parseExprOps=function(e,t){var n=this.markPosition(),r=this.parseMaybeUnary(t);return t&&t.start?r:this.parseExprOp(r,n,-1,e)},s.parseExprOp=function(e,t,n,l){var i=this.type.binop;if(null!=i&&(!l||this.type!==r._in)&&i>n){var a=this.startNodeAt(t);a.left=e,a.operator=this.value;var s=this.type;this.next();var o=this.markPosition();return a.right=this.parseExprOp(this.parseMaybeUnary(),o,s.rightAssociative?i-1:i,l),this.finishNode(a,s===r.logicalOR||s===r.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(a,t,n,l)}return e},s.parseMaybeUnary=function(e){if(this.type.prefix){var t=this.startNode(),n=this.type===r.incDec;return t.operator=this.value,t.prefix=!0,this.next(),t.argument=this.parseMaybeUnary(),e&&e.start&&this.unexpected(e.start),n?this.checkLVal(t.argument):this.strict&&"delete"===t.operator&&"Identifier"===t.argument.type&&this.raise(t.start,"Deleting local variable in strict mode"),this.finishNode(t,n?"UpdateExpression":"UnaryExpression")}var l=this.markPosition(),i=this.parseExprSubscripts(e);if(e&&e.start)return i;for(;this.type.postfix&&!this.canInsertSemicolon();){var t=this.startNodeAt(l);t.operator=this.value,t.prefix=!1,t.argument=i,this.checkLVal(i),this.next(),i=this.finishNode(t,"UpdateExpression")}return i},s.parseExprSubscripts=function(e){var t=this.markPosition(),n=this.parseExprAtom(e);return e&&e.start?n:this.parseSubscripts(n,t)},s.parseSubscripts=function(e,t,n){if(this.eat(r.dot)){var l=this.startNodeAt(t);return l.object=e,l.property=this.parseIdent(!0),l.computed=!1,this.parseSubscripts(this.finishNode(l,"MemberExpression"),t,n)}if(this.eat(r.bracketL)){var l=this.startNodeAt(t);return l.object=e,l.property=this.parseExpression(),l.computed=!0,this.expect(r.bracketR),this.parseSubscripts(this.finishNode(l,"MemberExpression"),t,n)}if(!n&&this.eat(r.parenL)){var l=this.startNodeAt(t);return l.callee=e,l.arguments=this.parseExprList(r.parenR,!1),this.parseSubscripts(this.finishNode(l,"CallExpression"),t,n)}if(this.type===r.backQuote){var l=this.startNodeAt(t);return l.tag=e,l.quasi=this.parseTemplate(),this.parseSubscripts(this.finishNode(l,"TaggedTemplateExpression"),t,n)}return e},s.parseExprAtom=function(e){var t=void 0;switch(this.type){case r._this:case r._super:var n=this.type===r._this?"ThisExpression":"Super";return t=this.startNode(),this.next(),this.finishNode(t,n);case r._yield:this.inGenerator&&this.unexpected();case r._do:if(this.options.features["es7.doExpressions"]){var l=this.startNode();return this.next(),l.body=this.parseBlock(),this.finishNode(l,"DoExpression")}case r.name:var i=this.markPosition();t=this.startNode();var a=this.parseIdent(this.type!==r.name);if(this.options.features["es7.asyncFunctions"])if("async"===a.name){if(this.type===r.parenL){var s=this.parseParenAndDistinguishExpression(i,!0);return s&&"ArrowFunctionExpression"===s.type?s:(t.callee=a,t.arguments=s?"SequenceExpression"===s.type?s.expressions:[s]:[],this.parseSubscripts(this.finishNode(t,"CallExpression"),i))}if(this.type===r.name)return a=this.parseIdent(),this.expect(r.arrow),this.parseArrowExpression(t,[a],!0);if(this.type===r._function&&!this.canInsertSemicolon())return this.next(),this.parseFunction(t,!1,!1,!0)}else if("await"===a.name&&this.inAsync)return this.parseAwait(t);return!this.canInsertSemicolon()&&this.eat(r.arrow)?this.parseArrowExpression(this.startNodeAt(i),[a]):a;case r.regexp:var o=this.value;return t=this.parseLiteral(o.value),t.regex={pattern:o.pattern,flags:o.flags},t;case r.num:case r.string:return this.parseLiteral(this.value);case r._null:case r._true:case r._false:return t=this.startNode(),t.value=this.type===r._null?null:this.type===r._true,t.raw=this.type.keyword,this.next(),this.finishNode(t,"Literal");case r.parenL:return this.parseParenAndDistinguishExpression();case r.bracketL:return t=this.startNode(),this.next(),(this.options.ecmaVersion>=7||this.options.features["es7.comprehensions"])&&this.type===r._for?this.parseComprehension(t,!1):(t.elements=this.parseExprList(r.bracketR,!0,!0,e),this.finishNode(t,"ArrayExpression"));case r.braceL:return this.parseObj(!1,e);case r._function:return t=this.startNode(),this.next(),this.parseFunction(t,!1);case r.at:this.parseDecorators();case r._class:return t=this.startNode(),this.takeDecorators(t),this.parseClass(t,!1);case r._new:return this.parseNew();case r.backQuote:return this.parseTemplate();default:this.unexpected()}},s.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")},s.parseParenExpression=function(){this.expect(r.parenL);var e=this.parseExpression();return this.expect(r.parenR),e},s.parseParenAndDistinguishExpression=function(e,t){e=e||this.markPosition();var n=void 0;if(this.options.ecmaVersion>=6){if(this.next(),(this.options.features["es7.comprehensions"]||this.options.ecmaVersion>=7)&&this.type===r._for)return this.parseComprehension(this.startNodeAt(e),!0);for(var l=this.markPosition(),i=[],a=!0,s={start:0},o=void 0,u=void 0;this.type!==r.parenR;){if(a?a=!1:this.expect(r.comma),this.type===r.ellipsis){var c=this.markPosition();o=this.start,i.push(this.parseParenItem(this.parseRest(),c));break}this.type!==r.parenL||u||(u=this.start),i.push(this.parseMaybeAssign(!1,s,this.parseParenItem)); }var p=this.markPosition();if(this.expect(r.parenR),!this.canInsertSemicolon()&&this.eat(r.arrow))return u&&this.unexpected(u),this.parseParenArrowList(e,i,t);if(!i.length){if(t)return;this.unexpected(this.lastTokStart)}o&&this.unexpected(o),s.start&&this.unexpected(s.start),i.length>1?(n=this.startNodeAt(l),n.expressions=i,this.finishNodeAt(n,"SequenceExpression",p)):n=i[0]}else n=this.parseParenExpression();if(this.options.preserveParens){var d=this.startNodeAt(e);return d.expression=n,this.finishNode(d,"ParenthesizedExpression")}return n.parenthesizedExpression=!0,n},s.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e),t,n)},s.parseParenItem=function(e,t){return e};var o=[];s.parseNew=function(){var e=this.startNode(),t=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(r.dot))return e.meta=t,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 n=this.markPosition();return e.callee=this.parseSubscripts(this.parseExprAtom(),n,!0),e.arguments=this.eat(r.parenL)?this.parseExprList(r.parenR,!1):o,this.finishNode(e,"NewExpression")},s.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===r.backQuote,this.finishNode(e,"TemplateElement")},s.parseTemplate=function(){var e=this.startNode();this.next(),e.expressions=[];var t=this.parseTemplateElement();for(e.quasis=[t];!t.tail;)this.expect(r.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(r.braceR),e.quasis.push(t=this.parseTemplateElement());return this.next(),this.finishNode(e,"TemplateLiteral")},s.parseObj=function(e,t){var n=this.startNode(),l=!0,i={};for(n.properties=[],this.next();!this.eat(r.braceR);){if(l)l=!1;else if(this.expect(r.comma),this.afterTrailingComma(r.braceR))break;var a=this.startNode(),s=!1,o=!1,u=void 0;if(this.options.features["es7.objectRestSpread"]&&this.type===r.ellipsis)a=this.parseSpread(),a.type="SpreadProperty",n.properties.push(a);else{if(this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(u=this.markPosition()),e||(s=this.eat(r.star))),this.options.features["es7.asyncFunctions"]&&this.isContextual("async")){(s||e)&&this.unexpected();var c=this.parseIdent();this.type===r.colon||this.type===r.parenL?a.key=c:(o=!0,this.parsePropertyName(a))}else this.parsePropertyName(a);this.parseObjPropValue(a,u,s,o,e,t),this.checkPropClash(a,i),n.properties.push(this.finishNode(a,"Property"))}}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")},s.parseObjPropValue=function(e,t,n,l,a,s){this.eat(r.colon)?(e.value=a?this.parseMaybeDefault():this.parseMaybeAssign(!1,s),e.kind="init"):this.options.ecmaVersion>=6&&this.type===r.parenL?(a&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(n,l)):this.options.ecmaVersion>=5&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&this.type!=r.comma&&this.type!=r.braceR?((n||l||a)&&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",a?((this.isKeyword(e.key.name)||this.strict&&(i.strictBind(e.key.name)||i.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(t,e.key)):this.type===r.eq&&s?(s.start||(s.start=this.start),e.value=this.parseMaybeDefault(t,e.key)):e.value=e.key,e.shorthand=!0):this.unexpected()},s.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(r.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),void this.expect(r.bracketR);e.computed=!1}e.key=this.type===r.num||this.type===r.string?this.parseExprAtom():this.parseIdent(!0)},s.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)},s.parseMethod=function(e,t){var n=this.startNode();return this.initFunction(n,t),this.expect(r.parenL),n.params=this.parseBindingList(r.parenR,!1,!1),this.options.ecmaVersion>=6&&(n.generator=e),this.parseFunctionBody(n),this.finishNode(n,"FunctionExpression")},s.parseArrowExpression=function(e,t,n){return this.initFunction(e,n),e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0),this.finishNode(e,"ArrowFunctionExpression")},s.parseFunctionBody=function(e,t){var n=t&&this.type!==r.braceL,l=this.inAsync;if(this.inAsync=e.async,n)e.body=this.parseMaybeAssign(),e.expression=!0;else{var i=this.inFunction,a=this.inGenerator,s=this.labels;this.inFunction=!0,this.inGenerator=e.generator,this.labels=[],e.body=this.parseBlock(!0),e.expression=!1,this.inFunction=i,this.inGenerator=a,this.labels=s}if(this.inAsync=l,this.strict||!n&&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 c=0;c<e.params.length;c++)this.checkLVal(e.params[c],!0,o);this.strict=u}},s.parseExprList=function(e,t,n,l){for(var i=[],a=!0;!this.eat(e);){if(a)a=!1;else if(this.expect(r.comma),t&&this.afterTrailingComma(e))break;i.push(n&&this.type===r.comma?null:this.type===r.ellipsis?this.parseSpread(l):this.parseMaybeAssign(!1,l))}return i},s.parseIdent=function(e){var t=this.startNode();return e&&"never"==this.options.allowReserved&&(e=!1),this.type===r.name?(!e&&(!this.options.allowReserved&&this.isReservedWord(this.value)||this.strict&&i.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"),t.name=this.value):e&&this.type.keyword?t.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"Identifier")},s.parseAwait=function(e){return(this.eat(r.semi)||this.canInsertSemicolon())&&this.unexpected(),e.all=this.eat(r.star),e.argument=this.parseMaybeAssign(!0),this.finishNode(e,"AwaitExpression")},s.parseYield=function(){var e=this.startNode();return this.next(),this.type==r.semi||this.canInsertSemicolon()||this.type!=r.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(r.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")},s.parseComprehension=function(e,t){for(e.blocks=[];this.type===r._for;){var n=this.startNode();this.next(),this.expect(r.parenL),n.left=this.parseBindingAtom(),this.checkLVal(n.left,!0),this.expectContextual("of"),n.right=this.parseExpression(),this.expect(r.parenR),e.blocks.push(this.finishNode(n,"ComprehensionBlock"))}return e.filter=this.eat(r._if)?this.parseParenExpression():null,e.body=this.parseExpression(),this.expect(t?r.parenR:r.bracketR),e.generator=t,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 a=r[l];n+="case "+a[0].length+":",t(a)}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 a(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=a,n.__esModule=!0;var s={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=s;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 c="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",p="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_",d=new RegExp("["+c+"]"),f=new RegExp("["+c+p+"]");c=p=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=a(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=a(n,e,t);return r.nextToken(),r.parseExpression()}function i(e,t){return a(t,e)}function a(e,t){return new o(c(e),String(t))}n.parse=r,n.parseExpressionAt=l,n.tokenizer=i,n.__esModule=!0;var s=e("./state"),o=s.Parser,u=e("./options"),c=u.getOptions;e("./parseutil"),e("./statement"),e("./lval"),e("./expression"),e("./lookahead"),n.Parser=s.Parser,n.plugins=s.plugins,n.defaultOptions=u.defaultOptions;var p=e("./location");n.SourceLocation=p.SourceLocation,n.getLineInfo=p.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;;){a.lastIndex=r;var l=a.exec(e);if(!(l&&l.index<t))return new s(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,a=e("./whitespace").lineBreakG,s=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 s(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,t,n){"use strict";var r=e("./state").Parser,l=r.prototype,i=["lastTokStartLoc","lastTokEndLoc","lastTokStart","lastTokEnd","lineStart","startLoc","endLoc","start","pos","end","type","value"];l.getState=function(){for(var e={},t=0;t<i.length;t++){var n=i[t];e[n]=this[n]}return e},l.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,t,n){"use strict";var r=e("./tokentype").types,l=e("./state").Parser,i=e("./identifier").reservedWords,a=e("./util").has,s=l.prototype;s.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},s.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 a=e[i];a&&this.toAssignable(a,t)}return e},s.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(e),this.finishNode(t,"SpreadElement")},s.parseRest=function(){var e=this.startNode();return this.next(),e.argument=this.type===r.name||this.type===r.bracketL?this.parseBindingAtom():this.unexpected(),this.finishNode(e,"RestElement")},s.parseBindingAtom=function(){if(this.options.ecmaVersion<6)return this.parseIdent();switch(this.type){case r.name:return this.parseIdent();case r.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(r.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case r.braceL:return this.parseObj(!0);default:this.unexpected()}},s.parseBindingList=function(e,t,n){for(var l=[],i=!0;!this.eat(e);)if(i?i=!1:this.expect(r.comma),t&&this.type===r.comma)l.push(null);else{if(n&&this.afterTrailingComma(e))break;if(this.type===r.ellipsis){l.push(this.parseAssignableListItemTypes(this.parseRest())),this.expect(e);break}var a=this.parseMaybeDefault();this.parseAssignableListItemTypes(a),l.push(this.parseMaybeDefault(null,a))}return l},s.parseAssignableListItemTypes=function(e){return e},s.parseMaybeDefault=function(e,t){if(e=e||this.markPosition(),t=t||this.parseBindingAtom(),!this.eat(r.eq))return t;var n=this.startNodeAt(e);return n.operator="=",n.left=t,n.right=this.parseMaybeAssign(),this.finishNode(n,"AssignmentPattern")},s.checkLVal=function(e,t,n){switch(e.type){case"Identifier":this.strict&&(i.strictBind(e.name)||i.strict(e.name))&&this.raise(e.start,(t?"Binding ":"Assigning to ")+e.name+" in strict mode"),n&&(a(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 r=0;r<e.properties.length;r++){var l=e.properties[r];"Property"===l.type&&(l=l.value),this.checkLVal(l,t,n)}break;case"ArrayPattern":for(var r=0;r<e.elements.length;r++){var s=e.elements[r];s&&this.checkLVal(s,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,a=l.prototype,s=n.Node=function o(){r(this,o)};a.startNode=function(){var e=new s;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},a.startNodeAt=function(e){var t=new s,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},a.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},a.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&&a(e,n)?e[n]:u[n];return s(t.onToken)&&!function(){var e=t.onToken;t.onToken=function(t){return e.push(t)}}(),s(t.onComment)&&(t.onComment=l(t,t.onComment)),t}function l(e,t){return function(n,r,l,i,a,s){var u={type:n?"Block":"Line",value:r,start:l,end:i};e.locations&&(u.loc=new o(this,a,s)),e.ranges&&(u.range=[l,i]),t.push(u)}}n.getOptions=r,n.__esModule=!0;var i=e("./util"),a=i.has,s=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,t,n){"use strict";var r=e("./tokentype").types,l=e("./state").Parser,i=e("./whitespace").lineBreak,a=l.prototype;a.isUseStrict=function(e){return this.options.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value},a.eat=function(e){return this.type===e?(this.next(),!0):!1},a.isContextual=function(e){return this.type===r.name&&this.value===e},a.eatContextual=function(e){return this.value===e&&this.eat(r.name)},a.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},a.canInsertSemicolon=function(){return this.type===r.eof||this.type===r.braceR||i.test(this.input.slice(this.lastTokEnd,this.start))},a.insertSemicolon=function(){return this.canInsertSemicolon()?(this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0):void 0},a.semicolon=function(){this.eat(r.semi)||this.insertSemicolon()||this.unexpected()},a.afterTrailingComma=function(e){return this.type==e?(this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),this.next(),!0):void 0},a.expect=function(e){this.eat(e)||this.unexpected()},a.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=a[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,a=l.keywords,s=e("./tokentype"),o=s.types,u=s.lineBreak;r.prototype.extend=function(e,t){this[e]=t(this[e])};var c={};n.plugins=c,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,t,n){"use strict";var r=e("./tokentype").types,l=e("./state").Parser,i=e("./whitespace").lineBreak,a=l.prototype;a.parseTopLevel=function(e){var t=!0;for(e.body||(e.body=[]);this.type!==r.eof;){var n=this.parseStatement(!0,!0);e.body.push(n),t&&this.isUseStrict(n)&&this.setStrict(!0),t=!1}return this.next(),this.options.ecmaVersion>=6&&(e.sourceType=this.options.sourceType),this.finishNode(e,"Program")};var s={kind:"loop"},o={kind:"switch"};a.parseStatement=function(e,t){this.type===r.at&&this.parseDecorators(!0);var n=this.type,l=this.startNode();switch(n){case r._break:case r._continue:return this.parseBreakContinueStatement(l,n.keyword);case r._debugger:return this.parseDebuggerStatement(l);case r._do:return this.parseDoStatement(l);case r._for:return this.parseForStatement(l);case r._function:return!e&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(l);case r._class:return e||this.unexpected(),this.takeDecorators(l),this.parseClass(l,!0);case r._if:return this.parseIfStatement(l);case r._return:return this.parseReturnStatement(l);case r._switch:return this.parseSwitchStatement(l);case r._throw:return this.parseThrowStatement(l);case r._try:return this.parseTryStatement(l);case r._let:case r._const:e||this.unexpected();case r._var:return this.parseVarStatement(l,n);case r._while:return this.parseWhileStatement(l);case r._with:return this.parseWithStatement(l);case r.braceL:return this.parseBlock();case r.semi:return this.parseEmptyStatement(l);case r._export:case r._import:return this.options.allowImportExportEverywhere||(t||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'")),n===r._import?this.parseImport(l):this.parseExport(l);case r.name:if(this.options.features["es7.asyncFunctions"]&&"async"===this.value&&this.lookahead().type===r._function)return this.next(),this.expect(r._function),this.parseFunction(l,!0,!1,!0);default:var i=this.value,a=this.parseExpression();return n===r.name&&"Identifier"===a.type&&this.eat(r.colon)?this.parseLabeledStatement(l,i,a):this.parseExpressionStatement(l,a)}},a.takeDecorators=function(e){this.decorators.length&&(e.decorators=this.decorators,this.decorators=[])},a.parseDecorators=function(e){for(;this.type===r.at;)this.decorators.push(this.parseDecorator());e&&this.type===r._export||this.type!==r._class&&this.raise(this.start,"Leading decorators must be attached to a class declaration")},a.parseDecorator=function(e){this.options.features["es7.decorators"]||this.unexpected();var t=this.startNode();return this.next(),t.expression=this.parseMaybeAssign(),this.finishNode(t,"Decorator")},a.parseBreakContinueStatement=function(e,t){var n="break"==t;this.next(),this.eat(r.semi)||this.insertSemicolon()?e.label=null:this.type!==r.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&&(n||"loop"===i.kind))break;if(e.label&&n)break}}return l===this.labels.length&&this.raise(e.start,"Unsyntactic "+t),this.finishNode(e,n?"BreakStatement":"ContinueStatement")},a.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")},a.parseDoStatement=function(e){var t=this.markPosition();if(this.next(),this.labels.push(s),e.body=this.parseStatement(!1),this.labels.pop(),this.options.features["es7.doExpressions"]&&this.type!==r._while){var n=this.startNodeAt(t);return n.expression=this.finishNode(e,"DoExpression"),this.semicolon(),this.finishNode(n,"ExpressionStatement")}return this.expect(r._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(r.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},a.parseForStatement=function(e){if(this.next(),this.labels.push(s),this.expect(r.parenL),this.type===r.semi)return this.parseFor(e,null);if(this.type===r._var||this.type===r._let||this.type===r._const){var t=this.startNode(),n=this.type;return this.next(),this.parseVar(t,!0,n),this.finishNode(t,"VariableDeclaration"),!(this.type===r._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==t.declarations.length||n!==r._var&&t.declarations[0].init?this.parseFor(e,t):this.parseForIn(e,t)}var l={start:0},i=this.parseExpression(!0,l);return this.type===r._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.toAssignable(i),this.checkLVal(i),this.parseForIn(e,i)):(l.start&&this.unexpected(l.start),this.parseFor(e,i))},a.parseFunctionStatement=function(e){return this.next(),this.parseFunction(e,!0)},a.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(!1),e.alternate=this.eat(r._else)?this.parseStatement(!1):null,this.finishNode(e,"IfStatement")},a.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(r.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},a.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(r.braceL),this.labels.push(o);for(var t,n;this.type!=r.braceR;)if(this.type===r._case||this.type===r._default){var l=this.type===r._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),l?t.test=this.parseExpression():(n&&this.raise(this.lastTokStart,"Multiple default clauses"),n=!0,t.test=null),this.expect(r.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(!0));return t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},a.parseThrowStatement=function(e){return this.next(),i.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 u=[];a.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===r._catch){var t=this.startNode();this.next(),this.expect(r.parenL),t.param=this.parseBindingAtom(),this.checkLVal(t.param,!0),this.expect(r.parenR),t.guard=null,t.body=this.parseBlock(),e.handler=this.finishNode(t,"CatchClause")}return e.guardedHandlers=u,e.finalizer=this.eat(r._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},a.parseVarStatement=function(e,t){return this.next(),this.parseVar(e,!1,t),this.semicolon(),this.finishNode(e,"VariableDeclaration")},a.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(s),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"WhileStatement")},a.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")},a.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},a.parseLabeledStatement=function(e,t,n){for(var l=0;l<this.labels.length;++l)this.labels[l].name===t&&this.raise(n.start,"Label '"+t+"' is already declared");var i=this.type.isLoop?"loop":this.type===r._switch?"switch":null;return this.labels.push({name:t,kind:i}),e.body=this.parseStatement(!0),this.labels.pop(),e.label=n,this.finishNode(e,"LabeledStatement")},a.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},a.parseBlock=function(e){var t=this.startNode(),n=!0,l=void 0;for(t.body=[],this.expect(r.braceL);!this.eat(r.braceR);){var i=this.parseStatement(!0);t.body.push(i),n&&e&&this.isUseStrict(i)&&(l=this.strict,this.setStrict(this.strict=!0)),n=!1}return l===!1&&this.setStrict(!1),this.finishNode(t,"BlockStatement")},a.parseFor=function(e,t){return e.init=t,this.expect(r.semi),e.test=this.type===r.semi?null:this.parseExpression(),this.expect(r.semi),e.update=this.type===r.parenR?null:this.parseExpression(),this.expect(r.parenR),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"ForStatement")},a.parseForIn=function(e,t){var n=this.type===r._in?"ForInStatement":"ForOfStatement";return this.next(),e.left=t,e.right=this.parseExpression(),this.expect(r.parenR),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,n)},a.parseVar=function(e,t,n){for(e.declarations=[],e.kind=n.keyword;;){var l=this.startNode();if(this.parseVarHead(l),this.eat(r.eq)?l.init=this.parseMaybeAssign(t):n!==r._const||this.type===r._in||this.options.ecmaVersion>=6&&this.isContextual("of")?"Identifier"==l.id.type||t&&(this.type===r._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(r.comma))break}return e},a.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0)},a.parseFunction=function(e,t,n,l){return this.initFunction(e,l),this.options.ecmaVersion>=6&&(e.generator=this.eat(r.star)),(t||this.type===r.name)&&(e.id=this.parseIdent()),this.parseFunctionParams(e),this.parseFunctionBody(e,n),this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression"); },a.parseFunctionParams=function(e){this.expect(r.parenL),e.params=this.parseBindingList(r.parenR,!1,!1)},a.parseClass=function(e,t){this.next(),this.parseClassId(e,t),this.parseClassSuper(e);var n=this.startNode();for(n.body=[],this.expect(r.braceL);!this.eat(r.braceR);)if(!this.eat(r.semi))if(this.type!==r.at){var l=this.startNode();this.takeDecorators(l);var i=this.eat(r.star),a=!1;this.parsePropertyName(l),this.type===r.parenL||l.computed||"Identifier"!==l.key.type||"static"!==l.key.name?l["static"]=!1:(i&&this.unexpected(),l["static"]=!0,i=this.eat(r.star),this.parsePropertyName(l)),i||"Identifier"!==l.key.type||l.computed||!this.isClassProperty()?(this.options.features["es7.asyncFunctions"]&&this.type!==r.parenL&&!l.computed&&"Identifier"===l.key.type&&"async"===l.key.name&&(a=!0,this.parsePropertyName(l)),l.kind="method",l.computed||i||("Identifier"===l.key.type?this.type===r.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(n,l,i,a)):n.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(n,"ClassBody"),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},a.isClassProperty=function(){return this.type===r.eq||this.type===r.semi||this.canInsertSemicolon()},a.parseClassProperty=function(e){return this.type===r.eq?(this.options.features["es7.classProperties"]||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.finishNode(e,"ClassProperty")},a.parseClassMethod=function(e,t,n,r){t.value=this.parseMethod(n,r),e.body.push(this.finishNode(t,"MethodDefinition"))},a.parseClassId=function(e,t){e.id=this.type===r.name?this.parseIdent():t?this.unexpected():null},a.parseClassSuper=function(e){e.superClass=this.eat(r._extends)?this.parseExprSubscripts():null},a.parseExport=function(e){if(this.next(),this.type===r.star){var t=this.startNode();if(this.next(),!this.options.features["es7.exportExtensions"]||!this.eatContextual("as"))return this.parseExportFrom(e),this.finishNode(e,"ExportAllDeclaration");t.exported=this.parseIdent(),e.specifiers=[this.finishNode(t,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(e),this.parseExportFrom(e)}else if(this.isExportDefaultSpecifier()){var t=this.startNode();if(t.exported=this.parseIdent(!0),e.specifiers=[this.finishNode(t,"ExportDefaultSpecifier")],this.type===r.comma&&this.lookahead().type===r.star){this.expect(r.comma);var n=this.startNode();this.expect(r.star),this.expectContextual("as"),n.exported=this.parseIdent(),e.specifiers.push(this.finishNode(n,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(e);this.parseExportFrom(e)}else{if(this.eat(r._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===r.string?this.parseExprAtom():this.unexpected():null,this.semicolon())}return this.checkExport(e),this.finishNode(e,"ExportNamedDeclaration")},a.isExportDefaultSpecifier=function(){if(this.type===r.name)return"type"!==this.value&&"async"!==this.value;if(this.type!==r._default)return!1;var e=this.lookahead();return e.type===r.comma||e.type===r.name&&"from"===e.value},a.parseExportSpecifiersMaybe=function(e){this.eat(r.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},a.parseExportFrom=function(e){this.expectContextual("from"),e.source=this.type===r.string?this.parseExprAtom():this.unexpected(),this.semicolon(),this.checkExport(e)},a.shouldParseExportDeclaration=function(){return this.options.features["es7.asyncFunctions"]&&this.isContextual("async")},a.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)}},a.parseExportSpecifiers=function(){var e=[],t=!0;for(this.expect(r.braceL);!this.eat(r.braceR);){if(t)t=!1;else if(this.expect(r.comma),this.afterTrailingComma(r.braceR))break;var n=this.startNode();n.local=this.parseIdent(this.type===r._default),n.exported=this.eatContextual("as")?this.parseIdent(!0):n.local,e.push(this.finishNode(n,"ExportSpecifier"))}return e},a.parseImport=function(e){return this.next(),this.type===r.string?(e.specifiers=u,e.source=this.parseExprAtom(),e.kind=""):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.type===r.string?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},a.parseImportSpecifiers=function(e){var t=!0;if(this.type===r.name){var n=this.markPosition();if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdent(),n)),!this.eat(r.comma))return}if(this.type===r.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(r.braceL);!this.eat(r.braceR);){if(t)t=!1;else if(this.expect(r.comma),this.afterTrailingComma(r.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"))}},a.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,a=e("./whitespace").lineBreak,s=n.TokContext=function c(e,t,n,l){r(this,c),this.token=e,this.isExpr=t,this.preserveSpace=n,this.override=l},o={b_stat:new s("{",!1),b_expr:new s("{",!0),b_tmpl:new s("${",!0),p_stat:new s("(",!1),p_expr:new s("(",!0),q_tmpl:new s("`",!0,!0,function(e){return e.readTmplToken()}),f_expr:new s("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?a.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"),a=i.isIdentifierStart,s=i.isIdentifierChar,o=e("./tokentype"),u=o.types,c=o.keywords,p=e("./state").Parser,d=e("./location").SourceLocation,f=e("./whitespace"),h=f.lineBreak,m=f.lineBreakG,g=f.isNewLine,y=f.nonASCIIwhitespace,v=n.Token=function w(e){l(this,w),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])},b=p.prototype;b.next=function(){this.options.onToken&&this.options.onToken(new v(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},b.getToken=function(){return this.next(),new v(this)},"undefined"!=typeof Symbol&&(b[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===u.eof,value:t}}}}),b.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()}},b.curContext=function(){return this.context[this.context.length-1]},b.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())},b.readToken=function(e){return a(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},b.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},b.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())},b.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())},b.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}}},b.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)},b.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))},b.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)},b.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)},b.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)},b.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);return 61===e?this.finishOp(u.assign,2):this.finishOp(u.bitwiseXOR,1)},b.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)},b.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))},b.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)},b.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)+"'")},b.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){}b.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(),a=l;if(i){var s=/^[gmsiy]*$/;this.options.ecmaVersion>=6&&(s=/^[gmsiyu]*$/),s.test(i)||this.raise(n,"Invalid regular expression flag"),i.indexOf("u")>=0&&!x&&(a=a.replace(/\\u([a-fA-F0-9]{4})|\\u\{([0-9a-fA-F]+)\}|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"))}try{new RegExp(a)}catch(o){o instanceof SyntaxError&&this.raise(n,"Error parsing regular expression: "+o.message),this.raise(o)}var c=void 0;try{c=new RegExp(l,i)}catch(p){c=null}return this.finishToken(u.regexp,{pattern:l,flags:i,value:c})},b.readInt=function(e,t){for(var n=this.pos,r=0,l=0,i=null==t?1/0:t;i>l;++l){var a=this.input.charCodeAt(this.pos),s=void 0;if(s=a>=97?a-97+10:a>=65?a-65+10:a>=48&&57>=a?a-48:1/0,s>=e)break;++this.pos,r=r*e+s}return this.pos===n||null!=t&&this.pos-n!==t?null:r},b.readRadixNumber=function(e){this.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.start+2,"Expected number in radix "+e),a(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,t)},b.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),a(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i=this.input.slice(t,this.pos),s=void 0;return n?s=parseFloat(i):r&&1!==i.length?/[89]/.test(i)||this.strict?this.raise(t,"Invalid number"):s=parseInt(i,8):s=parseInt(i,10),this.finishToken(u.num,s)},b.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},b.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)},b.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}},b.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)}},b.readHexChar=function(e){var t=this.readInt(16,e);return null===t&&this.raise(this.start,"Bad character escape sequence"),t};var _;b.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(s(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?a:s)(u,l)||this.raise(o,"Invalid Unicode escape"),e+=r(u),n=this.pos}t=!1}return e+this.input.slice(n,this.pos)},b.readWord=function(){var e=this.readWord1(),t=u.name;return(this.options.ecmaVersion>=6||!_)&&this.isKeyword(e)&&(t=c[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 a(e,{beforeExpr:!0,binop:t})}function l(e){var t=void 0===arguments[1]?{}:arguments[1];t.keyword=e,c[e]=u["_"+e]=new a(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 a=n.TokenType=function p(e){var t=void 0===arguments[1]?{}:arguments[1];i(this,p),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},s={beforeExpr:!0},o={startsExpr:!0},u={num:new a("num",o),regexp:new a("regexp",o),string:new a("string",o),name:new a("name",o),eof:new a("eof"),bracketL:new a("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new a("]"),braceL:new a("{",{beforeExpr:!0,startsExpr:!0}),braceR:new a("}"),parenL:new a("(",{beforeExpr:!0,startsExpr:!0}),parenR:new a(")"),comma:new a(",",s),semi:new a(";",s),colon:new a(":",s),dot:new a("."),question:new a("?",s),arrow:new a("=>",s),template:new a("template"),ellipsis:new a("...",s),backQuote:new a("`",o),dollarBraceL:new a("${",{beforeExpr:!0,startsExpr:!0}),at:new a("@"),eq:new a("=",{beforeExpr:!0,isAssign:!0}),assign:new a("_=",{beforeExpr:!0,isAssign:!0}),incDec:new a("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new a("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 a("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:r("%",10),star:r("*",10),slash:r("/",10),exponent:new a("**",{beforeExpr:!0,binop:11,rightAssociative:!0})};n.types=u;var c={};n.keywords=c,l("break"),l("case",s),l("catch"),l("continue"),l("debugger"),l("default"),l("do",{isLoop:!0}),l("else",s),l("finally"),l("for",{isLoop:!0}),l("function"),l("if"),l("return",s),l("switch"),l("throw",s),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",s),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 a=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;n.nonASCIIwhitespace=a},{}],19:[function(e,t,n){(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 a=void 0===arguments[2]?{}:arguments[2],s=a;s.filename||(s.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,a];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())}),a=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])},s=n.document.getElementsByTagName("script"),o=0;o<s.length;++o){var u=s[o];t.indexOf(u.type)>=0&&e.push(u)}for(o in e)a(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":455,"../transformation":63,"../transformation/file/options":49}],20:[function(e,t,n){"use strict";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("repeating")),a=r(e("trim-right")),s=r(e("lodash/lang/isBoolean")),o=r(e("lodash/collection/includes")),u=r(e("lodash/lang/isNumber")),c=function(){function e(t,n){l(this,e),this.position=t,this._indent=n.indent.base,this.format=n,this.buf=""}return e.prototype.get=function(){return a(this.buf)},e.prototype.getIndent=function(){return this.format.compact||this.format.concise?"":i(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),u(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)?o(e,n):e===n},e}();t.exports=c},{"lodash/collection/includes":319,"lodash/lang/isBoolean":393,"lodash/lang/isNumber":397,repeating:437,"trim-right":454}],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 a(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=a,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;(_.isUpdateExpression(r)||_.isUnaryExpression(r))&&(n=!0),_.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 a(e,t){t(e.test),this.space(),this.push("?"),this.space(),t(e.consequent),this.space(),this.push(":"),this.space(),t(e.alternate)}function s(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 c(){this.push("super")}function p(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&&_.isMemberExpression(e.property))throw new TypeError("Got a MemberExpression for MemberExpression property");var r=e.computed;_.isLiteral(e.property)&&E(e.property.value)&&(r=!0),r?(this.push("["),t(e.property),this.push("]")):(_.isLiteral(n)&&x(n.value)&&!k.test(n.value.toString())&&this.push("."),this.push("."),t(e.property))}function y(e,t){t(e.meta),this.push("."),t(e.property)}var v=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=a,n.NewExpression=s,n.SequenceExpression=o,n.ThisExpression=u,n.Super=c,n.Decorator=p,n.CallExpression=d,n.EmptyStatement=f,n.ExpressionStatement=h,n.AssignmentExpression=m,n.MemberExpression=g,n.MetaProperty=y,n.__esModule=!0;var x=b(e("is-integer")),E=b(e("lodash/lang/isNumber")),_=v(e("../../types")),w=function(e){ return function(t,n){this.push(e),(t.delegate||t.all)&&this.push("*"),t.argument&&(this.space(),n(t.argument))}},S=w("yield");n.YieldExpression=S;var I=w("await");n.AwaitExpression=I,n.BinaryExpression=m,n.LogicalExpression=m,n.AssignmentPattern=m;var k=/e/i},{"../../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(e){this.push("bool")}function a(e,t){this.push("declare class "),this._interfaceish(e,t)}function s(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 c(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 p(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 v(e){this._stringLiteral(e.value)}function b(){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 w(e,t){this.push(":"),this.space(),e.optional&&this.push("?"),t(e.typeAnnotation)}function S(e,t){this.push("<"),t.join(e.params,{separator:", "}),this.push(">")}function I(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 T(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("?"),P.isFunctionTypeAnnotation(e.value)||(this.push(":"),this.space()),t(e.value)}function j(e,t){t(e.qualification),this.push("."),t(e.id)}function M(e,t){t.join(e.types,{separator:" | "})}function A(e,t){this.push("("),t(e.expression),t(e.typeAnnotation),this.push(")")}function O(e){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=a,n.DeclareFunction=s,n.DeclareModule=o,n.DeclareVariable=u,n.FunctionTypeAnnotation=c,n.FunctionTypeParam=p,n.InterfaceExtends=d,n._interfaceish=f,n.InterfaceDeclaration=h,n.IntersectionTypeAnnotation=m,n.NullableTypeAnnotation=g,n.NumberTypeAnnotation=y,n.StringLiteralTypeAnnotation=v,n.StringTypeAnnotation=b,n.TupleTypeAnnotation=x,n.TypeofTypeAnnotation=E,n.TypeAlias=_,n.TypeAnnotation=w,n.TypeParameterInstantiation=S,n.ObjectTypeAnnotation=I,n.ObjectTypeCallProperty=k,n.ObjectTypeIndexer=T,n.ObjectTypeProperty=C,n.QualifiedTypeIdentifier=j,n.UnionTypeAnnotation=M,n.TypeCastExpression=A,n.VoidTypeAnnotation=O,n.__esModule=!0;var P=L(e("../../types"));n.ClassImplements=d,n.GenericTypeAnnotation=d,n.TypeParameterDeclaration=S},{"../../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 a(e,t){t(e.object),this.push("."),t(e.property)}function s(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 c(e,t){this.push("<"),t(e.name),e.attributes.length>0&&(this.push(" "),t.join(e.attributes,{separator:" "})),this.push(e.selfClosing?" />":">")}function p(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=a,n.JSXSpreadAttribute=s,n.JSXExpressionContainer=o,n.JSXElement=u,n.JSXOpeningElement=c,n.JSXClosingElement=p,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 a(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 s=function(e){return e&&e.__esModule?e:{"default":e}};n._params=r,n._method=l,n.FunctionExpression=i,n.ArrowFunctionExpression=a,n.__esModule=!0;var o=s(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 a(e,t){t(e.local),e.exported&&e.local!==e.exported&&(this.push(" as "),t(e.exported))}function s(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 "),p.call(this,e,t)}function c(e,t){this.push("export default "),p.call(this,e,t)}function p(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=a,n.ExportNamespaceSpecifier=s,n.ExportAllDeclaration=o,n.ExportNamedDeclaration=u,n.ExportDefaultDeclaration=c,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 a(e,t){this.keyword("while"),this.push("("),t(e.test),this.push(")"),t.block(e.body)}function s(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 c(e,t){this.keyword("catch"),this.push("("),t(e.param),this.push(") "),t(e.body)}function p(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"+b(" ",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}},v=function(e){return e&&e.__esModule?e["default"]:e};n.WithStatement=r,n.IfStatement=l,n.ForStatement=i,n.WhileStatement=a,n.DoWhileStatement=s,n.LabeledStatement=o,n.TryStatement=u,n.CatchClause=c,n.ThrowStatement=p,n.SwitchStatement=d,n.SwitchCase=f,n.DebuggerStatement=h,n.VariableDeclaration=m,n.VariableDeclarator=g,n.__esModule=!0;var b=v(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 w=E("of");n.ForOfStatement=w;var S=function(e,t){return function(n,r){this.push(e);var l=n[t||"label"];l&&(this.push(" "),r(l)),this.semicolon()}},I=S("continue");n.ContinueStatement=I;var k=S("return","argument");n.ReturnStatement=k;var T=S("break");n.BreakStatement=T},{"../../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;s(r,function(r,i){t(r),l>i+1&&(n.push("${ "),t(e.expressions[i]),n.push(" }"))}),this._push("`")}var a=function(e){return e&&e.__esModule?e["default"]:e};n.TaggedTemplateExpression=r,n.TemplateElement=l,n.TemplateLiteral=i,n.__esModule=!0;var s=a(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 a(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 s(e,t){var n=this,r=e.elements,l=r.length;this.push("["),p(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 c=function(e){return e&&e.__esModule?e["default"]:e};n.Identifier=r,n.RestElement=l,n.ObjectExpression=i,n.Property=a,n.ArrayExpression=s,n.Literal=o,n._stringLiteral=u,n.__esModule=!0;var p=c(e("lodash/collection/each"));n.SpreadElement=l,n.SpreadProperty=l,n.ObjectPattern=i,n.ArrayPattern=s},{"lodash/collection/each":316}],32:[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},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("detect-indent")),s=l(e("./whitespace")),o=l(e("repeating")),u=l(e("./source-map")),c=l(e("./position")),p=r(e("../messages")),d=l(e("./buffer")),f=l(e("lodash/object/extend")),h=l(e("lodash/collection/each")),m=l(e("./node")),g=r(e("../types")),y=function(){function t(e,n,r){i(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 c,this.map=new u(this.position,n,r),this.buffer=new d(this.position,this.format)}return t.normalizeOptions=function(e,n,r){var l=" ";if(e){var i=a(e).indent;i&&" "!==i&&(l=i)}var s={comments:null==n.comments||n.comments,compact:n.compact,quotes:t.findCommonStringDelimeter(e,r),indent:{adjustMultilineComment:!0,style:l,base:0}};return"auto"===s.compact&&(s.compact=e.length>1e5,s.compact&&console.error(p.get("codeGeneratorDeopt",n.filename,"100KB"))),s},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 a=e.slice(i.start,i.end);"'"===a[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 h(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||m.isUserWhitespacable(e,t)){var i=0;if(null==e.start||e._ignoreUserWhitespace){l||i++,r.addNewlines&&(i+=r.addNewlines(l,e)||0);var a=m.needsWhitespaceAfter;l&&(a=m.needsWhitespaceBefore),a(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 a=m.needsParensNoLineTerminator(e,t),s=a||m.needsParens(e,t);s&&this.push("("),a&&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),a&&(this.newline(),this.dedent()),s&&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(),h(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){g.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(g.isExpressionStatement(n))return[];var l=[],i=[t];return g.isExpressionStatement(t)&&i.push(t.argument),h(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&&h(e,function(e){var n=!1;if(h(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 a=new RegExp("\\n\\s{1,"+i+"}","g");l=l.replace(a,"\n")}var s=Math.max(t.indentSize(),r);l=l.replace(/\n/g,"\n"+o(" ",s))}0===r&&(l=t.getIndent()+l),t._push(l),t.newline(t.whitespace.getNewlinesAfter(e))}})},t}();h(d.prototype,function(e,t){y.prototype[t]=function(){return e.apply(this.buffer,arguments)}}),h(y.generators,function(e){f(y.prototype,e)}),t.exports=function(e,t,n){var r=new y(e,t,n);return r.generate()},t.exports.CodeGenerator=y},{"../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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e){return e&&e.__esModule?e["default"]:e},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("./whitespace")),s=r(e("./parentheses")),o=l(e("lodash/collection/each")),u=l(e("lodash/collection/some")),c=r(e("../../types")),p=function(e,t,n){if(e){for(var r,l=Object.keys(e),i=0;i<l.length;i++){var a=l[i];if(c.is(a,t)){var s=e[a];if(r=s(t,n),null!=r)break}}return r}},d=function(){function e(t,n){i(this,e),this.parent=n,this.node=t}return e.isUserWhitespacable=function(e){return c.isUserWhitespacable(e)},e.needsWhitespace=function(t,n,r){if(!t)return 0;c.isExpressionStatement(t)&&(t=t.expression);var l=p(a.nodes,t,n);if(!l){var i=p(a.list,t,n);if(i)for(var s=0;s<i.length&&!(l=e.needsWhitespace(i[s],t,r));s++);}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(c.isNewExpression(t)&&t.callee===e){if(c.isCallExpression(e))return!0;var n=u(e,function(e){return c.isCallExpression(e)});if(n)return!0}return p(s,e,t)},e.needsParensNoLineTerminator=function(e,t){return t&&e.leadingComments&&e.leadingComments.length?c.isYieldExpression(t)||c.isAwaitExpression(t)?!0:c.isContinueStatement(t)||c.isBreakStatement(t)||c.isReturnStatement(t)||c.isThrowStatement(t)?!0:!1:!1},e}();t.exports=d,o(d,function(e,t){d.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 d[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 a(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=v[n],l=e.operator,i=v[l];if(r>i)return!0;if(r===i&&t.right===e)return!0}}function s(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 c(e,t){return y.isExpressionStatement(t)}function p(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=a,n.BinaryExpression=s,n.SequenceExpression=o,n.YieldExpression=u,n.ClassExpression=c,n.UnaryLike=p,n.FunctionExpression=d,n.ConditionalExpression=f,n.__esModule=!0;var g=m(e("lodash/collection/each")),y=h(e("../../types")),v={};g([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(e,t){g(e,function(e){v[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(p.isMemberExpression(e))r(e.object,t),e.computed&&r(e.property,t);else if(p.isBinary(e)||p.isAssignmentExpression(e))r(e.left,t),r(e.right,t);else if(p.isCallExpression(e))t.hasCall=!0,r(e.callee,t);else if(p.isFunction(e))t.hasFunction=!0;else if(p.isIdentifier(e)){var n=t;n.hasHelper||(n.hasHelper=l(e.callee))}return t}function l(e){return p.isMemberExpression(e)?l(e.object)||l(e.property):p.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:p.isCallExpression(e)?l(e.callee):p.isBinary(e)||p.isAssignmentExpression(e)?p.isIdentifier(e.left)&&l(e.left)||l(e.right):!1}function i(e){return p.isLiteral(e)||p.isObjectExpression(e)||p.isArrayExpression(e)||p.isIdentifier(e)||p.isMemberExpression(e)}var a=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e},o=s(e("lodash/lang/isBoolean")),u=s(e("lodash/collection/each")),c=s(e("lodash/collection/map")),p=a(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 p.isFunction(e.left)||p.isFunction(e.right)?{after:!0}:void 0},Literal:function(e){return"use strict"===e.value?{after:!0}:void 0},CallExpression:function(e){return p.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],a=l(n.id)&&!i(n.init);if(!a){var s=r(n.init);a=l(n.init)&&s.hasCall||s.hasFunction}if(a)return{before:!0,after:!0}}},IfStatement:function(e){return p.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 c(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(p.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,n){"use strict";var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=function(){function e(){r(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=l},{}],37:[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},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("source-map")),s=r(e("../types")),o=function(){function e(t,n,r){i(this,e),this.position=t,this.opts=n,n.sourceMaps?(this.map=new a.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=o},{"../types":153,"source-map":441}],38:[function(e,t,n){"use strict";function r(e,t,n){return e+=t,e>=n&&(e-=n),e}var l=function(e){return e&&e.__esModule?e["default"]:e},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("lodash/collection/sortBy")),s=function(){function e(t,n){i(this,e),this.tokens=a(t.concat(n),"start"),this.used={},this._lastFoundIndex=0}return e.prototype.getNewlinesBefore=function(e){for(var t,n,l,i=this.tokens,a=0;a<i.length;a++){var s=r(a,this._lastFoundIndex,this.tokens.length);if(l=i[s],e.start===l.start){t=i[s-1],n=l,this._lastFoundIndex=s;break}}return this.getNewlinesBetween(t,n)},e.prototype.getNewlinesAfter=function(e){for(var t,n,l,i=this.tokens,a=0;a<i.length;a++){var s=r(a,this._lastFoundIndex,this.tokens.length);if(l=i[s],e.end===l.end){t=l,n=i[s+1],this._lastFoundIndex=s;break}}if(n&&"eof"===n.type.label)return 1;var o=this.getNewlinesBetween(t,n);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,n){"use strict";function r(e){var t=o.matchToToken(e);if("name"===t.type&&u.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 l(e){return e.replace(o,function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];var l=r(t),i=p[l];return i?t[0].split(d).map(function(e){return i(e)}).join("\n"):t[0]})}var i=function(e){return e&&e.__esModule?e["default"]:e},a=i(e("line-numbers")),s=i(e("repeating")),o=i(e("js-tokens")),u=i(e("esutils")),c=i(e("chalk")),p={string:c.red,punctuator:c.bold,curly:c.green,parens:c.blue.bold,square:c.yellow,keyword:c.cyan,number:c.magenta,regex:c.magenta,comment:c.grey,invalid:c.inverse},d=/\r\n|[\n\r\u2028\u2029]/;t.exports=function(e,t,n){var r=void 0===arguments[3]?{}:arguments[3];n=Math.max(n,0),r.highlightCode&&c.supportsColor&&(e=l(e)),e=e.split(d);var i=Math.max(t-3,0),o=Math.min(e.length,t+3);return t||n||(i=0,o=e.length),a(e.slice(i,o),{start:i+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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../types"));t.exports=function(e,t,n){if(e&&"Program"===e.type)return l.file(e,t||[],n||[]);throw new Error("Not a valid ast?")}},{"../types":153}],41:[function(e,t,n){"use strict";t.exports=function(){return Object.create(null)}},{}],42:[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},i=l(e("./normalize-ast")),a=l(e("estraverse")),s=l(e("./code-frame")),o=r(e("../../acorn"));t.exports=function(e,t,n){try{var r=[],l=[],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:l,ranges:!0};e.nonStandard&&(u.plugins.jsx=!0,u.plugins.flow=!0);var c=o.parse(t,u);return a.attachComments(c,r,l),c=i(c,r,l),n?n(c):c}catch(p){if(!p._babel){p._babel=!0;var d=p.message=""+e.filename+": "+p.message,f=p.loc;if(f&&(p.codeFrame=s(t,f.line,f.column+1,e),d+="\n"+p.codeFrame),p.stack){var h=p.stack.replace(p.message,d);try{p.stack=h}catch(m){}}}throw p}}},{"../../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=s[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 a.inspect(e)}})}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.get=r,n.parseArgs=l,n.__esModule=!0;var a=i(e("util")),s={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=s},{util:199}],44:[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},i=l(e("estraverse")),a=l(e("lodash/object/extend")),s=l(e("ast-types")),o=r(e("./types"));a(i.VisitorKeys,o.VISITOR_KEYS);var u=s.Type.def,c=s.Type.or;u("File").bases("Node").build("program").field("program",u("Program")),u("AssignmentPattern").bases("Pattern").build("left","right").field("left",u("Pattern")).field("right",u("Expression")),u("RestElement").bases("Pattern").build("argument").field("argument",u("expression")),u("DoExpression").bases("Expression").build("body").field("body",[u("Statement")]),u("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration",c(u("Declaration"),u("Expression"),null)),u("ExportNamedDeclaration").bases("Declaration").build("declaration").field("declaration",c(u("Declaration"),u("Expression"),null)).field("specifiers",[c(u("ExportSpecifier"))]).field("source",c(u("ModuleSpecifier"),null)),s.finalize()},{"./types":153,"ast-types":171,estraverse:296,"lodash/object/extend":406}],45:[function(e,t,n){"use strict";function r(e){if(!o.existsSync)return!1;var t=u[e];return null!=t?t:u[e]=o.existsSync(e)}var l=function(e){return e&&e.__esModule?e["default"]:e},i=l(e("strip-json-comments")),a=l(e("lodash/object/merge")),s=l(e("path")),o=l(e("fs")),u={},c={};t.exports=function(e){function t(e,l){var u=s.join(e,l);if(r(u)){var p,d=o.readFileSync(u,"utf8");try{var f,h;f=c,h=d,!f[h]&&(f[h]=JSON.parse(i(d))),p=f[h]}catch(m){throw m.message=""+u+": "+m.message,m}if(p.breakConfig)return;a(n,p,function(e,t){return Array.isArray(e)?e.concat(t):void 0})}var g=s.dirname(e);g!==e&&t(g,l)}var n=void 0===arguments[1]?{}:arguments[1],l=".babelrc";return n.breakConfig!==!0&&t(e,l),n}},{fs:172,"lodash/object/merge":410,path:182,"strip-json-comments":452}],46:[function(e,t,n){(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},a=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")},s=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")),c=i(e("shebang-regex")),p=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")),v=i(e("lodash/object/defaults")),b=i(e("lodash/collection/includes")),x=(i(e("../../traversal")),i(e("lodash/object/assign"))),E=i(e("./logger")),_=i(e("../../helpers/parse")),w=(i(e("../../traversal/scope")),i(e("slash"))),S=l(e("../../util")),I=i(e("path")),k=i(e("lodash/collection/each")),T=l(e("../../types")),C={enter:function(e,t,n,l){r(l.stack,e,n)}},j=function(){function t(){var e=void 0===arguments[0]?{}:arguments[0];s(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=I.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],a=e[l];if(a||!i.optional){if(a&&i.deprecated)throw new Error("Deprecated option "+l+": "+i.deprecated);null==a&&(a=i["default"]||a);var s=u[i.type];if(s&&(a=s(l,a)),i.alias){var o=e,c=i.alias;o[c]||(o[c]=a)}else e[l]=a}}return e.inputSourceMap&&(e.sourceMaps=!0),e.filename=w(e.filename),e.sourceRoot&&(e.sourceRoot=w(e.sourceRoot)),e.moduleId&&(e.moduleIds=!0),e.basename=I.basename(e.filename,I.extname(e.filename)),e.ignore=S.arrayify(e.ignore,S.regexify),e.only=S.arrayify(e.only,S.regexify),v(e,{moduleRoot:e.sourceRoot}),v(e,{sourceRoot:e.moduleRoot}),v(e,{filenameRelative:e.filename}),v(e,{sourceFileName:e.filenameRelative,sourceMapName:e.filenameRelative}),e.externalHelpers&&this.set("helpersNamespace",T.identifier("babelHelpers")),e},t.prototype.isLoose=function(e){return b(this.opts.loose,e)},t.prototype.buildTransformers=function(){var e=this,t=this.transformers={},n=[],r=[];k(g.transformers,function(l,i){var a=t[i]=l.buildPass(e);a.canTransform()&&(r.push(a),l.metadata.secondPass&&n.push(a),l.manipulateOptions&&l.manipulateOptions(e.opts,e))});for(var l=[],i=[],a=0;a<e.opts.plugins.length;a++)this.addPlugin(e.opts.plugins[a],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=S.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 s=t.split(":"),o=a(s,2);t=o[0];var u=o[1];i=void 0===u?"before":u;var c=S.resolveRelative(t)||S.resolveRelative("babel-plugin-"+t);if(!c)throw new ReferenceError("Unknown plugin "+JSON.stringify(t));l=e(c)}else l=t;if("before"!==i&&"after"!==i)throw new TypeError("Plugin "+JSON.stringify(t)+" has an illegal position of "+JSON.stringify(i));var p=l.key;if(this.transformers[p])throw new ReferenceError("The key for plugin "+JSON.stringify(t)+" of "+p+" 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[p]=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=c.exec(e);return t&&(this.shebang=t[0],e=e.replace(c,"")),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(t){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=[T.importDefaultSpecifier(r)],i=T.importDeclaration(l,T.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 T.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(!b(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 a=T.identifier(T.toIdentifier(e));return T.memberExpression(i,a)}var s=S.template("helper-"+e);s._compact=!0;var o=this.scope.generateUidIdentifier(e);return this.scope.push({key:e,id:o,init:s}),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 S.shouldIgnore(e.filename,e.ignore,e.only)},t.prototype.parse=function(e){var t=function(t){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 a=this.transformers[i];l[i]=a.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=p.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=T.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(t,n){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 a=i.toJSON();return a.sources=n.sources,a.file=n.file,a}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=j}).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,n){"use strict";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("../../util")),a=function(){function e(t,n){l(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){i.debug(this._buildMessage(e))},e.prototype.deopt=function(e,t){i.debug(this._buildMessage(t))},e}();t.exports=a},{"../../util":157}],48:[function(e,t,n){"use strict";function r(e,t){return t=p.arrayify(t),(t.indexOf("all")>=0||t.indexOf(!0)>=0)&&(t=Object.keys(c.transformers)),c._ensureTransformerNames(e,t)}function l(e,t){return+t}function i(e,t){return!!t}function a(e,t){return p.booleanify(t)}function s(e,t){return p.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=a,n.list=s,n.__esModule=!0;var c=u(e("./../index")),p=o(e("../../util"))},{"../../util":157,"./../index":63}],49:[function(e,t,n){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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e){return e&&e.__esModule?e["default"]:e},i=l(e("./explode-assignable-expression")),a=r(e("../../types"));t.exports=function(e,t){var n=function(e){return e.operator===t.operator+"="},r=function(e,t){return a.assignmentExpression("=",e,t)};e.ExpressionStatement=function(e,l,s,o){if(!o.isConsequenceExpressionStatement(e)){var u=e.expression;if(n(u)){var c=[],p=i(u.left,c,o,s,!0);return c.push(a.expressionStatement(r(p.ref,t.build(p.uid,u.right)))),c}}},e.AssignmentExpression=function(e,l,a,s){if(n(e)){var o=[],u=i(e.left,o,s,a);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,n){"use strict";function r(e,t){var n=e.blocks.shift();if(n){var l=r(e,t);return l||(l=t(),e.filter&&(l=i.ifStatement(e.filter,i.blockStatement([l])))),i.forOfStatement(i.variableDeclaration("let",[i.variableDeclarator(n.left)]),n.right,i.blockStatement([l]))}}var l=function(e){return e&&e.__esModule?e:{"default":e}};t.exports=r;var i=l(e("../../types"))},{"../../types":153}],52:[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},i=l(e("lodash/lang/isString")),a=r(e("../../messages")),s=l(e("esutils")),o=r(e("./react")),u=r(e("../../types"));t.exports=function(e,t){e.check=function(e){return u.isJSX(e)?!0:o.isCreateClass(e)?!0:!1},e.JSXIdentifier=function(e,t){return"this"===e.name&&u.isReferenced(e,t)?u.thisExpression():s.keyword.isIdentifierName(e.name)?void(e.type="Identifier"):u.literal(e.name)},e.JSXNamespacedName=function(e,t,n,r){throw this.errorWithNode(a.get("JSXNamespacedTags"))},e.JSXMemberExpression={exit:function(e){e.computed=u.isLiteral(e.property),e.type="MemberExpression"}},e.JSXExpressionContainer=function(e){return e.expression},e.JSXAttribute={enter:function(e){var t=e.value;u.isLiteral(t)&&i(t.value)&&(t.value=t.value.replace(/\n\s+/g," "))},exit:function(e){var t=e.value||u.literal(!0);return u.inherits(u.property("init",e.name,t),e)}},e.JSXOpeningElement={exit:function(e,r,l,i){var a,s=e.name,o=[];u.isIdentifier(s)?a=s.name:u.isLiteral(s)&&(a=s.value);var c={tagExpr:s,tagName:a,args:o};t.pre&&t.pre(c,i);var p=e.attributes;return p=p.length?n(p,i):u.literal(null),o.push(p),t.post&&t.post(c,i),c.call||u.callExpression(c.callee,o)}};var n=function(e,t){for(var n=[],r=[],l=function(){n.length&&(r.push(u.objectExpression(n)),n=[])};e.length;){var i=e.shift();u.isJSXSpreadAttribute(i)?(l(),r.push(i.argument)):n.push(i)}return l(),1===r.length?e=r[0]:(u.isObjectExpression(r[0])||r.unshift(u.objectExpression([])),e=u.callExpression(t.addHelper("extends"),r)),e};e.JSXElement={enter:function(e){e.children=o.buildChildren(e)},exit:function(e){var t=e.openingElement;return t.arguments=t.arguments.concat(e.children),t.arguments.length>=3&&(t._prettyCall=!0),u.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(u.isIdentifier(i.key,{name:"displayName"})){r=!1;break}}r&&n.unshift(u.property("init",u.identifier("displayName"),u.literal(e)))};e.ExportDefaultDeclaration=function(e,t,n,l){o.isCreateClass(e.declaration)&&r(l.opts.basename,e.declaration)},e.AssignmentExpression=e.Property=e.VariableDeclarator=function(e){var t,n;u.isAssignmentExpression(e)?(t=e.left,n=e.right):u.isProperty(e)?(t=e.key,n=e.value):u.isVariableDeclarator(e)&&(t=e.id,n=e.init),u.isMemberExpression(t)&&(t=t.property),u.isIdentifier(t)&&o.isCreateClass(n)&&r(t.name,n)}}},{"../../messages":43,"../../types":153,"./react":58,esutils:300,"lodash/lang/isString":401}],53:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../../types"));t.exports=function(e){var t=l.functionExpression(null,[],e.body,e.generator,e.async);t.shadow=!0;var n=l.callExpression(t,[]);return e.generator&&(n=l.yieldExpression(n,!0)),l.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),a={};p(e,i)&&(a=e[i]),e[i]=a,a._key=t,r&&(a._computed=!0),a[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 a(e){var t=d.objectExpression([]);return c(e,function(e){var n=d.objectExpression([]),r=d.property("init",e._key,n,e._computed);c(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 s(e){return c(e,function(e){e.value&&(e.writable=d.literal(!0)),e.configurable=d.literal(!0),e.enumerable=d.literal(!0)}),a(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=a,n.toDefineObject=s,n.__esModule=!0;var c=(u(e("lodash/lang/cloneDeep")),u(e("../../traversal")),u(e("lodash/collection/each"))),p=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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../../types")),i=function(e,t,n,r){var i;if(l.isIdentifier(e)){if(r.hasBinding(e.name))return e;i=e}else{if(!l.isMemberExpression(e))throw new Error("We can't explode this node type "+e.type);if(i=e.object,l.isIdentifier(i)&&r.hasGlobal(i.name))return i}var a=r.generateUidBasedOnNode(i);return t.push(l.variableDeclaration("var",[l.variableDeclarator(a,i)])),a},a=function(e,t,n,r){var i=e.property,a=l.toComputedKey(e,i);if(l.isLiteral(a))return a;var s=r.generateUidBasedOnNode(i);return t.push(l.variableDeclaration("var",[l.variableDeclarator(s,i)])),s};t.exports=function(e,t,n,r,s){var o;o=l.isIdentifier(e)&&s?e:i(e,t,n,r);var u,c;if(l.isIdentifier(e))u=e,c=o;else{var p=a(e,t,n,r),d=e.computed||l.isLiteral(p);c=u=l.memberExpression(o,p,d)}return{uid:c,ref:u}}},{"../../types":153}],56:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../../types"));t.exports=function(e){for(var t=0,n=0;n<e.params.length;n++)l.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=c.toComputedKey(e,e.key);if(!c.isLiteral(r))return e;var l=c.toIdentifier(r.value),i=c.identifier(l),a=e.value,s=f(a,l,n);e.value=d(s,a,i,n)}function i(e,t,n){if(e.id)return e;var r;if(!c.isProperty(t)||"init"!==t.kind||t.computed&&!c.isLiteral(t.key)){if(!c.isVariableDeclarator(t))return e;r=t.id}else r=t.key;var l;if(c.isLiteral(r))l=r.value;else{if(!c.isIdentifier(r))return;l=r.name}l=c.toIdentifier(l),r=c.identifier(l);var i=f(e,l,n);return d(i,e,r,n)}var a=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.custom=r,n.property=l,n.bare=i,n.__esModule=!0;var o=s(e("./get-function-arity")),u=a(e("../../util")),c=a(e("../../types")),p={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");var i=u.template(l,{FUNCTION:t,FUNCTION_ID:n,FUNCTION_KEY:r.generateUidIdentifier(n.name)});i.callee._skipModulesRemap=!0;for(var a=i.callee.body.body[0].params,s=0,c=o(t);c>s;s++)a.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,p,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(!c(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 a=r[n],s=0===n,o=n===r.length-1,c=n===l,p=a.replace(/\t/g," ");s||(p=p.replace(/^[ ]+/,"")),o||(p=p.replace(/[ ]+$/,"")),p&&(c||(p+=" "),i+=p)}i&&t.push(u.literal(i))}function a(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 s=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=a,n.__esModule=!0;var u=(o(e("lodash/lang/isString")),s(e("../../types"))),c=u.buildMatchMemberExpression("React.createClass"),p=u.buildMatchMemberExpression("React.Component");n.isReactComponent=p},{"../../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||(s(n,t),e.regex.flags=n.join(""))}var i=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e};n.is=r,n.pullFlag=l,n.__esModule=!0;var s=a(e("lodash/array/pull")),o=i(e("../../types"))},{"../../types":153,"lodash/array/pull":313}],60:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../../types")),i={enter:function(e,t,n,r){l.isFunction(e)&&this.skip(),l.isAwaitExpression(e)&&(e.type="YieldExpression",e.all&&(e.all=!1,e.argument=l.callExpression(l.memberExpression(l.identifier("Promise"),l.identifier("all")),[e.argument])))}},a={enter:function(e,t,n,r){var i=r.id.name;if(l.isReferencedIdentifier(e,t,{name:i})&&n.bindingIdentifierEquals(i,r.id)){var a;return a=r,!a.ref&&(a.ref=n.generateUidIdentifier(i)),a.ref}}};t.exports=function(e,t,n){e.async=!1,e.generator=!0,n.traverse(e,i,u);var r=l.callExpression(t,[e]),s=e.id;if(e.id=null,l.isFunctionDeclaration(e)){var o=l.variableDeclaration("let",[l.variableDeclarator(s,r)]);return o._blockHoist=!0,o}if(s){var u={id:s};if(n.traverse(e,a,u),u.ref)return n.parent.push({id:u.ref}),l.assignmentExpression("=",u.ref,r)}return r}},{"../../types":153}],61:[function(e,t,n){"use strict";function r(e,t){return u.isSuper(e)?u.isMemberExpression(t,{computed:!1})?!1:u.isCallExpression(t,{callee:e})?!1:!0:!1}function l(e){return u.isMemberExpression(e)&&u.isSuper(e.object)}var i=function(e){return e&&e.__esModule?e:{"default":e}},a=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")},o=i(e("../../messages")),u=i(e("../../types")),c={enter:function(e,t,n,r){var l=r.topLevel,i=r.self;if(u.isFunction(e)&&!u.isArrowFunctionExpression(e))return i.traverseLevel(this,!1),this.skip();if(u.isProperty(e,{method:!0})||u.isMethodDefinition(e))return this.skip();var a=l?u.thisExpression:i.getThisReference.bind(i),s=i.specHandle;i.isLoose&&(s=i.looseHandle);var o=s.call(i,this,a);return o&&(this.hasSuper=!0),o!==!0?o: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 u.callExpression(this.file.addHelper("set"),[u.callExpression(u.memberExpression(u.identifier("Object"),u.identifier("getPrototypeOf")),[this.isStatic?this.getObjectRef():u.memberExpression(this.getObjectRef(),u.identifier("prototype"))]),n?e:u.literal(e.name),t,r])},e.prototype.getSuperProperty=function(e,t,n){return u.callExpression(this.file.addHelper("get"),[u.callExpression(u.memberExpression(u.identifier("Object"),u.identifier("getPrototypeOf")),[this.isStatic?this.getObjectRef():u.memberExpression(this.getObjectRef(),u.identifier("prototype"))]),t?e:u.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(c,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(u.variableDeclaration("var",[u.variableDeclarator(this.topLevelThisReference,u.thisExpression())])),e},e.prototype.getLooseSuperProperty=function(e,t){var n=this.methodNode,r=n.key,l=this.superRef||u.identifier("Function");return t.property===e?void 0:u.isCallExpression(t,{callee:e})?(t.arguments.unshift(u.thisExpression()),"constructor"===r.name?u.memberExpression(l,u.identifier("call")):(e=l,n["static"]||(e=u.memberExpression(e,u.identifier("prototype"))),e=u.memberExpression(e,r,n.computed),u.memberExpression(e,u.identifier("call")))):u.isMemberExpression(t)&&!n["static"]?u.memberExpression(l,u.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(!u.isMemberExpression(r))return;if(!u.isSuper(r.object))return;return u.appendToMemberExpression(r,u.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")),[u.variableDeclaration("var",[u.variableDeclarator(e,n.left)]),u.expressionStatement(u.assignmentExpression("=",n.left,u.binaryExpression(n.operator[0],e,n.right)))]); },e.prototype.specHandle=function(e,t){var n,i,s,c,p=this.methodNode,d=e.parent,f=e.node;if(r(f,d))throw e.errorWithNode(o.get("classesIllegalBareSuper"));if(u.isCallExpression(f)){var h=f.callee;if(u.isSuper(h)){if(n=p.key,i=p.computed,s=f.arguments,"constructor"!==p.key.name||!this.inClass){var m=p.key.name||"METHOD_NAME";throw this.file.errorWithNode(f,o.get("classesIllegalSuperCall",m))}}else l(h)&&(n=h.property,i=h.computed,s=f.arguments)}else if(u.isMemberExpression(f)&&u.isSuper(f.object))n=f.property,i=f.computed;else{if(u.isUpdateExpression(f)&&l(f.argument)){var g=u.binaryExpression(f.operator[0],f.argument,u.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(u.expressionStatement(y))}if(u.isAssignmentExpression(f)&&l(f.left))return this.specHandleAssignmentExpression(null,e,f,t)}if(n){c=t();var v=this.getSuperProperty(n,i,c);return s?1===s.length&&u.isSpreadElement(s[0])?u.callExpression(u.memberExpression(v,u.identifier("apply")),[c,s[0].argument]):u.callExpression(u.memberExpression(v,u.identifier("call")),[c].concat(a(s))):v}},e}();t.exports=p},{"../../messages":43,"../../types":153}],62:[function(e,t,n){"use strict";function r(e){var t=e.body[0];return a.isExpressionStatement(t)&&a.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 a=i(e("../../types"))},{"../../types":153}],63:[function(e,t,n){"use strict";function r(e,t){var n=new o(t);return n.parse(e)}var l=function(e){return e&&e.__esModule?e["default"]:e};t.exports=r;var i=l(e("../helpers/normalize-ast")),a=l(e("./transformer")),s=l(e("../helpers/object")),o=l(e("./file")),u=l(e("lodash/collection/each"));r.fromAst=function(e,t,n){e=i(e);var r=new o(n);return r.addCode(t),r.transform(e),r.generate()},r._ensureTransformerNames=function(e,t){for(var n=[],l=0;l<t.length;l++){var i=t[l],a=r.deprecatedTransformerMap[i],s=r.aliasTransformerMap[i];if(s)n.push(s);else if(a)console.error("The transformer "+i+" has been renamed to "+a),t.push(a);else if(r.transformers[i])n.push(i);else{if(!r.namespaces[i])throw new ReferenceError("Unknown transformer "+i+" specified in "+e);n=n.concat(r.namespaces[i])}}return n},r.transformerNamespaces=s(),r.transformers=s(),r.namespaces=s(),r.deprecatedTransformerMap=e("./transformers/deprecated"),r.aliasTransformerMap=e("./transformers/aliases"),r.moduleFormatters=e("./modules");var c=l(e("./transformers"));u(c,function(e,t){var n=t.split(".")[0],l=r.namespaces,i=n;l[i]||(l[i]=[]),r.namespaces[n].push(t),r.transformerNamespaces[t]=n,r.transformers[t]=new a(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,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e},l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("../../messages")),s=r(e("../../traversal")),o=r(e("lodash/object/extend")),u=r(e("../../helpers/object")),c=l(e("../../util")),p=l(e("../../types")),d={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 a=p.assignmentExpression(e.operator[0]+"=",e.argument,p.literal(1)),s=r.remapExportAssignment(a,i);if(p.isExpressionStatement(t)||e.prefix)return s;var o=[];o.push(s);var u;return u="--"===e.operator?"+":"-",o.push(p.binaryExpression(u,e.argument,p.literal(1))),p.sequenceExpression(o)}}if(e._skipModulesRemap)return this.skip();if(p.isAssignmentExpression(e)&&!e._ignoreModulesRemap){var i=r.getExport(e.left,n);if(i)return this.skip(),r.remapExportAssignment(e,i)}}},f={ImportDeclaration:{enter:function(e,t,n,r){r.hasLocalImports=!0,o(r.localImports,this.getBindingIdentifiers())}}},h=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 a in i){var s=i[a];r._addExport(a,s)}}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)}}}}),m=function(){function e(t){i(this,e),this.internalRemap=u(),this.defaultIds=u(),this.scope=t.scope,this.file=t,this.ids=u(),this.hasNonDefaultExports=!1,this.hasLocalExports=!1,this.hasLocalImports=!1,this.localExports=u(),this.localImports=u(),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(h,this)},e.prototype.getLocalImports=function(){this.file.path.traverse(f,this)},e.prototype.remapAssignments=function(){(this.hasLocalExports||this.hasLocalImports)&&this.file.path.traverse(d,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,a.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),c.template("exports-from-assign",{INIT:t,ID:p.literal(e.name)},!0)},e.prototype.buildExportsAssignment=function(e,t){return this.checkExportIdentifier(e),c.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 a=n.declarations[i];a.init=this.buildExportsAssignment(a.id,a.init,e).expression;var s=p.variableDeclaration(n.kind,[a]);0===i&&p.inherits(s,n),t.push(s)}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=m},{"../../helpers/object":41,"../../messages":43,"../../traversal":144,"../../types":153,"../../util":157,"lodash/object/extend":406}],65:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=r(e("../../util"));t.exports=function(e){var t=function(){this.noInteropRequireImport=!0,this.noInteropRequireExport=!0,e.apply(this,arguments)};return l.inherits(t,e),t}},{"../../util":157}],66:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("./amd")),i=r(e("./_strict"));t.exports=i(l)},{"./_strict":65,"./amd":67}],67:[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},i=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)},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=l(e("./_default")),o=l(e("./common")),u=l(e("lodash/collection/includes")),c=l(e("lodash/object/values")),p=r(e("../../util")),d=r(e("../../types")),f=function(e){function t(){a(this,t),null!=e&&e.apply(this,arguments)}return i(t,e),t.prototype.init=function(){o.prototype._init.call(this,this.hasNonDefaultExports)},t.prototype.buildDependencyLiterals=function(){var e=[];for(var t in this.ids)e.push(d.literal(t));return e},t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments);var t=e.body,n=[d.literal("exports")];this.passModuleArg&&n.push(d.literal("module")),n=n.concat(this.buildDependencyLiterals()),n=d.arrayExpression(n);var r=c(this.ids);this.passModuleArg&&r.unshift(d.identifier("module")),r.unshift(d.identifier("exports"));var l=d.functionExpression(null,r,d.blockStatement(t)),i=[n,l],a=this.getModuleName();a&&i.unshift(d.literal(a));var o=d.callExpression(d.identifier("define"),i);e.body=[d.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((d.isImportNamespaceSpecifier(e)||d.isImportDefaultSpecifier(e))&&(this.defaultIds[r]=e.local),u(this.file.dynamicImportedNoDefault,t))this.ids[t.source.value]=l;else if(d.isImportNamespaceSpecifier(e));else if(u(this.file.dynamicImported,t)||!d.isSpecifierDefault(e)||this.noInteropRequireImport){var i=e.imported;d.isSpecifierDefault(e)&&(i=d.identifier("default")),l=d.memberExpression(l,i)}else{var a=this.scope.generateUidIdentifier(e.local.name);n.push(d.variableDeclaration("var",[d.variableDeclarator(a,d.callExpression(this.file.addHelper("interop-require"),[l]))])),l=a}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)):o.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 d.isFunctionDeclaration(n)&&(r._blockHoist=3),void t.push(r)}s.prototype.exportDeclaration.apply(this,arguments)},t}(s);t.exports=f},{"../../types":153,"../../util":157,"./_default":64,"./common":69,"lodash/collection/includes":319,"lodash/object/values":411}],68:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("./common")),i=r(e("./_strict"));t.exports=i(l)},{"./_strict":65,"./common":69}],69:[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},i=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)},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=l(e("./_default")),o=l(e("lodash/collection/includes")),u=r(e("../../util")),c=r(e("../../types")),p=function(e){function t(){a(this,t),null!=e&&e.apply(this,arguments)}return i(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=u.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(c.expressionStatement(c.assignmentExpression("=",c.memberExpression(c.identifier("module"),c.identifier("exports")),c.memberExpression(c.identifier("exports"),c.identifier("default")))))},t.prototype.importSpecifier=function(e,t,n){var r=e.local,l=this.getExternalReference(t,n);if(c.isSpecifierDefault(e)){if(o(this.file.dynamicImportedNoDefault,t))this.internalRemap[r.name]=l;else if(this.noInteropRequireImport)this.internalRemap[r.name]=c.memberExpression(l,c.identifier("default"));else if(!o(this.file.dynamicImported,t)){var i=this.scope.generateUidBasedOnNode(t,"import");n.push(c.variableDeclaration("var",[c.variableDeclarator(i,c.callExpression(this.file.addHelper("interop-require-wildcard"),[l]))])),this.internalRemap[r.name]=c.memberExpression(i,c.identifier("default"))}}else c.isImportNamespaceSpecifier(e)?(this.noInteropRequireImport||(l=c.callExpression(this.file.addHelper("interop-require-wildcard"),[l])),n.push(c.variableDeclaration("var",[c.variableDeclarator(r,l)]))):this.internalRemap[r.name]=c.memberExpression(l,e.imported)},t.prototype.importDeclaration=function(e,t){t.push(u.template("require",{MODULE_NAME:e.source},!0))},t.prototype.exportSpecifier=function(e,t,n){this.doDefaultExportInterop(e)&&(this.hasDefaultOnlyExport=!0),s.prototype.exportSpecifier.apply(this,arguments)},t.prototype.exportDeclaration=function(e,t){this.doDefaultExportInterop(e)&&(this.hasDefaultOnlyExport=!0),s.prototype.exportDeclaration.apply(this,arguments)},t.prototype._getExternalReference=function(e,t){var n,r=(e.source.value,c.callExpression(c.identifier("require"),[e.source]));o(this.file.dynamicImported,e)&&!o(this.file.dynamicImportedNoDefault,e)?(r=c.memberExpression(r,c.identifier("default")),n=e.specifiers[0].local):n=this.scope.generateUidBasedOnNode(e,"import");var l=c.variableDeclaration("var",[c.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,n){"use strict";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("../../types")),a=function(){function e(){l(this,e)}return e.prototype.exportDeclaration=function(e,t){var n=i.toStatement(e.declaration,!0);n&&t.push(i.inherits(n,e))},e.prototype.exportAllDeclaration=function(){},e.prototype.importDeclaration=function(){},e.prototype.importSpecifier=function(){},e.prototype.exportSpecifier=function(){},e}();t.exports=a},{"../../types":153}],71:[function(e,t,n){"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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e){return e&&e.__esModule?e["default"]:e},i=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)},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=l(e("./_default")),o=l(e("./amd")),u=r(e("../../util")),c=l(e("lodash/array/last")),p=l(e("lodash/collection/each")),d=l(e("lodash/collection/map")),f=r(e("../../types")),h=function(e,t){return e._blockHoist&&!t.transformers.runtime.canTransform()},m={enter:function(e,t,n,r){if(f.isFunction(e))return this.skip();if(f.isVariableDeclaration(e)){if("var"!==e.kind&&!f.isProgram(t))return;if(h(e,n.file))return;for(var l=[],i=0;i<e.declarations.length;i++){var a=e.declarations[i];if(r.push(f.variableDeclarator(a.id)),a.init){var s=f.expressionStatement(f.assignmentExpression("=",a.id,a.init));l.push(s)}}if(f.isFor(t)){if(t.left===e)return e.declarations[0].id;if(t.init===e)return l}return l}}},g={enter:function(e,t,n,r){f.isFunction(e)&&this.skip(),(f.isFunctionDeclaration(e)||h(e,n.file))&&(r.push(e),this.remove())}},y={enter:function(e,t,n,r){e._importSource===r.source&&(f.isVariableDeclaration(e)?p(e.declarations,function(e){r.hoistDeclarators.push(f.variableDeclarator(e.id)),r.nodes.push(f.expressionStatement(f.assignmentExpression("=",e.id,e.init)))}):r.nodes.push(e),this.remove())}},v=function(e){function t(e){a(this,t),this.exportIdentifier=e.scope.generateUidIdentifier("export"),this.noInteropRequireExport=!0,this.noInteropRequireImport=!0,s.apply(this,arguments)}return i(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=f.memberExpression(e,n,!0),l=f.variableDeclaration("var",[f.variableDeclarator(n)]),i=e,a=f.blockStatement([f.expressionStatement(this.buildExportCall(n,r))]);return this._addImportSource(f.forInStatement(l,i,a),t)},t.prototype.buildExportsAssignment=function(e,t,n){var r=this.buildExportCall(f.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(f.literal(t[r].name),n);return n},t.prototype.buildExportCall=function(e,t,n){var r=f.callExpression(this.exportIdentifier,[e,t]);return n?f.expressionStatement(r):r},t.prototype.importSpecifier=function(e,t,n){o.prototype.importSpecifier.apply(this,arguments);for(var r in this.internalRemap)n.push(f.variableDeclaration("var",[f.variableDeclarator(f.identifier(r),this.internalRemap[r])]));this.internalRemap={},this._addImportSource(c(n),t)},t.prototype.buildRunnerSetters=function(e,t){var n=this.file.scope;return f.arrayExpression(d(this.ids,function(r,l){var i={hoistDeclarators:t,source:l,nodes:[]};return n.traverse(e,y,i),f.functionExpression(null,[r],f.blockStatement(i.nodes))}))},t.prototype.transform=function(e){s.prototype.transform.apply(this,arguments);var t=[],n=this.getModuleName(),r=f.literal(n),l=f.blockStatement(e.body),i=u.template("system",{MODULE_DEPENDENCIES:f.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,MODULE_NAME:r,SETTERS:this.buildRunnerSetters(l,t),EXECUTE:f.functionExpression(null,[],l)},!0),a=i.expression.arguments[2].body.body;n||i.expression.arguments.shift();var o=a.pop();if(this.file.scope.traverse(l,m,t),t.length){var c=f.variableDeclaration("var",t);c._blockHoist=!0,a.unshift(c)}this.file.scope.traverse(l,g,a),a.push(o),e.body=[i]},t}(o);t.exports=v},{"../../types":153,"../../util":157,"./_default":64,"./amd":67,"lodash/array/last":312,"lodash/collection/each":316,"lodash/collection/map":320}],73:[function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e["default"]:e},l=r(e("./umd")),i=r(e("./_strict"));t.exports=i(l)},{"./_strict":65,"./umd":74}],74:[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},i=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)},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=l(e("./_default")),o=l(e("./amd")),u=l(e("lodash/object/values")),c=r(e("../../util")),p=r(e("../../types")),d=function(e){function t(){a(this,t),null!=e&&e.apply(this,arguments)}return i(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=u(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)),o=[p.literal("exports")];this.passModuleArg&&o.push(p.literal("module")),o=o.concat(n),o=[p.arrayExpression(o)];var d=c.template("test-exports"),f=c.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 v=this.defaultIds[y]||p.identifier(p.toIdentifier(y));g.push(p.memberExpression(p.identifier("global"),v))}var b=this.getModuleName();b&&o.unshift(p.literal(b));var x=this.file.opts.basename;b&&(x=b),x=p.identifier(p.toIdentifier(x));var E=c.template("umd-runner-body",{AMD_ARGUMENTS:o,COMMON_TEST:h,COMMON_ARGUMENTS:m,BROWSER_ARGUMENTS:g,GLOBAL_ARG:x});e.body=[p.expressionStatement(p.callExpression(E,[p.thisExpression(),a]))]},t}(o);t.exports=d},{"../../types":153,"../../util":157,"./_default":64,"./amd":67,"lodash/object/values":411}],75:[function(e,t,n){"use strict";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/includes")),a=r(e("../traversal")),s=function(){function e(t,n){l(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&&i(r,n))return!1;var l=t.whitelist;if(l)return i(l,n);var a=e.metadata.stage;return null!=a&&a>=t.stage?!0:e.metadata.optional&&!i(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),a(e.ast,this.handlers,e.scope,e),this.ran=!0}},e}();t.exports=s},{"../traversal":144,"lodash/collection/includes":319}],76:[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},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("./transformer-pass")),s=l(e("lodash/lang/isFunction")),o=l(e("../traversal")),u=l(e("lodash/lang/isObject")),c=l(e("lodash/object/assign")),p=(r(e("../../acorn")),l(e("./file"))),d=l(e("lodash/collection/each")),f=function(){function e(t,n,r){i(this,e),n=c({},n);var l=function(e){var t=n[e];return delete n[e],t};this.manipulateOptions=l("manipulateOptions"),this.metadata=l("metadata")||{},this.parser=l("parser"),this.check=l("check"),this.post=l("post"),this.pre=l("pre"),null!=this.metadata.stage&&(this.metadata.optional=!0),this.handlers=this.normalize(n);var a=this;a.opts||(a.opts={}),this.key=t}return e.prototype.normalize=function(e){var t=this;return s(e)&&(e={ast:e}),o.explode(e),d(e,function(n,r){return"_"===r[0]?void(t[r]=n):void("enter"!==r&&"exit"!==r&&(s(n)&&(n={enter:n}),u(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 a(e,this)},e}();t.exports=f},{"../../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,n){t.exports={useStrict:"strict","es5.runtime":"runtime","es6.runtime":"runtime"}},{}],78:[function(e,t,n){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 s.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,a.push(t,e.key,e.kind,e.computed,e.value),!1):!0}),n?s.callExpression(s.memberExpression(s.identifier("Object"),s.identifier("defineProperties")),[e,a.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 a=i(e("../../helpers/define-map")),s=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")),a=i.isArrowFunctionExpression;n.check=a},{"../../../types":153}],83:[function(e,t,n){"use strict";function r(e,t){if(!b.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=b.identifier("undefined"))}return e._let=!0,e.kind="var",!0}function l(e,t){return!b.isFor(t)||!b.isFor(t,{left:e})}function i(e,t){return b.isVariableDeclaration(e,{kind:"var"})&&!r(e,t)}function a(e){for(var t=0;t<e.length;t++)delete e[t]._let}function s(e){return b.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 a=[e],s=0;s<e.declarations.length;s++){var o=e.declarations[s];if(o.init){var u=b.assignmentExpression("=",o.id,o.init);u._ignoreBlockScopingTDZ=!0,a.push(b.expressionStatement(u))}o.init=i.addHelper("temporal-undefined")}return e._blockHoist=2,a}}function u(e,t,n,l){var i=e.left||e.init;r(i,e)&&(b.ensureBlock(e),e.body._letDeclarators=[i]);var a=new M(this,this.get("body"),t,n,l);return a.run()}function c(e,t,n,r){if(!b.isLoop(t)){var l=new M(null,this,t,n,r);l.run()}}function p(e,t,n,r){if(b.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){p(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=s,n.VariableDeclaration=o,n.Loop=u,n.BlockStatement=c,n.__esModule=!0;var g=h(e("../../../traversal")),y=h(e("../../../helpers/object")),v=f(e("../../../util")),b=f(e("../../../types")),x=h(e("lodash/object/values")),E=h(e("lodash/object/extend"));n.Program=c;var _={enter:p},w={enter:function(e,t,n,r){return this.isFunction()?(this.traverse(S,r),this.skip()):void 0}},S={enter:function(e,t,n,r){if(this.isReferencedIdentifier()){var l=r.letReferences[e.name];l&&n.getBindingIdentifier(e.name)===l&&(r.closurify=!0)}}},I={enter:function(e,t,n,r){if(this.isForStatement())i(e.init,e)&&(e.init=b.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(b.expressionStatement);if(this.isFunction())return this.skip()}}},k={enter:function(e,t,n,r){this.isLabeledStatement()&&r.innerLabels.push(e.label.name)}},T={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 b.isBreakStatement(e)?"break":b.isContinueStatement(e)?"continue":void 0},j={enter:function(e,t,n,r){var l;if(this.isLoop()&&(r.ignoreLabeless=!0,this.traverse(j,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(b.isBreakStatement(e)&&b.isSwitchCase(t))return}r.hasBreakContinue=!0,r.map[i]=e,l=b.literal(i)}return this.isReturnStatement()&&(r.hasReturn=!0,l=b.objectExpression([b.property("init",b.identifier("v"),e.argument||b.identifier("undefined"))])),l?(l=b.returnStatement(l),b.inherits(l,e)):void 0}},M=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=b.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(!b.isFunction(this.parent)&&!b.isProgram(this.block)&&this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.loopLabel&&!b.isLabeledStatement(this.loopParent)?b.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 a=n.generateUidIdentifier(i.name).name;i.name=a,e=!0,r[l]=r[a]={binding:i, uid:a}}}if(e){var s=this.loop;s&&(d(s.right,s,n,r),d(s.test,s,n,r),d(s.update,s,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),a=b.functionExpression(null,l,b.blockStatement(e.body));a.shadow=!0,this.addContinuations(a),e.body=this.body;var s=a;this.loop&&(s=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(b.variableDeclaration("var",[b.variableDeclarator(s,a)])));var o=b.callExpression(s,i),u=this.scope.generateUidIdentifier("ret"),c=g.hasType(a.body,this.scope,"YieldExpression",b.FUNCTION_TYPES);c&&(a.generator=!0,o=b.yieldExpression(o,!0));var p=g.hasType(a.body,this.scope,"AwaitExpression",b.FUNCTION_TYPES);p&&(a.async=!0,o=b.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(b.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,T,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(b.expressionStatement(b.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,b.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=b.getBindingIdentifiers(e);E(this.letReferences,i),this.hasLetReferences=!0}if(this.hasLetReferences){a(n);var s={letReferences:this.letReferences,closurify:!1};return this.blockPath.traverse(w,s),s.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(j,e),e},e.prototype.hoistVarDeclarations=function(){this.blockPath.traverse(I,this)},e.prototype.pushDeclar=function(e){this.body.push(b.variableDeclaration(e.kind,e.declarations.map(function(e){return b.variableDeclarator(e.id)})));for(var t=[],n=0;n<e.declarations.length;n++){var r=e.declarations[n];if(r.init){var l=b.assignmentExpression("=",r.id,r.init);t.push(b.inherits(l,r))}}return t},e.prototype.buildHas=function(e,t){var n=this.body;n.push(b.variableDeclaration("var",[b.variableDeclarator(e,t)]));var r,l=(this.loop,this.has),i=[];if(l.hasReturn&&(r=v.template("let-scoping-return",{RETURN:e})),l.hasBreakContinue){for(var a in l.map)i.push(b.switchCase(b.literal(a),[l.map[a]]));if(l.hasReturn&&i.push(b.switchCase(null,[r])),1===i.length){var s=i[0];n.push(this.file.attachAuxiliaryComment(b.ifStatement(b.binaryExpression("===",e,s.test),s.consequent[0])))}else{for(var o=0;o<i.length;o++){var u=i[o].consequent[0];if(b.isBreakStatement(u)&&!u.label){var c;u.label=(c=this,!c.loopLabel&&(c.loopLabel=this.file.scope.generateUidIdentifier("loop")),c.loopLabel)}}n.push(this.file.attachAuxiliaryComment(b.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,t,n,r){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}},a=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")};n.ClassDeclaration=r,n.ClassExpression=l,n.__esModule=!0;var o=a(e("../../helpers/replace-supers")),u=i(e("../../helpers/name-method")),c=i(e("../../helpers/define-map")),p=i(e("../../../messages")),d=i(e("../../../util")),f=a(e("../../../traversal")),h=(a(e("lodash/collection/each")),a(e("lodash/object/has"))),m=i(e("../../../types")),g="__initializeProperties",y=m.isClass;n.check=y;var v={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)}}},b=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){s(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 a=[],s=[];this.hasSuper&&(s.push(t),t=this.scope.generateUidBasedOnNode(t),a.push(t),this.superName=t,l.push(m.expressionStatement(m.callExpression(r.addHelper("inherits"),[n,t])))),this.buildBody();var o=this.node.decorators,c=n;if(o&&(c=this.scope.generateUidIdentifier(n)),i.body.unshift(m.expressionStatement(m.callExpression(r.addHelper("class-call-check"),[m.thisExpression(),c]))),o){this.className&&l.push(m.variableDeclaration("var",[m.variableDeclarator(c,n)]));for(var p=0;p<o.length;p++){var f=o[p],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,a,m.blockStatement(l)),s)},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 a=i;if(a._inherits||(a._inherits=[]),i._inherits.push(e),i._key=e.key,t&&(i.enumerable=m.literal(!0)),e.computed&&(i._computed=!0),e.decorators){var s;this.hasDecorators=!0;var o=(s=i,!s.decorators&&(s.decorators=m.arrayExpression([])),s.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 a=n[i],s=l[i];if(m.isMethodDefinition(a)){var u="constructor"===a.kind;u&&this.verifyConstructor(s);var p=new o({methodPath:s,methodNode:a,objectRef:this.classRef,superRef:this.superName,isStatic:a["static"],isLoose:this.isLoose,scope:this.scope,file:this.file},!0);p.replace(),u?this.pushConstructor(a,s):this.pushMethod(a)}else m.isClassProperty(a)&&this.pushProperty(a)}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=c.toClassObject(this.instanceMutatorMap)),this.hasStaticDescriptors&&(g=c.toClassObject(this.staticMutatorMap)),h||g){h&&(h=c.toComputedObjectFromClass(h)),g&&(g=c.toComputedObjectFromClass(g));var v=m.literal(null),b=[this.classRef,v,v,v,v];h&&(b[1]=h),g&&(b[2]=g),this.instanceInitializersId&&(b[3]=this.instanceInitializersId,r.unshift(this.buildObjectAssignment(this.instanceInitializersId))),this.staticInitializersId&&(b[4]=this.staticInitializersId,r.unshift(this.buildObjectAssignment(this.staticInitializersId)));for(var x=0,i=0;i<b.length;i++)b[i]!==v&&(x=i);b=b.slice(0,x+1),r.push(m.expressionStatement(m.callExpression(this.file.addHelper(y),b)))}},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(b,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,p.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,v,{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 a=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.Scopable=l,n.VariableDeclaration=i,n.__esModule=!0;var s=a(e("../../../messages")),o=a(e("../../../types")),u={enter:function(e,t,n,r){if(this.isAssignmentExpression()||this.isUpdateExpression()){var l=this.getBindingIdentifiers();for(var i in l){var a=l[i],o=r.constants[i];if(o){var u=o.identifier;if(a!==u&&n.bindingIdentifierEquals(i,u))throw r.file.errorWithNode(a,s.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 a=l.declarations[0].id;if(f.isPattern(a)){var s=n.generateUidIdentifier("ref");e.left=f.variableDeclaration(l.kind,[f.variableDeclarator(s,null)]);var o=[],u=new g({kind:l.kind,file:r,scope:n,nodes:o});u.init(a,s),f.ensureBlock(e);var c=e.body;c.body=o.concat(c.body)}}}function l(e,t,n,r){var l=e.param;if(f.isPattern(l)){var i=n.generateUidIdentifier("ref");e.param=i;var a=[],s=new g({kind:"let",file:r,scope:n,nodes:a});return s.init(l,i),e.body.body=a.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 a(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 a=new g({operator:e.operator,file:r,scope:n,nodes:i});return a.init(e.left,l),i.push(f.expressionStatement(l)),i}}function s(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)&&s(e)){for(var l,i=[],a=0;a<e.declarations.length;a++){l=e.declarations[a];var o=l.init,u=l.id,c=new g({nodes:i,scope:n,kind:e.kind,file:r});f.isPattern(u)&&o?(c.init(u,o),+a!==e.declarations.length-1&&f.inherits(i[i.length-1],l)):i.push(f.inherits(c.buildVariableAssignment(l.id,l.init),l))}if(!f.isProgram(t)&&!f.isBlockStatement(t)){for(l=null,a=0;a<i.length;a++){if(e=i[a],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 c=function(e){return e&&e.__esModule?e:{"default":e}},p=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=a,n.VariableDeclaration=o,n.__esModule=!0;var d=c(e("../../../messages")),f=c(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,a){if(!f.isPattern(t))return t;i=!0;var s=n.generateUidIdentifier("ref"),o=new g({blockHoist:e.params.length-a,nodes:l,scope:n,file:r,kind:"let"});return o.init(t,s),s}),i){r.checkNode(l),f.ensureBlock(e);var a=e.body;a.body=l.concat(a.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){p(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 a=e.properties[i];if(i>=r)break;if(!f.isSpreadProperty(a)){var s=a.key;f.isIdentifier(s)&&!a.computed&&(s=f.literal(a.key.name)),l.push(s)}}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 a;f.isRestElement(i)?(a=this.toArray(t),l>0&&(a=f.callExpression(f.memberExpression(a,f.identifier("slice")),[f.literal(l)])),i=i.argument):a=f.memberExpression(t,f.literal(l),!0),this.push(i,a)}}}},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=p;r.isLoose("es6.forOf")&&(i=c);var a=i(e,t,n,r),s=a.declar,u=a.loop,d=u.body;o.ensureBlock(e),s&&d.body.push(s),d.body=d.body.concat(e.body.body),o.inherits(u,e),o.inherits(u.body,e.body),a.replaceParent?(this.parentPath.replaceWithMultiple(a.node),this.remove()):this.replaceWithMultiple(a.node)}function l(e,t,n){var r=[],l=e.right;if(!o.isIdentifier(l)||!t.hasBinding(l.name)){var i=t.generateUidIdentifier("arr");r.push(o.variableDeclaration("var",[o.variableDeclarator(i,l)])),l=i}var a=t.generateUidIdentifier("i"),u=s.template("for-of-array",{BODY:e.body,KEY:a,ARR:l});o.inherits(u,e),o.ensureBlock(u);var c=o.memberExpression(l,a,!0),p=e.left;return o.isVariableDeclaration(p)?(p.declarations[0].init=c,u.body.body.unshift(p)):u.body.body.unshift(o.expressionStatement(o.assignmentExpression("=",p,c))),r.push(u),r}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.ForOfStatement=r,n._ForOfStatementArray=l,n.__esModule=!0;var a=i(e("../../../messages")),s=i(e("../../../util")),o=i(e("../../../types")),u=o.isForOfStatement;n.check=u;var c=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,a.get("unknownForHead",u.type));i=n.generateUidIdentifier("ref"),l=o.variableDeclaration(u.kind,[o.variableDeclarator(u.declarations[0].id,i)])}var c=n.generateUidIdentifier("iterator"),p=n.generateUidIdentifier("isArray"),d=s.template("for-of-loose",{LOOP_OBJECT:c,IS_ARRAY:p,OBJECT:e.right,INDEX:n.generateUidIdentifier("i"),ID:i});return l||d.body.body.shift(),{declar:l,node:d,loop:d}},p=function(e,t,n,r){var l,i=e.left,u=n.generateUidIdentifier("step"),c=o.memberExpression(u,o.identifier("value"));if(o.isIdentifier(i)||o.isPattern(i)||o.isMemberExpression(i))l=o.expressionStatement(o.assignmentExpression("=",i,c));else{if(!o.isVariableDeclaration(i))throw r.errorWithNode(i,a.get("unknownForHead",i.type));l=o.variableDeclaration(i.kind,[o.variableDeclarator(i.declarations[0].id,c)])}var p=n.generateUidIdentifier("iterator"),d=s.template("for-of",{ITERATOR_HAD_ERROR_KEY:n.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:n.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:n.generateUidIdentifier("iteratorError"),ITERATOR_KEY:p,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 a(e,t,n,l){var i=[];return l.moduleFormatter.exportDeclaration(e,i,t),r(e,i),i}function s(e,t,n,l){if(!this.get("declaration").isTypeAlias()){var i=[];if(e.declaration){if(u.isVariableDeclaration(e.declaration)){var a=e.declaration.declarations[0];a.init=a.init||u.identifier("undefined")}l.moduleFormatter.exportDeclaration(e,i,t)}else if(e.specifiers)for(var s=0;s<e.specifiers.length;s++)l.moduleFormatter.exportSpecifier(e.specifiers[s],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=a,n.ExportNamedDeclaration=s,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,a=n.generateUidIdentifier("this"),u=new s({topLevelThisReference:a,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(a,o.thisExpression())]))}}function l(e,t,n,l){for(var i,a=function(){return!i&&(i=n.generateUidIdentifier("obj")),i},s=this.get("properties"),u=0;u<e.properties.length;u++)r(s[u],e.properties[u],n,a,l);return i?(n.push({id:i}),o.assignmentExpression("=",i,e)):void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e};n.ObjectExpression=l,n.__esModule=!0;var s=a(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 a=i(e("../../helpers/call-delegate")),s=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},c={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 p=0,d={iife:!1,scope:n},f=function(t,n,a){var u=s.template("default-parameter",{VARIABLE_NAME:t,DEFAULT_VALUE:n,ARGUMENT_KEY:o.literal(a),ARGUMENTS:i},!0);r.checkNode(u),u._blockHoist=e.params.length-a,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"),v=g.get("right"),b=n.generateUidIdentifier("x");b._isDefaultPlaceholder=!0,e.params[m]=b,d.iife||(v.isIdentifier()&&n.hasOwnBinding(v.node.name)?d.iife=!0:v.traverse(c,d)),f(y.node,v.node,m)}else g.isRestElement()||(p=m+1),g.isIdentifier()||g.traverse(c,d),r.transformers["es6.spec.blockScoping"].canTransform()&&g.isIdentifier()&&f(g.node,o.identifier("undefined"),m)}e.params=e.params.slice(0,p),d.iife?(l.push(a(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 a=i(e("lodash/lang/isNumber")),s=l(e("../../../util")),o=l(e("../../../types")),u=o.isRestElement;n.check=u;var c={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(c,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(a(l.value)||o.isUnaryExpression(l)||o.isBinaryExpression(l))return void r.candidates.push(this)}r.canOptimise=!1,this.stop()}}},p=function(e){return o.isRestElement(e.params[e.params.length-1])};n.Function=function(e,t,n,l){if(p(e)){var i=e.params.pop().argument,a=o.identifier("arguments");if(a._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(c,f),f.canOptimise&&f.candidates.length)for(var h=0;h<f.candidates.length;h++){var m=f.candidates[h];m.replaceWith(a),r(m.parent,e.params.length)}else{var g=o.literal(e.params.length),y=n.generateUidIdentifier("key"),v=n.generateUidIdentifier("len"),b=y,x=v;e.params.length&&(b=o.binaryExpression("-",y,g),x=o.conditionalExpression(o.binaryExpression(">",v,g),o.binaryExpression("-",v,g),o.literal(0)));var E=s.template("rest",{ARGUMENTS:a,ARRAY_KEY:b,ARRAY_LEN:x,START:g,ARRAY:i,KEY:y,LEN:v});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,a,s=e.properties,u=0;u<s.length;u++)i=s[u],"init"===i.kind&&(a=i.key,!i.computed&&o.isIdentifier(a)&&(i.key=o.literal(a.name)));var c=!1;for(u=0;u<s.length;u++)i=s[u],i.computed&&(c=!0),("init"!==i.kind||!c||o.isLiteral(o.toComputedKey(i,i.key),{value:"__proto__"}))&&(r.push(i),s[u]=null);for(u=0;u<s.length;u++)if(i=s[u]){a=i.key;var p;p=i.computed&&o.isMemberExpression(a)&&o.isIdentifier(a.object,{name:"Symbol"})?o.assignmentExpression("=",o.memberExpression(n,a,!0),i.value):o.callExpression(l.addHelper("define-property"),[n,a,i.value]),t.push(o.expressionStatement(p))}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 a(e,t,n,i){for(var a=!1,s=0;s<e.properties.length&&!(a=o.isProperty(e.properties[s],{computed:!0,kind:"init"}));s++);if(a){var u=[],c=n.generateUidBasedOnNode(t),p=[],d=l;i.isLoose("es6.properties.computed")&&(d=r);var f=d(e,p,c,u,i);return f?f:(p.unshift(o.variableDeclaration("var",[o.variableDeclarator(c,o.objectExpression(u))])),p.push(o.expressionStatement(c)),p)}}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.check=i,n.ObjectExpression=a,n.__esModule=!0;var o=s(e("../../../types"))},{"../../../types":153}],93:[function(e,t,n){"use strict";function r(e){return a.isProperty(e)&&(e.method||e.shorthand)}function l(e){e.method&&(e.method=!1),e.shorthand&&(e.shorthand=!1,e.key=a.removeComments(a.clone(e.key)))}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.Property=l,n.__esModule=!0;var a=i(e("../../../types"))},{"../../../types":153}],94:[function(e,t,n){"use strict";function r(e){return a.is(e,"y")}function l(e){return a.is(e,"y")?s.newExpression(s.identifier("RegExp"),[s.literal(e.regex.pattern),s.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 a=i(e("../../helpers/regex")),s=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=s(e.regex.pattern,e.regex.flags),o.pullFlag(e,"u"))}var i=function(e){return e&&e.__esModule?e:{"default":e}},a=function(e){return e&&e.__esModule?e["default"]:e};n.check=r,n.Literal=l,n.__esModule=!0;var s=a(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(a,{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")),a={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 a=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([a,t]))):i.logicalExpression("&&",a,e)}}}},s={optional:!0};n.metadata=s,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 a=i.literal("undefined");return i.conditionalExpression(i.binaryExpression("===",i.unaryExpression("typeof",e.argument),a),a,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")),a={optional:!0};n.metadata=a},{"../../../types":153}],98:[function(e,t,n){"use strict";function r(e,t,n,r){if(!i.isTaggedTemplateExpression(t))for(var l=0;l<e.expressions.length;l++)e.expressions[l]=i.callExpression(i.identifier("String"),[e.expressions[l]])}var l=function(e){return e&&e.__esModule?e:{"default":e}};n.TemplateLiteral=r,n.__esModule=!0;var i=l(e("../../../types")),a={optional:!0};n.metadata=a},{"../../../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(p.isSpreadElement(e[t]))return!0;return!1}function i(e,t){for(var n=[],l=[],i=function(){l.length&&(n.push(p.arrayExpression(l)),l=[])},a=0;a<e.length;a++){var s=e[a];p.isSpreadElement(s)?(i(),n.push(r(s,t))):l.push(s)}return i(),n}function a(e,t,n){var r=e.elements;if(l(r)){var a=i(r,n),s=a.shift();return p.isArrayExpression(s)||(a.unshift(s),s=p.arrayExpression([])),p.callExpression(p.memberExpression(s,p.identifier("concat")),a)}}function s(e,t,n){var r=e.arguments;if(l(r)){var a=p.identifier("undefined");e.arguments=[];var s;s=1===r.length&&"arguments"===r[0].argument.name?[r[0].argument]:i(r,n);var o=s.shift();e.arguments.push(s.length?p.callExpression(p.memberExpression(o,p.identifier("concat")),s):o);var u=e.callee;if(this.get("callee").isMemberExpression()){var c=n.generateMemoisedReference(u.object);c?(u.object=p.assignmentExpression("=",c,u.object),a=c):a=u.object,p.appendToMemberExpression(u,p.identifier("apply"))}else e.callee=p.memberExpression(e.callee,p.identifier("apply"));e.arguments.unshift(a)}}function o(e,t,n,r){var a=e.arguments;if(l(a)){var s=i(a,n),o=p.arrayExpression([p.literal(null)]);return a=p.callExpression(p.memberExpression(o,p.identifier("concat")),s),p.newExpression(p.callExpression(p.memberExpression(r.addHelper("bind"),p.identifier("apply")),[e.callee,a]),[])}}var u=function(e){return e&&e.__esModule?e:{"default":e}},c=function(e){return e&&e.__esModule?e["default"]:e};n.ArrayExpression=a,n.CallExpression=s,n.NewExpression=o,n.__esModule=!0;var p=(c(e("lodash/collection/includes")),u(e("../../../types"))),d=p.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},a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=i(e("lodash/collection/reduceRight")),o=l(e("../../../messages")),u=i(e("lodash/array/flatten")),c=l(e("../../../util")),p=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 p(l.right.elements,function(e){return d.expressionStatement(e)})}else this.remove()}}},g=function(){function e(t,n,r){a(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(p(this.vars,function(e){return e.declarations},this)),l=s(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 a=this.paramDecls;a.length>0&&n.unshift(d.variableDeclaration("var",a)),n.unshift(d.expressionStatement(d.assignmentExpression("=",this.getAgainId(),d.literal(!1)))),e.body=c.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 v=this.leftId;v&&g.push(d.variableDeclarator(v)),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(),a=this.getParams();l.push(d.expressionStatement(d.assignmentExpression("=",i,n)));var s,o;if(d.isArrayExpression(n)){var u=n.elements;for(s=0;s<u.length&&s<a.length;s++){o=a[s];var c=u[s]||(u[s]=d.identifier("undefined"));o._isDefaultPlaceholder||(u[s]=d.assignmentExpression("=",o,c))}}else for(this.setsArguments=!0,s=0;s<a.length;s++)o=a[s],o._isDefaultPlaceholder||l.push(d.expressionStatement(d.assignmentExpression("=",o,d.memberExpression(i,d.literal(s),!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 s.isTemplateLiteral(e)||s.isTaggedTemplateExpression(e)}function l(e,t,n,r){for(var l=e.quasi,i=[],a=[],o=[],u=0;u<l.quasis.length;u++){var c=l.quasis[u];a.push(s.literal(c.value.cooked)),o.push(s.literal(c.value.raw))}a=s.arrayExpression(a),o=s.arrayExpression(o);var p="tagged-template-literal";return r.isLoose("es6.templateLiterals")&&(p+="-loose"),i.push(s.callExpression(r.addHelper(p),[a,o])),i=i.concat(l.expressions),s.callExpression(e.tag,i)}function i(e,t,n,r){var l,i=[];for(l=0;l<e.quasis.length;l++){var a=e.quasis[l];i.push(s.literal(a.value.cooked));var u=e.expressions.shift();u&&i.push(u)}if(i.length>1){var c=i[i.length-1];s.isLiteral(c,{value:""})&&i.pop();var p=o(i.shift(),i.shift());for(l=0;l<i.length;l++)p=o(p,i[l]);return p}return i[0]}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.TaggedTemplateExpression=l,n.TemplateLiteral=i,n.__esModule=!0;var s=a(e("../../../types")),o=function(e,t){return s.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 a=i;return e.generator&&(a=l),a(e,t,n,r)}function l(e){var t=[],n=p.functionExpression(null,[],p.blockStatement(t),!0);return n.shadow=!0,t.push(o(e,function(){return p.expressionStatement(p.yieldExpression(e.body))})),p.callExpression(n,[])}function i(e,t,n,r){var l=n.generateUidBasedOnNode(t),i=c.template("array-comprehension-container",{KEY:l});i.callee.shadow=!0;var a=i.callee.body,s=a.body;u.hasType(e,n,"YieldExpression",p.FUNCTION_TYPES)&&(i.callee.generator=!0,i=p.yieldExpression(i,!0));var d=s.pop();return s.push(o(e,function(){return c.template("array-push",{STATEMENT:e.body,KEY:l},!0)})),s.push(d),i}var a=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};n.ComprehensionExpression=r,n.__esModule=!0;var o=s(e("../../helpers/build-comprehension")),u=s(e("../../../traversal")),c=a(e("../../../util")),p=a(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")),a={optional:!0,stage:0};n.metadata=a;var s=i.isDoExpression;n.check=s},{"../../../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")),a=r(e("../../../types")),s={stage:2};n.metadata=s;var o=a.memberExpression(a.identifier("Math"),a.identifier("pow"));i(n,{operator:"**",build:function(e,t){return a.callExpression(o,[e,t])}})},{"../../../types":153,"../../helpers/build-binary-assignment-operator-transformer":50}],108:[function(e,t,n){"use strict";function r(e){return s.isExportDefaultSpecifier(e)||s.isExportNamespaceSpecifier(e)}function l(e,t,n){var r=e.specifiers[0];if(s.isExportNamespaceSpecifier(r)||s.isExportDefaultSpecifier(r)){var i,a=e.specifiers.shift(),o=n.generateUidIdentifier(a.exported.name);i=s.isExportNamespaceSpecifier(a)?s.importNamespaceSpecifier(o):s.importDefaultSpecifier(o),t.push(s.importDeclaration([i],e.source)),t.push(s.exportNamedDeclaration(null,[s.exportSpecifier(o,a.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 a=function(e){return e&&e.__esModule?e:{"default":e}};n.check=r,n.ExportNamedDeclaration=i,n.__esModule=!0;var s=a(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=[],s=function(){i.length&&(l.push(a.objectExpression(i)),i=[])},u=0;u<e.properties.length;u++){var c=e.properties[u];a.isSpreadProperty(c)?(s(),l.push(c.argument)):i.push(c)}return s(),a.isObjectExpression(l[0])||l.unshift(a.objectExpression([])),a.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 a=i(e("../../../types")),s={stage:1};n.metadata=s;var o=function(e){for(var t=0;t<e.properties.length;t++)if(a.isSpreadProperty(e.properties[t]))return!0;return!1}},{"../../../types":153}],110:[function(e,t,n){"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")),a=r(e("lodash/object/values")),s={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 s=l(e.body,function(e){var t=e&&e._blockHoist;return null==t&&(t=1),t===!0&&(t=2),t});e.body=i(a(s).reverse())}}};n.BlockStatement=s,n.Program=s},{"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 s=a.variableDeclarator(i.id,i.init);if(i.init)e.body.unshift(r.attachAuxiliaryComment(a.variableDeclaration(t,[s])));else{var o=n,u=t;o[u]||(o[u]=[]),n[t].push(s)}}for(t in n)e.body.unshift(r.attachAuxiliaryComment(a.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")),a=l(e("../../../types")),s={secondPass:!0};n.metadata=s,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 a=n.generateUidIdentifier("default");return r=u.variableDeclaration("var",[u.variableDeclarator(a,r)]),e.declaration=a,[i(),e]}return u.isFunctionDeclaration(r)?(e._blockHoist=2,e.declaration=r.id,[i(),e]):void 0}function a(e,t,n){l.apply(this,arguments);var r=e.declaration,i=function(){return r._ignoreUserWhitespace=!0,r};if(u.isClassDeclaration(r))return e.specifiers=[u.exportSpecifier(r.id,r.id)],e.declaration=null,[i(),e];if(u.isFunctionDeclaration(r))return e.specifiers=[u.exportSpecifier(r.id,r.id)],e.declaration=null,e._blockHoist=2,[i(),e];if(u.isVariableDeclaration(r)){var a=[],s=this.get("declaration").getBindingIdentifiers();for(var o in s){var c=s[o];a.push(u.exportSpecifier(c,c))}return[r,u.exportNamedDeclaration(null,a)]}}function s(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=a,n.Program=s,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 a,o=function(t,n){a||(a=e()),a.unshift(s.variableDeclaration("var",[s.variableDeclarator(t,n)]))};r&&o(r,s.identifier("arguments")),l&&o(l,s.thisExpression())}function l(e,t,n){r(function(){return e.body},this,n)}function i(e,t,n){r(function(){return s.ensureBlock(e),e.body.body},this,n)}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=l,n.FunctionDeclaration=i,n.__esModule=!0;var s=a(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 a=e.body[0];a&&(l.leadingComments=a.leadingComments,a.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 a(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 s=function(e){return e&&e.__esModule?e:{"default":e}};n.ForOfStatement=r,n.MethodDefinition=l,n.Property=i,n.BlockStatement=a,n.__esModule=!0;var o=s(e("../../../messages")),u=s(e("../../../types")),c={readOnly:!0};n.metadata=c,n.ForInStatement=r,n.Program=a},{"../../../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,a=l(e("../../../types")),s=a.isForOfStatement;n.check=s;var o=!0;n.optional=o},{"../../../types":153,"../es6/for-of":87}],120:[function(e,t,n){"use strict";function r(e,t,n,r){if(!e._ignoreConstant){var l={isImmutable:!0};this.traverse(a,l),this.skip(),l.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 a={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 a(e,t){u(f.properties,o.identifier(e),t)}function u(e,t,n){e.push(o.property("init",t,n))}var c=e.openingElement;if(!r(c.attributes)){var p=!0,d=o.objectExpression([]),f=o.objectExpression([]),h=o.literal(null),m=c.name;o.isJSXIdentifier(m)&&s.isCompatTag(m.name)&&(m=o.literal(m.name),p=!1),a("type",m),a("ref",o.literal(null)),e.children.length&&u(d.properties,o.identifier("children"),o.arrayExpression(s.buildChildren(e)));for(var g=0;g<c.attributes.length;g++){var y=c.attributes[g];l(y,"key")?h=y.value:u(d.properties,y.name,y.value)}return p&&(d=o.callExpression(i.addHelper("default-props"),[o.memberExpression(m,o.identifier("defaultProps")),d])),a("props",d),a("key",h),f}}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.JSXElement=i,n.__esModule=!0;var s=a(e("../../helpers/react")),o=a(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 a=i(e("../../helpers/remap-async-to-generator")),s=l(e("../../../types")),o={optional:!0};n.metadata=o,n.Function=function(e,t,n,r){return e.async&&!e.generator?a(e,s.memberExpression(r.addImport("bluebird",null,!0),s.identifier("coroutine")),n):void 0}},{"../../../types":153,"../../helpers/remap-async-to-generator":60}],124:[function(e,t,n){"use strict";function r(e){this.remove()}function l(e){e.typeAnnotation=null,e.value||this.remove()}function i(e){e["implements"]=null}function a(e){return e.expression}function s(e){e.isType&&this.remove()}function o(e){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=a,n.ImportDeclaration=s,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;s.isLiteral(t)&&"number"==typeof t.value&&(t.value=""+t.value)}function i(e){e.regex&&(e.regex.pattern="foobar",e.regex.flags="")}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.BinaryExpression=r,n.Property=l,n.Literal=i,n.__esModule=!0;var s=a(e("../../../types")),o=a(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")),a=l(e("../../../types")),s={optional:!0};n.metadata=s,e("../../helpers/build-react-transformer")(n,{pre:function(e){e.callee=e.tagExpr},post:function(e){i.isCompatTag(e.tagName)&&(e.call=a.callExpression(a.memberExpression(a.memberExpression(a.identifier("React"),a.identifier("DOM")),e.tagExpr,a.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=s.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(a.identifier).reduce(function(e,t){return a.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")),a=l(e("../../../types")),s=/^\*\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)?a.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 s.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 a=i(e("regenerator-babel")),s=l(e("../../../types")),o={enter:function(e){a.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(a,e.name)}var l=function(e){return e&&e.__esModule?e:{"default":e}},i=function(e){return e&&e.__esModule?e["default"]:e},a=i(e("core-js/library")),s=i(e("lodash/collection/includes")),o=l(e("../../../util")),u=i(e("lodash/object/has")),c=l(e("../../../types")),p=c.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,!c.isReferenced(f,e))return;if(!e.computed&&r(f)&&u(a[f.name],i.name)&&!n.getBindingIdentifier(f.name))return this.skip(),c.prependToMemberExpression(e,l.get("coreIdentifier"))}else{if(this.isReferencedIdentifier()&&!c.isMemberExpression(t)&&s(d,e.name)&&!n.getBindingIdentifier(e.name))return c.memberExpression(l.get("coreIdentifier"),e);if(this.isCallExpression()){var h=e.callee;return e.arguments.length?!1:c.isMemberExpression(h)&&h.computed?(i=h.property,p(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(!p(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 a(e,t,n,r){if(u.isIdentifier(e.callee,{name:"eval"}))throw r.errorWithNode(e,o.get("evalInStrictMode"))}var s=function(e){return e&&e.__esModule?e:{"default":e}};n.Program=r,n.FunctionExpression=l,n.ThisExpression=i,n.CallExpression=a,n.__esModule=!0;var o=s(e("../../../messages")),u=s(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(s.isFunctionDeclaration(l)){var i=s.variableDeclaration("let",[s.variableDeclarator(l.id,s.toExpression(l))]);i._blockHoist=2,l.id=null,t[e][r]=i,n.checkNode(i)}}}function l(e,t,n,l){s.isFunction(t)&&t.body===e||s.isExportDeclaration(t)||r("body",e,l)}function i(e,t,n,l){r("consequent",e,l)}var a=function(e){return e&&e.__esModule?e:{"default":e}};n.BlockStatement=l,n.SwitchCase=i,n.__esModule=!0;var s=a(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 p.isLiteral(p.toComputedKey(e,e.key),{value:"__proto__"})}function l(e){var t=e.left;return p.isMemberExpression(t)&&p.isLiteral(p.toComputedKey(t,t.property),{value:"__proto__"})}function i(e,t,n){return p.expressionStatement(p.callExpression(n.addHelper("defaults"),[t,e.right]))}function a(e,t,n,r){if(l(e)){var a=[],s=e.left.object,o=n.generateMemoisedReference(s);return a.push(p.expressionStatement(p.assignmentExpression("=",o,s))),a.push(i(e,o,r)),o&&a.push(o),a}}function s(e,t,n,r){var a=e.expression;if(p.isAssignmentExpression(a,{operator:"="}))return l(a)?i(a,a.left.object,r):void 0}function o(e,t,n,l){for(var i,a=0;a<e.properties.length;a++){var s=e.properties[a];r(s)&&(i=s.value,d(e.properties,s))}if(i){var o=[p.objectExpression([]),i];return e.properties.length&&o.push(e),p.callExpression(l.addHelper("extends"),o)}}var u=function(e){return e&&e.__esModule?e["default"]:e},c=function(e){return e&&e.__esModule?e:{"default":e}};n.AssignmentExpression=a,n.ExpressionStatement=s,n.ObjectExpression=o,n.__esModule=!0;var p=c(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,t){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")),a={optional:!0,react:!0};n.metadata=a},{"../../../types":153}],135:[function(e,t,n){"use strict";function r(e){if(a.isBlockStatement(e)){for(var t=!1,n=0;n<e.body.length;n++){var r=e.body[n];a.isBlockScoped(r)&&(t=!0)}if(!t)return e.body}return e}function l(e,t,n){var r=this.get("test").evaluateTruthy();return r===!0?e.consequent:r===!1?e.alternate:void 0}var i=function(e){return e&&e.__esModule?e:{"default":e}};n.ConditionalExpression=l,n.__esModule=!0;var a=i(e("../../../types")),s={optional:!0};n.metadata=s;var o={exit:function(e,t,n){var l=e.consequent,i=e.alternate,s=this.get("test").evaluateTruthy();return s===!0?r(l):s===!1?i?r(i):this.remove():(a.isBlockStatement(i)&&!i.body.length&&(i=e.alternate=null),void(a.isBlockStatement(l)&&!l.body.length&&a.isBlockStatement(i)&&i.body.length&&(e.consequent=e.alternate,e.alternate=null,e.test=a.unaryExpression("!",test,!0))))}};n.IfStatement=o},{"../../../types":153}],136:[function(e,t,n){(function(t){"use strict";function r(e){if(s(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")),a={optional:!0};n.metadata=a;var s=i.buildMatchMemberExpression("process.env")}).call(this,e("_process"))},{"../../../types":153,_process:183}],137:[function(e,t,n){"use strict";function r(e,t,n){var r=this.evaluate();return r.confident?a.valueToNode(r.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 a=i(e("../../../types")),s={optional:!0};n.metadata=s},{"../../../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")),a={optional:!0};n.metadata=a},{"../../../types":153}],139:[function(e,t,n){"use strict";function r(e){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,s.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 a=function(e){return e&&e.__esModule?e:{"default":e}};n.CallExpression=l,n.ModuleDeclaration=i,n.__esModule=!0;var s=a(e("../../../messages")),o=a(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 c=a(e.name,u);0>=c||c>3||o>=c||(l=u,o=c)}var p;throw p=l?s.get("undeclaredVariableSuggestion",e.name,l):s.get("undeclaredVariable",e.name),r.errorWithNode(e,p,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 a=i(e("leven")),s=l(e("../../../messages")),o={optional:!0};n.metadata=o},{"../../../messages":43,leven:307}],142:[function(e,t,n){"use strict";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("../types")),a=function(){function e(t){var n=t.identifier,r=t.scope,i=t.path,a=t.kind;l(this,e),this.identifier=n,this.constant=!0,this.scope=r,this.path=i,this.kind=a}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=i.typeParameterInstantiation(t)),this.assignType(i.genericTypeAnnotation(i.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(e){return!1},e}();t.exports=a},{"../types":153}],143:[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},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("./path")),s=(l(e("lodash/array/compact")),r(e("../types")),function(){function e(t,n,r,l){i(this,e),this.parentPath=l,this.scope=t,this.state=r,this.opts=n}return e.prototype.create=function(e,t,n){return a.get(this.parentPath,this,e,t,n)},e.prototype.visitMultiple=function(e,t,n){if(0===e.length)return!1;for(var r=[],l=this.queue=[],i=!1,a=0;a<e.length;a++)e[a]&&l.push(this.create(t,e,a));for(var a=0;a<l.length;a++){var s=l[a];if(!(r.indexOf(s.node)>=0)&&(r.push(s.node),s.visit())){i=!0;break}}for(var a=0;a<l.length;a++);return i},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,n){"use strict";function r(e,t,n,l,i){if(e){if(!t.noScope&&!n&&"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 a=0;a<e.length;a++)r.node(e[a],t,n,l,i);else r.node(e,t,n,l,i)}}function l(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 i(e,t,n,r){e.type===r.type&&(r.has=!0,this.skip())}var a=function(e){return e&&e.__esModule?e:{"default":e}},s=function(e){return e&&e.__esModule?e["default"]:e};t.exports=r;var o=s(e("./context")),u=s(e("lodash/collection/includes")),c=a(e("../types"));r.node=function(e,t,n,r,l){var i=c.VISITOR_KEYS[e.type];if(i)for(var a=new o(n,t,r,l),s=0;s<i.length;s++)if(a.visit(e,i[s]))return};var p=["trailingComments","leadingComments","extendedRange","_declarations","_scopeInfo","_paths","tokens","range","start","end","loc","raw"],d={noScope:!0,exit:l};r.removeProperties=function(e){return r(e,d),l(e),e},r.explode=function(e){for(var t in e){var n=e[t],r=c.FLIPPED_ALIAS_KEYS[t];if(r)for(var l=0;l<r.length;l++){var i=e,a=r[l];i[a]||(i[a]=n)}}return e},r.hasType=function(e,t,n,l){if(u(l,e.type))return!1;if(e.type===n)return!0;var a={has:!1,type:n};return r(e,{blacklist:l,enter:i},t,a),a.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 a=e(n.get("left")),s=e(n.get("right"));switch(r.operator){case"||":return a||s;case"&&":return a&&s}}if(n.isBinaryExpression()){var a=e(n.get("left")),s=e(n.get("right"));switch(r.operator){case"-":return a-s;case"+":return a+s;case"/":return a/s;case"*":return a*s;case"%":return a%s;case"<":return s>a;case">":return a>s;case"<=":return s>=a;case">=":return a>=s;case"==":return a==s;case"!=":return a!=s;case"===":return a===s;case"!==":return a!==s}}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,n){"use strict";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("../../transformation/helpers/react")),a=r(e("../../types")),s={enter:function(e,t,n,r){if((!this.isJSXIdentifier()||!i.isCompatTag(e.name))&&(this.isJSXIdentifier()||this.isIdentifier())&&this.isReferenced()){var l=n.getBinding(e.name);if(l!==r.scope.getBinding(e.name))return;l&&l.constant?r.bindings[e.name]=l:(n.dump(),r.foundIncompatible=!0,this.stop())}}},o=function(){function e(t,n){l(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([a.variableDeclaration("var",[a.variableDeclarator(t,this.path.node)])]),this.path.replaceWith(t)}}},e}();t.exports=o},{"../../transformation/helpers/react":58,"../../types":153}],148:[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},i=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}}(),a=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=l(e("./hoister")),o=l(e("lodash/lang/isBoolean")),u=l(e("lodash/lang/isNumber")),c=(l(e("lodash/lang/isRegExp")),l(e("lodash/lang/isString"))),p=l(e("../index")),d=l(e("lodash/collection/includes")),f=l(e("lodash/object/assign")),h=(l(e("lodash/object/extend")),l(e("../scope"))),m=r(e("../../types")),g={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=[],a=0;a<e.declarations.length;a++){var s=e.declarations[a];s.init&&i.push(m.expressionStatement(m.assignmentExpression("=",s.id,s.init)))}return i}}},y=function(){function e(t,n){a(this,e),this.container=n,this.parent=t,this.data={}}return e.get=function(t,n,r,l,i,a){for(var s,o,u=l[i],c=(s=l,!s._paths&&(s._paths=[]),s._paths),p=0;p<c.length;p++){var d=c[p];if(d.node===u){o=d;break}}return o||(o=new e(r,l),c.push(o)),o.setContext(t,n,i,a),o},e.getScope=function(e,t,n){var r=t;return e.isScope()&&(r=new h(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]=m.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];m.isExpressionStatement(t)&&m.isIdentifier(t.expression)&&e.pop()},e.prototype.isStatementOrBlock=function(){return m.isLabeledStatement(this.parent)||m.isBlockStatement(this.container)?!1:d(m.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]=m.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(m.expressionStatement(m.assignmentExpression("=",t,this.node))),e.push(m.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),m.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")&&m.isStatement(e))return this.replaceExpressionWithStatements([e]);var n=this.node;n&&m.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=m.toSequenceExpression(e,this.scope);if(t)return this.replaceWith(t);var n=m.functionExpression(null,[],m.blockStatement(e));n.shadow=!0;for(var r=this.getLastStatements(),l=0;l<r.length;l++){var i=r[l];i.isExpressionStatement()&&i.replaceWith(m.returnStatement(i.node.expression))}return this.replaceWith(m.callExpression(n,[])),this.traverse(g),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 a=this,s=0;s>r.length;s++){var o=r[s];a="."===o?a.parentPath:a.get(r[s])}return a},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&&(m.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(!m.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 a=l[i];if(a.isProperty()){var s=a.get("key"),o=a.isnt("computed")&&s.isIdentifier({name:n});if(o||(o=s.isLiteral({value:n})),o)return a.get("value")}}}},e.prototype.inferType=function(e){if(e=e.resolve()){if(e.isRestElement()||e.parentPath.isRestElement()||e.isArrayExpression())return m.genericTypeAnnotation(m.identifier("Array"));if(e.parentPath.isTypeCastExpression())return e.parentPath.node.typeAnnotation;if(e.isTypeCastExpression())return e.node.typeAnnotation;if(e.isObjectExpression())return m.genericTypeAnnotation(m.identifier("Object"));if(e.isFunction())return m.identifier("Function");if(e.isLiteral()){var t=e.node.value;if(c(t))return m.stringTypeAnnotation();if(u(t))return m.numberTypeAnnotation();if(o(t))return m.booleanTypeAnnotation()}if(e.isCallExpression()){var n=e.get("callee").resolve();if(n&&n.isFunction())return n.node.returnType}}},e.prototype.isScope=function(){return m.isScope(this.node,this.parent)},e.prototype.isReferencedIdentifier=function(e){return m.isReferencedIdentifier(this.node,this.parent,e)},e.prototype.isReferenced=function(){return m.isReferenced(this.node,this.parent)},e.prototype.isBlockScoped=function(){return m.isBlockScoped(this.node)},e.prototype.isVar=function(){return m.isVar(this.node)},e.prototype.isPreviousType=function(e){return m.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:m.isGenericTypeAnnotation(r)&&m.isIdentifier(r.id,{name:e})?t.requireTypeParameters&&!r.typeParameters?!1:!0:!1:!1},e.prototype.getBindingIdentifiers=function(){return m.getBindingIdentifiers(this.node)},e.prototype.traverse=function(e){var t=function(t,n){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(m.isIdentifier(i)){if(n[l]!==i.name)return!1}else{if(!m.isLiteral(i)){if(m.isMemberExpression(i)){if(i.computed&&!m.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},i(e,{node:{get:function(){return this.removed?null:this.container[this.key]},set:function(e){throw new Error("Don't use `path.node = newNode;`, use `path.replaceWith(newNode)` or `path.replaceWithMultiple([newNode])`")}}}),e}();t.exports=y,f(y.prototype,e("./evaluation")),f(y.prototype,e("./conversion"));for(var v=0;v<m.TYPES.length;v++)!function(){var e=m.TYPES[v],t="is"+e;y.prototype[t]=function(e){return m[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,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},l=function(e){return e&&e.__esModule?e["default"]:e},i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=l(e("lodash/collection/includes")),s=l(e("./index")),o=l(e("lodash/object/defaults")),u=r(e("../messages")),c=l(e("./binding")),p=l(e("globals")),d=l(e("lodash/array/flatten")),f=l(e("lodash/object/extend")),h=l(e("../helpers/object")),m=l(e("lodash/collection/each")),g=r(e("../types")),y={enter:function(e,t,n,r){var l=this;return g.isFor(e)&&m(g.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()&&g.isDeclaration(e.declaration)||this.isDeclaration()&&r.scope.registerDeclaration(this))}},v={enter:function(e,t,n,r){g.isReferencedIdentifier(e,t)&&!n.hasBinding(e.name)?r.addGlobal(e):g.isLabeledStatement(e)?r.addGlobal(e):g.isAssignmentExpression(e)?n.registerConstantViolation(this.get("left"),this.get("right")):g.isUpdateExpression(e)?n.registerConstantViolation(this.get("argument"),null):g.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()}},x=function(){function e(t,n,r){if(i(this,e),n&&n.block===t.node)return n;var l=t.getData("scope");return l&&l.parent===n?l:(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=d([p.builtin,p.browser,p.node].map(Object.keys)),e.contextVariables=["this","arguments","super"],e.prototype.traverse=function(e){var t=function(t,n,r){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 g.identifier(this.generateUid(e))},e.prototype.generateUid=function(e){e=g.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;g.isAssignmentExpression(e)?n=e.left:g.isVariableDeclarator(e)?n=e.id:g.isProperty(n)&&(n=n.key);var r=[],l=function(e){var t=function(t){return e.apply(this,arguments)};return t.toString=function(){return e.toString()},t}(function(e){if(g.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(g.isModuleSpecifier(e))l(e.local);else if(g.isMemberExpression(e))l(e.object),l(e.property);else if(g.isIdentifier(e))r.push(e.name);else if(g.isLiteral(e))r.push(e.value);else if(g.isCallExpression(e))l(e.callee);else if(g.isObjectExpression(e)||g.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(g.isThisExpression(e)||g.isSuper(e))return null;if(g.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,u.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(g.isReferencedIdentifier(n,r)&&n.name===e)n.name=t;else if(g.isDeclaration(n)){var a=this.getBindingIdentifiers();for(var s in a)s===e&&(a[s].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(g.isIdentifier(e)){var r=this.getBinding(e.name);if(r&&r.isTypeGeneric("Array",{inference:!1}))return e}if(g.isArrayExpression(e))return e;if(g.isIdentifier(e,{name:"arguments"}))return g.callExpression(g.memberExpression(n.addHelper("slice"),g.identifier("call")),[e]);var l="to-array",i=[e];return t===!0?l="to-consumable-array":t&&(i.push(g.literal(t)),l="sliced-to-array",this.file.isLoose("es6.forOf")&&(l+="-loose")),g.callExpression(n.addHelper(l),i)},e.prototype.registerDeclaration=function(e){var t=e.node;if(g.isFunctionDeclaration(t))this.registerBinding("hoisted",e);else if(g.isVariableDeclaration(t))for(var n=e.get("declarations"),r=0;r<n.length;r++)this.registerBinding(t.kind,n[r]);else g.isClassDeclaration(t)?this.registerBinding("let",e):g.isImportDeclaration(t)||g.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 c({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 f(this,t);if(t=this.block._scopeInfo={bindings:h(),globals:h()},f(this,t),e.isLoop())for(var n=0;n<g.FOR_INIT_KEYS.length;n++){var r=e.get(g.FOR_INIT_KEYS[n]);r.isBlockScoped()&&this.registerBinding("let",r)}if(e.isFunctionExpression()&&e.has("id")&&(g.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,y,{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,v,this)},e.prototype.push=function(e){var t=this.block;(g.isLoop(t)||g.isCatchClause(t)||g.isFunction(t))&&(g.ensureBlock(t),t=t.body),g.isBlockStatement(t)||g.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&&!g.isFunction(e.block);)e=e.parent;return e},e.prototype.getBlockParent=function(){for(var e=this;e.parent&&!g.isFunction(e.block)&&!g.isLoop(e.block)&&!g.isFunction(e.block);)e=e.parent;return e},e.prototype.getAllBindings=function(){var e=h(),t=this;do o(e,t.bindings),t=t.parent;while(t);return e},e.prototype.getAllBindingsOfKind=function(){for(var e=h(),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:a(e.globals,t)?!0:a(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=x},{"../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,n){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,n){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||b.isIdentifier(t)&&(t=b.literal(t.name)),t}()}function l(e,t){function n(e){for(var t=!1,i=[],a=0;a<e.length;a++){var s=e[a];if(b.isExpression(s))i.push(s);else if(b.isExpressionStatement(s))i.push(s.expression);else{if(b.isVariableDeclaration(s)){if("var"!==s.kind)return l=!0;v(s.declarations,function(e){var t=b.getBindingIdentifiers(e);for(var n in t)r.push({kind:s.kind,id:t[n]});e.init&&i.push(b.assignmentExpression("=",e.id,e.init))}),t=!0;continue}if(b.isIfStatement(s)){var o=s.consequent?n([s.consequent]):b.identifier("undefined"),u=s.alternate?n([s.alternate]):b.identifier("undefined");if(!o||!u)return l=!0;i.push(b.conditionalExpression(s.test,o,u))}else{if(!b.isBlockStatement(s))return l=!0;i.push(n(s.body))}}t=!1}return t&&i.push(b.identifier("undefined")),1===i.length?i[0]:b.sequenceExpression(i)}var r=[],l=!1,i=n(e);if(!l){for(var a=0;a<r.length;a++)t.push(r[a]);return i}}function i(e){var t=void 0===arguments[1]?e.key:arguments[1];return function(){var n;return n=b.isIdentifier(t)?t.name:JSON.stringify(b.isLiteral(t)?t.value:y.removeProperties(b.cloneDeep(t))),e.computed&&(n="["+n+"]"),n}()}function a(e){return b.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():""}),b.isValidIdentifier(e)||(e="_"+e),e||"_")}function s(e,t){if(b.isStatement(e))return e;var n,r=!1;if(b.isClass(e))r=!0,n="ClassDeclaration";else if(b.isFunction(e))r=!0,n="FunctionDeclaration";else if(b.isAssignmentExpression(e))return b.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(b.isExpressionStatement(e)&&(e=e.expression),b.isClass(e)?e.type="ClassExpression":b.isFunction(e)&&(e.type="FunctionExpression"),b.isExpression(e))return e;throw new Error("cannot turn "+e.type+" to an expression")}function u(e,t){return b.isBlockStatement(e)?e:(b.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(b.isStatement(e)||(e=b.isFunction(t)?b.returnStatement(e):b.expressionStatement(e)),e=[e]),b.blockStatement(e))}function c(e){if(void 0===e)return b.identifier("undefined");if(e===!0||e===!1||null===e||g(e)||h(e)||m(e))return b.literal(e);if(Array.isArray(e))return b.arrayExpression(e.map(b.valueToNode));if(f(e)){var t=[];for(var n in e){var r;r=b.isValidIdentifier(n)?b.identifier(n):b.literal(n),t.push(b.property("init",r,b.valueToNode(e[n])))}return b.objectExpression(t)}throw new Error("don't know how to turn this value into a node")}var p=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=a,n.toStatement=s,n.toExpression=o,n.toBlock=u,n.valueToNode=c,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")),v=d(e("lodash/collection/each")),b=p(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,r){if(!t)return!1;var l=i(t.type,e);return l?"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 a(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 s(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 c(e){var t={};for(var n in e)"_"!==n[0]&&(t[n]=e[n]);return t}function p(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(T,function(t){delete e[t]}),e}function h(e,t){return e&&t&&x(T,function(n){e[n]=E(v([].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=a,n.appendToMemberExpression=s,n.prependToMemberExpression=o,n.ensureBlock=u,n.clone=c,n.cloneDeep=p,n.buildMatchMemberExpression=d,n.removeComments=f,n.inheritsComments=h,n.inherits=m,n.__esModule=!0;var y=g(e("to-fast-properties")),v=g(e("lodash/array/compact")),b=g(e("lodash/object/assign")),x=g(e("lodash/collection/each")),E=g(e("lodash/array/uniq")),_=n,w=["consequent","body","alternate"];n.STATEMENT_OR_BLOCK_KEYS=w;var S=["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=S;var I=["body","expressions"];n.FLATTENABLE_KEYS=I;var k=["left","init"];n.FOR_INIT_KEYS=k;var T=["leadingComments","trailingComments"];n.COMMENT_KEYS=T;var C=e("./visitor-keys");n.VISITOR_KEYS=C;var j=e("./builder-keys");n.BUILDER_KEYS=j;var M=e("./alias-keys");n.ALIAS_KEYS=M,_.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 A=Object.keys(_.VISITOR_KEYS).concat(Object.keys(_.FLIPPED_ALIAS_KEYS));n.TYPES=A,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,b(_,e("./retrievers")),b(_,e("./validators")),b(_,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":453}],154:[function(e,t,n){"use strict";function r(e){for(var t=[].concat(e),n=s();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 a=l[i];t=t.concat(r[a]||[])}}}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}},a=function(e){return e&&e.__esModule?e["default"]:e};n.getBindingIdentifiers=r,n.getLastStatements=l,n.__esModule=!0;var s=a(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 a(e){return g.isVariableDeclaration(e)&&("var"!==e.kind||e._let)}function s(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 c(e,t){return g.isBlockStatement(e)&&g.isFunction(t,{body:e})?!1:g.isScopable(e)}function p(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=a,n.isBlockScoped=s,n.isVar=o,n.isSpecifierDefault=u,n.isScope=c,n.isImmutable=p,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,n){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=M.extname(e);return w(n,r)}function i(t){try{return e.resolve(t)}catch(n){return null}}function a(e){R||(R=new T,R.paths=T._nodeModulePaths(t.cwd()));try{return T._resolveFilename(e,R)}catch(n){return null}}function s(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")),I(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(I(e))return u(s(e),t);if(Array.isArray(e))return t&&(e=e.map(t)),e;throw new TypeError("illegal type for arrayify")}function c(e){return"true"===e?!0:"false"===e?!1:e}function p(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=b(l),C(t)||S(l,F,null,t),l.body.length>1)return l.body;var i=l.body[0];return!r&&P.isExpressionStatement(i)?i.expression:i}function f(e,t){var n=j({filename:e,looseModules:!0},t).program;return n=S.removeProperties(n)}function h(){var e={},t=M.join(r,"transformation/templates");if(!L.existsSync(t))throw new ReferenceError(E.get("missingTemplatesDirectory"));return A(L.readdirSync(t),function(n){if("."!==n[0]){var r=M.basename(n,M.extname(n)),l=M.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=a,n.list=s,n.regexify=o,n.arrayify=u,n.booleanify=c,n.shouldIgnore=p,n.template=d,n.parseTemplate=f,n.__esModule=!0,e("./patch");var y=g(e("lodash/string/escapeRegExp")),v=g(e("debug/node")),b=g(e("lodash/lang/cloneDeep")),x=g(e("lodash/lang/isBoolean")),E=m(e("./messages")),_=g(e("minimatch")),w=g(e("lodash/collection/contains")),S=g(e("./traversal")),I=g(e("lodash/lang/isString")),k=g(e("lodash/lang/isRegExp")),T=g(e("module")),C=g(e("lodash/lang/isEmpty")),j=g(e("./helpers/parse")),M=g(e("path")),A=g(e("lodash/collection/each")),O=g(e("lodash/object/has")),L=g(e("fs")),P=m(e("./types")),N=e("util");n.inherits=N.inherits,n.inspect=N.inspect;var D=v("babel");n.debug=D,l.EXTENSIONS=[".js",".jsx",".es6",".es"];var R,F={enter:function(e,t,n,r){P.isExpressionStatement(e)&&(e=e.expression),P.isIdentifier(e)&&O(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":456,"./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,t,n){var r=e("../lib/types"),l=r.Type,i=l.def,a=l.or,s=r.builtInTypes,o=s.string,u=s.number,c=s["boolean"],p=s.RegExp,d=e("../lib/shared"),f=d.defaults,h=d.geq;i("Printable").field("loc",a(i("SourceLocation"),null),f["null"],!0),i("Node").bases("Printable").field("type",o).field("comments",a([i("Comment")],null),f["null"],!0),i("SourceLocation").build("start","end","source").field("start",i("Position")).field("end",i("Position")).field("source",a(o,null),f["null"]),i("Position").build("line","column").field("line",h(1)).field("column",h(0)),i("Program").bases("Node").build("body").field("body",[i("Statement")]),i("Function").bases("Node").field("id",a(i("Identifier"),null),f["null"]).field("params",[i("Pattern")]).field("body",i("BlockStatement")),i("Statement").bases("Node"),i("EmptyStatement").bases("Statement").build(),i("BlockStatement").bases("Statement").build("body").field("body",[i("Statement")]),i("ExpressionStatement").bases("Statement").build("expression").field("expression",i("Expression")),i("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",i("Expression")).field("consequent",i("Statement")).field("alternate",a(i("Statement"),null),f["null"]),i("LabeledStatement").bases("Statement").build("label","body").field("label",i("Identifier")).field("body",i("Statement")),i("BreakStatement").bases("Statement").build("label").field("label",a(i("Identifier"),null),f["null"]),i("ContinueStatement").bases("Statement").build("label").field("label",a(i("Identifier"),null),f["null"]),i("WithStatement").bases("Statement").build("object","body").field("object",i("Expression")).field("body",i("Statement")),i("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",i("Expression")).field("cases",[i("SwitchCase")]).field("lexical",c,f["false"]),i("ReturnStatement").bases("Statement").build("argument").field("argument",a(i("Expression"),null)),i("ThrowStatement").bases("Statement").build("argument").field("argument",i("Expression")),i("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",i("BlockStatement")).field("handler",a(i("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[i("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[i("CatchClause")],f.emptyArray).field("finalizer",a(i("BlockStatement"),null),f["null"]), i("CatchClause").bases("Node").build("param","guard","body").field("param",i("Pattern")).field("guard",a(i("Expression"),null),f["null"]).field("body",i("BlockStatement")),i("WhileStatement").bases("Statement").build("test","body").field("test",i("Expression")).field("body",i("Statement")),i("DoWhileStatement").bases("Statement").build("body","test").field("body",i("Statement")).field("test",i("Expression")),i("ForStatement").bases("Statement").build("init","test","update","body").field("init",a(i("VariableDeclaration"),i("Expression"),null)).field("test",a(i("Expression"),null)).field("update",a(i("Expression"),null)).field("body",i("Statement")),i("ForInStatement").bases("Statement").build("left","right","body","each").field("left",a(i("VariableDeclaration"),i("Expression"))).field("right",i("Expression")).field("body",i("Statement")).field("each",c),i("DebuggerStatement").bases("Statement").build(),i("Declaration").bases("Statement"),i("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",i("Identifier")),i("FunctionExpression").bases("Function","Expression").build("id","params","body"),i("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",a("var","let","const")).field("declarations",[a(i("VariableDeclarator"),i("Identifier"))]),i("VariableDeclarator").bases("Node").build("id","init").field("id",i("Pattern")).field("init",a(i("Expression"),null)),i("Expression").bases("Node","Pattern"),i("ThisExpression").bases("Expression").build(),i("ArrayExpression").bases("Expression").build("elements").field("elements",[a(i("Expression"),null)]),i("ObjectExpression").bases("Expression").build("properties").field("properties",[i("Property")]),i("Property").bases("Node").build("kind","key","value").field("kind",a("init","get","set")).field("key",a(i("Literal"),i("Identifier"))).field("value",a(i("Expression"),i("Pattern"))),i("SequenceExpression").bases("Expression").build("expressions").field("expressions",[i("Expression")]);var m=a("-","+","!","~","typeof","void","delete");i("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",m).field("argument",i("Expression")).field("prefix",c,f["true"]);var g=a("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");i("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",g).field("left",i("Expression")).field("right",i("Expression"));var y=a("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");i("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",y).field("left",i("Pattern")).field("right",i("Expression"));var v=a("++","--");i("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",v).field("argument",i("Expression")).field("prefix",c);var b=a("||","&&");i("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",b).field("left",i("Expression")).field("right",i("Expression")),i("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",i("Expression")).field("consequent",i("Expression")).field("alternate",i("Expression")),i("NewExpression").bases("Expression").build("callee","arguments").field("callee",i("Expression")).field("arguments",[i("Expression")]),i("CallExpression").bases("Expression").build("callee","arguments").field("callee",i("Expression")).field("arguments",[i("Expression")]),i("MemberExpression").bases("Expression").build("object","property","computed").field("object",i("Expression")).field("property",a(i("Identifier"),i("Expression"))).field("computed",c,f["false"]),i("Pattern").bases("Node"),i("ObjectPattern").bases("Pattern").build("properties").field("properties",[a(i("PropertyPattern"),i("Property"))]),i("PropertyPattern").bases("Pattern").build("key","pattern").field("key",a(i("Literal"),i("Identifier"))).field("pattern",i("Pattern")),i("ArrayPattern").bases("Pattern").build("elements").field("elements",[a(i("Pattern"),null)]),i("SwitchCase").bases("Node").build("test","consequent").field("test",a(i("Expression"),null)).field("consequent",[i("Statement")]),i("Identifier").bases("Node","Expression","Pattern").build("name").field("name",o),i("Literal").bases("Node","Expression").build("value").field("value",a(o,c,null,u,p)),i("Comment").bases("Printable").field("value",o).field("leading",c,f["true"]).field("trailing",c,f["false"]),i("Block").bases("Comment").build("value","leading","trailing"),i("Line").bases("Comment").build("value","leading","trailing")},{"../lib/shared":169,"../lib/types":170}],159:[function(e,t,n){e("./core");var r=e("../lib/types"),l=r.Type.def,i=r.Type.or,a=r.builtInTypes,s=a.string,o=a["boolean"];l("XMLDefaultDeclaration").bases("Declaration").field("namespace",l("Expression")),l("XMLAnyName").bases("Expression"),l("XMLQualifiedIdentifier").bases("Expression").field("left",i(l("Identifier"),l("XMLAnyName"))).field("right",i(l("Identifier"),l("Expression"))).field("computed",o),l("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",i(l("Identifier"),l("Expression"))).field("computed",o),l("XMLAttributeSelector").bases("Expression").field("attribute",l("Expression")),l("XMLFilterExpression").bases("Expression").field("left",l("Expression")).field("right",l("Expression")),l("XMLElement").bases("XML","Expression").field("contents",[l("XML")]),l("XMLList").bases("XML","Expression").field("contents",[l("XML")]),l("XML").bases("Node"),l("XMLEscape").bases("XML").field("expression",l("Expression")),l("XMLText").bases("XML").field("text",s),l("XMLStartTag").bases("XML").field("contents",[l("XML")]),l("XMLEndTag").bases("XML").field("contents",[l("XML")]),l("XMLPointTag").bases("XML").field("contents",[l("XML")]),l("XMLName").bases("XML").field("contents",i(s,[l("XML")])),l("XMLAttribute").bases("XML").field("value",s),l("XMLCdata").bases("XML").field("contents",s),l("XMLComment").bases("XML").field("contents",s),l("XMLProcessingInstruction").bases("XML").field("target",s).field("contents",i(s,null))},{"../lib/types":170,"./core":158}],160:[function(e,t,n){e("./core");var r=e("../lib/types"),l=r.Type.def,i=r.Type.or,a=r.builtInTypes,s=a["boolean"],o=(a.object,a.string),u=e("../lib/shared").defaults;l("Function").field("generator",s,u["false"]).field("expression",s,u["false"]).field("defaults",[i(l("Expression"),null)],u.emptyArray).field("rest",i(l("Identifier"),null),u["null"]),l("FunctionDeclaration").build("id","params","body","generator","expression"),l("FunctionExpression").build("id","params","body","generator","expression"),l("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,u["null"]).field("body",i(l("BlockStatement"),l("Expression"))).field("generator",!1,u["false"]),l("YieldExpression").bases("Expression").build("argument","delegate").field("argument",i(l("Expression"),null)).field("delegate",s,u["false"]),l("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",l("Expression")).field("blocks",[l("ComprehensionBlock")]).field("filter",i(l("Expression"),null)),l("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",l("Expression")).field("blocks",[l("ComprehensionBlock")]).field("filter",i(l("Expression"),null)),l("ComprehensionBlock").bases("Node").build("left","right","each").field("left",l("Pattern")).field("right",l("Expression")).field("each",s),l("ModuleSpecifier").bases("Literal").build("value").field("value",o),l("Property").field("key",i(l("Literal"),l("Identifier"),l("Expression"))).field("method",s,u["false"]).field("shorthand",s,u["false"]).field("computed",s,u["false"]),l("PropertyPattern").field("key",i(l("Literal"),l("Identifier"),l("Expression"))).field("computed",s,u["false"]),l("MethodDefinition").bases("Declaration").build("kind","key","value","static").field("kind",i("init","get","set","")).field("key",i(l("Literal"),l("Identifier"),l("Expression"))).field("value",l("Function")).field("computed",s,u["false"]).field("static",s,u["false"]),l("SpreadElement").bases("Node").build("argument").field("argument",l("Expression")),l("ArrayExpression").field("elements",[i(l("Expression"),l("SpreadElement"),null)]),l("NewExpression").field("arguments",[i(l("Expression"),l("SpreadElement"))]),l("CallExpression").field("arguments",[i(l("Expression"),l("SpreadElement"))]),l("SpreadElementPattern").bases("Pattern").build("argument").field("argument",l("Pattern")),l("ArrayPattern").field("elements",[i(l("Pattern"),null,l("SpreadElement"))]);var c=i(l("MethodDefinition"),l("VariableDeclarator"),l("ClassPropertyDefinition"),l("ClassProperty"));l("ClassProperty").bases("Declaration").build("key").field("key",i(l("Literal"),l("Identifier"),l("Expression"))).field("computed",s,u["false"]),l("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",c),l("ClassBody").bases("Declaration").build("body").field("body",[c]),l("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",i(l("Identifier"),null)).field("body",l("ClassBody")).field("superClass",i(l("Expression"),null),u["null"]),l("ClassExpression").bases("Expression").build("id","body","superClass").field("id",i(l("Identifier"),null),u["null"]).field("body",l("ClassBody")).field("superClass",i(l("Expression"),null),u["null"]).field("implements",[l("ClassImplements")],u.emptyArray),l("ClassImplements").bases("Node").build("id").field("id",l("Identifier")).field("superClass",i(l("Expression"),null),u["null"]),l("Specifier").bases("Node"),l("NamedSpecifier").bases("Specifier").field("id",l("Identifier")).field("name",i(l("Identifier"),null),u["null"]),l("ExportSpecifier").bases("NamedSpecifier").build("id","name"),l("ExportBatchSpecifier").bases("Specifier").build(),l("ImportSpecifier").bases("NamedSpecifier").build("id","name"),l("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",l("Identifier")),l("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",l("Identifier")),l("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",s).field("declaration",i(l("Declaration"),l("Expression"),null)).field("specifiers",[i(l("ExportSpecifier"),l("ExportBatchSpecifier"))],u.emptyArray).field("source",i(l("ModuleSpecifier"),null),u["null"]),l("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[i(l("ImportSpecifier"),l("ImportNamespaceSpecifier"),l("ImportDefaultSpecifier"))],u.emptyArray).field("source",l("ModuleSpecifier")),l("TaggedTemplateExpression").bases("Expression").field("tag",l("Expression")).field("quasi",l("TemplateLiteral")),l("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[l("TemplateElement")]).field("expressions",[l("Expression")]),l("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:o,raw:o}).field("tail",s)},{"../lib/shared":169,"../lib/types":170,"./core":158}],161:[function(e,t,n){e("./core");var r=e("../lib/types"),l=r.Type.def,i=r.Type.or,a=r.builtInTypes,s=a["boolean"],o=e("../lib/shared").defaults;l("Function").field("async",s,o["false"]),l("SpreadProperty").bases("Node").build("argument").field("argument",l("Expression")),l("ObjectExpression").field("properties",[i(l("Property"),l("SpreadProperty"))]),l("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",l("Pattern")),l("ObjectPattern").field("properties",[i(l("PropertyPattern"),l("SpreadPropertyPattern"),l("Property"),l("SpreadProperty"))]),l("AwaitExpression").bases("Expression").build("argument","all").field("argument",i(l("Expression"),null)).field("all",s,o["false"])},{"../lib/shared":169,"../lib/types":170,"./core":158}],162:[function(e,t,n){e("./core");var r=e("../lib/types"),l=r.Type.def,i=r.Type.or,a=r.builtInTypes,s=a.string,o=a["boolean"],u=e("../lib/shared").defaults;l("JSXAttribute").bases("Node").build("name","value").field("name",i(l("JSXIdentifier"),l("JSXNamespacedName"))).field("value",i(l("Literal"),l("JSXExpressionContainer"),null),u["null"]),l("JSXIdentifier").bases("Identifier").build("name").field("name",s),l("JSXNamespacedName").bases("Node").build("namespace","name").field("namespace",l("JSXIdentifier")).field("name",l("JSXIdentifier")),l("JSXMemberExpression").bases("MemberExpression").build("object","property").field("object",i(l("JSXIdentifier"),l("JSXMemberExpression"))).field("property",l("JSXIdentifier")).field("computed",o,u["false"]);var c=i(l("JSXIdentifier"),l("JSXNamespacedName"),l("JSXMemberExpression"));l("JSXSpreadAttribute").bases("Node").build("argument").field("argument",l("Expression"));var p=[i(l("JSXAttribute"),l("JSXSpreadAttribute"))];l("JSXExpressionContainer").bases("Expression").build("expression").field("expression",l("Expression")),l("JSXElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",l("JSXOpeningElement")).field("closingElement",i(l("JSXClosingElement"),null),u["null"]).field("children",[i(l("JSXElement"),l("JSXExpressionContainer"),l("JSXText"),l("Literal"))],u.emptyArray).field("name",c,function(){return this.openingElement.name}).field("selfClosing",o,function(){return this.openingElement.selfClosing}).field("attributes",p,function(){return this.openingElement.attributes}),l("JSXOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",c).field("attributes",p,u.emptyArray).field("selfClosing",o,u["false"]),l("JSXClosingElement").bases("Node").build("name").field("name",c),l("JSXText").bases("Literal").build("value").field("value",s),l("JSXEmptyExpression").bases("Expression").build(),l("Type").bases("Node"),l("AnyTypeAnnotation").bases("Type"),l("VoidTypeAnnotation").bases("Type"),l("NumberTypeAnnotation").bases("Type"),l("StringTypeAnnotation").bases("Type"),l("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",s).field("raw",s),l("BooleanTypeAnnotation").bases("Type"),l("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",l("Type")),l("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",l("Type")),l("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[l("FunctionTypeParam")]).field("returnType",l("Type")).field("rest",i(l("FunctionTypeParam"),null)).field("typeParameters",i(l("TypeParameterDeclaration"),null)),l("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",l("Identifier")).field("typeAnnotation",l("Type")).field("optional",o),l("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",l("Type")),l("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[l("ObjectTypeProperty")]).field("indexers",[l("ObjectTypeIndexer")],u.emptyArray).field("callProperties",[l("ObjectTypeCallProperty")],u.emptyArray),l("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",i(l("Literal"),l("Identifier"))).field("value",l("Type")).field("optional",o),l("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",l("Identifier")).field("key",l("Type")).field("value",l("Type")),l("ObjectTypeCallProperty").bases("Node").build("value").field("value",l("FunctionTypeAnnotation")).field("static",o,!1),l("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",i(l("Identifier"),l("QualifiedTypeIdentifier"))).field("id",l("Identifier")),l("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",i(l("Identifier"),l("QualifiedTypeIdentifier"))).field("typeParameters",i(l("TypeParameterInstantiation"),null)),l("MemberTypeAnnotation").bases("Type").build("object","property").field("object",l("Identifier")).field("property",i(l("MemberTypeAnnotation"),l("GenericTypeAnnotation"))),l("UnionTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",l("Type")),l("Identifier").field("typeAnnotation",i(l("TypeAnnotation"),null),u["null"]),l("TypeParameterDeclaration").bases("Node").build("params").field("params",[l("Identifier")]),l("TypeParameterInstantiation").bases("Node").build("params").field("params",[l("Type")]),l("Function").field("returnType",i(l("TypeAnnotation"),null),u["null"]).field("typeParameters",i(l("TypeParameterDeclaration"),null),u["null"]),l("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",l("TypeAnnotation")).field("static",o,!1),l("ClassImplements").field("typeParameters",i(l("TypeParameterInstantiation"),null),u["null"]),l("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",l("Identifier")).field("typeParameters",i(l("TypeParameterDeclaration"),null),u["null"]).field("body",l("ObjectTypeAnnotation")).field("extends",[l("InterfaceExtends")]),l("InterfaceExtends").bases("Node").build("id").field("id",l("Identifier")).field("typeParameters",i(l("TypeParameterInstantiation"),null)),l("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",l("Identifier")).field("typeParameters",i(l("TypeParameterDeclaration"),null)).field("right",l("Type")),l("TypeCastExpression").bases("Expression").build("expression","typeAnnotation").field("expression",l("Expression")).field("typeAnnotation",l("TypeAnnotation")),l("TupleTypeAnnotation").bases("Type").build("types").field("types",[l("Type")]),l("DeclareVariable").bases("Statement").build("id").field("id",l("Identifier")),l("DeclareFunction").bases("Statement").build("id").field("id",l("Identifier")),l("DeclareClass").bases("InterfaceDeclaration").build("id"),l("DeclareModule").bases("Statement").build("id","body").field("id",i(l("Identifier"),l("Literal"))).field("body",l("BlockStatement"))},{"../lib/shared":169,"../lib/types":170,"./core":158}],163:[function(e,t,n){e("./core");var r=e("../lib/types"),l=r.Type.def,i=r.Type.or,a=e("../lib/shared").geq;l("Function").field("body",i(l("BlockStatement"),l("Expression"))),l("ForOfStatement").bases("Statement").build("left","right","body").field("left",i(l("VariableDeclaration"),l("Expression"))).field("right",l("Expression")).field("body",l("Statement")),l("LetStatement").bases("Statement").build("head","body").field("head",[l("VariableDeclarator")]).field("body",l("Statement")),l("LetExpression").bases("Expression").build("head","body").field("head",[l("VariableDeclarator")]).field("body",l("Expression")),l("GraphExpression").bases("Expression").build("index","expression").field("index",a(0)).field("expression",l("Literal")),l("GraphIndexExpression").bases("Expression").build("index").field("index",a(0))},{"../lib/shared":169,"../lib/types":170,"./core":158}],164:[function(e,t,n){function r(e,t,n){return d.check(n)?n.length=0:n=null,i(e,t,n)}function l(e){return/[_$a-z][_$a-z0-9]*/i.test(e)?"."+e:"["+JSON.stringify(e)+"]"}function i(e,t,n){return e===t?!0:d.check(e)?a(e,t,n):f.check(e)?s(e,t,n):h.check(e)?h.check(t)&&+e===+t:m.check(e)?m.check(t)&&e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.ignoreCase===t.ignoreCase:e==t}function a(e,t,n){d.assert(e);var r=e.length;if(!d.check(t)||t.length!==r)return n&&n.push("length"),!1;for(var l=0;r>l;++l){if(n&&n.push(l),l in e!=l in t)return!1;if(!i(e[l],t[l],n))return!1;n&&o.strictEqual(n.pop(),l)}return!0}function s(e,t,n){if(f.assert(e),!f.check(t))return!1;if(e.type!==t.type)return n&&n.push("type"),!1;var r=c(e),l=r.length,a=c(t),s=a.length;if(l===s){for(var u=0;l>u;++u){var d=r[u],h=p(e,d),m=p(t,d);if(n&&n.push(d),!i(h,m,n))return!1;n&&o.strictEqual(n.pop(),d)}return!0}if(!n)return!1;var y=Object.create(null);for(u=0;l>u;++u)y[r[u]]=!0;for(u=0;s>u;++u){if(d=a[u],!g.call(y,d))return n.push(d),!1;delete y[d]}for(d in y){n.push(d);break}return!1}var o=e("assert"),u=e("../main"),c=u.getFieldNames,p=u.getFieldValue,d=u.builtInTypes.array,f=u.builtInTypes.object,h=u.builtInTypes.Date,m=u.builtInTypes.RegExp,g=Object.prototype.hasOwnProperty;r.assert=function(e,t){var n=[];r(e,t,n)||(0===n.length?o.strictEqual(e,t):o.ok(!1,"Nodes differ in the following path: "+n.map(l).join("")))},t.exports=r},{"../main":171,assert:173}],165:[function(e,t,n){function r(e,t,n){u.ok(this instanceof r),m.call(this,e,t,n)}function l(e){return p.BinaryExpression.check(e)||p.LogicalExpression.check(e)}function i(e){return p.CallExpression.check(e)?!0:h.check(e)?e.some(i):p.Node.check(e)?c.someField(e,function(e,t){return i(t)}):!1}function a(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 u.strictEqual(n.body[0],t),!0;if(p.ExpressionStatement.check(n)&&"expression"===e.name)return u.strictEqual(n.expression,t),!0;if(p.SequenceExpression.check(n)&&"expressions"===e.parent.name&&0===e.name)u.strictEqual(n.expressions[0],t);else if(p.CallExpression.check(n)&&"callee"===e.name)u.strictEqual(n.callee,t);else if(p.MemberExpression.check(n)&&"object"===e.name)u.strictEqual(n.object,t);else if(p.ConditionalExpression.check(n)&&"test"===e.name)u.strictEqual(n.test,t);else if(l(n)&&"left"===e.name)u.strictEqual(n.left,t);else{if(!p.UnaryExpression.check(n)||n.prefix||"argument"!==e.name)return!1;u.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)&&o(e);return e}function o(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=d.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=d.expressionStatement(t);e.replace(i)}}var u=e("assert"),c=e("./types"),p=c.namedTypes,d=c.builders,f=c.builtInTypes.number,h=c.builtInTypes.array,m=e("./path"),g=e("./scope");e("util").inherits(r,m);var y=r.prototype;Object.defineProperties(y,{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}}}),y.replace=function(){return delete this.node,delete this.parent,delete this.scope,m.prototype.replace.apply(this,arguments)},y.prune=function(){var e=this.parent;return this.replace(),s(e)},y._computeNode=function(){var e=this.value;if(p.Node.check(e))return e;var t=this.parentPath;return t&&t.node||null},y._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},y._computeScope=function(){var e=this.value,t=this.parentPath,n=t&&t.scope;return p.Node.check(e)&&g.isEstablishedBy(e)&&(n=new g(this,n)),n||null},y.getValueProperty=function(e){return c.getFieldValue(this.value,e)},y.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 l=r.operator,t=v[l],a=n.operator,s=v[a];if(t>s)return!0;if(t===s&&"right"===this.name)return u.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&&f.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 i(n)}return e!==!0&&!this.canBeFirstInStatement()&&this.firstInStatement()?!0:!1};var v={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){v[e]=t})}),y.canBeFirstInStatement=function(){var e=this.node;return!p.FunctionExpression.check(e)&&!p.ObjectExpression.check(e)},y.firstInStatement=function(){return a(this)},t.exports=r},{"./path":167,"./scope":168,"./types":170,assert:173,util:199}],166:[function(e,t,n){function r(){u.ok(this instanceof r),this._reusableContextStack=[],this._methodNameTable=l(this),this._shouldVisitComments=g.call(this._methodNameTable,"Block")||g.call(this._methodNameTable,"Line"),this.Context=s(this),this._visiting=!1,this._changeReported=!1}function l(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=c.computeSupertypeLookupTable(t),l=Object.create(null),t=Object.keys(r),i=t.length,a=0;i>a;++a){var s=t[a];n="visit"+r[s],m.check(e[n])&&(l[s]=n)}return l}function i(e,t){for(var n in t)g.call(t,n)&&(e[n]=t[n]);return e}function a(e,t){u.ok(e instanceof p),u.ok(t instanceof r);var n=e.value;if(f.check(n))e.each(t.visitWithoutReset,t);else if(h.check(n)){var l=c.getFieldNames(n);t._shouldVisitComments&&n.comments&&l.indexOf("comments")<0&&l.push("comments");for(var i=l.length,a=[],s=0;i>s;++s){var o=l[s];g.call(n,o)||(n[o]=c.getFieldValue(n,o)),a.push(e.get(o))}for(var s=0;i>s;++s)t.visitWithoutReset(a[s])}else;return e.value}function s(e){function t(n){u.ok(this instanceof t),u.ok(this instanceof r),u.ok(n instanceof p),Object.defineProperty(this,"visitor",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.currentPath=n,this.needToCallTraverse=!0,Object.seal(this)}u.ok(e instanceof r);var n=t.prototype=Object.create(e);return n.constructor=t,i(n,b),t}var o,u=e("assert"),c=e("./types"),p=e("./node-path"),d=c.namedTypes.Printable,f=c.builtInTypes.array,h=c.builtInTypes.object,m=c.builtInTypes["function"],g=Object.prototype.hasOwnProperty;r.fromMethodsObject=function(e){function t(){u.ok(this instanceof t),r.call(this)}if(e instanceof r)return e;if(!h.check(e))return new r;var n=t.prototype=Object.create(y);return n.constructor=t,i(n,e),i(t,r),m.assert(t.fromMethodsObject),m.assert(t.visit),new t},r.visit=function(e,t){return r.fromMethodsObject(t).visit(e)};var y=r.prototype,v=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");y.visit=function(){u.ok(!this._visiting,v),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},y.AbortRequest=function(){},y.abort=function(){var e=this;e._abortRequested=!0;var t=new e.AbortRequest;throw t.cancel=function(){e._abortRequested=!1},t},y.reset=function(e){},y.visitWithoutReset=function(e){if(this instanceof this.Context)return this.visitor.visitWithoutReset(e);u.ok(e instanceof p);var t=e.value,n=d.check(t)&&this._methodNameTable[t.type];if(!n)return a(e,this);var r=this.acquireContext(e);try{return r.invokeVisitorMethod(n)}finally{this.releaseContext(r)}},y.acquireContext=function(e){return 0===this._reusableContextStack.length?new this.Context(e):this._reusableContextStack.pop().reset(e)},y.releaseContext=function(e){u.ok(e instanceof this.Context),this._reusableContextStack.push(e),e.currentPath=null},y.reportChanged=function(){this._changeReported=!0},y.wasChangeReported=function(){return this._changeReported};var b=Object.create(null);b.reset=function(e){return u.ok(this instanceof this.Context),u.ok(e instanceof p),this.currentPath=e,this.needToCallTraverse=!0,this},b.invokeVisitorMethod=function(e){u.ok(this instanceof this.Context),u.ok(this.currentPath instanceof p);var t=this.visitor[e].call(this,this.currentPath);t===!1?this.needToCallTraverse=!1:t!==o&&(this.currentPath=this.currentPath.replace(t)[0],this.needToCallTraverse&&this.traverse(this.currentPath)),u.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 u.ok(this instanceof this.Context),u.ok(e instanceof p),u.ok(this.currentPath instanceof p),this.needToCallTraverse=!1,a(e,r.fromMethodsObject(t||this.visitor))},b.visit=function(e,t){return u.ok(this instanceof this.Context),u.ok(e instanceof p),u.ok(this.currentPath instanceof p),this.needToCallTraverse=!1,r.fromMethodsObject(t||this.visitor).visitWithoutReset(e)},b.reportChanged=function(){this.visitor.reportChanged()},b.abort=function(){this.needToCallTraverse=!1,this.visitor.abort()},t.exports=r},{"./node-path":165,"./types":170,assert:173}],167:[function(e,t,n){function r(e,t,n){u.ok(this instanceof r),t?u.ok(t instanceof r):(t=null,n=null),this.value=e,this.parentPath=t,this.name=n,this.__childCache=null}function l(e){return e.__childCache||(e.__childCache=Object.create(null))}function i(e,t){var n=l(e),r=e.getValueProperty(t),i=n[t];return p.call(n,t)&&i.value===r||(i=n[t]=new e.constructor(r,e,t)),i}function a(){}function s(e,t,n,r){if(f.assert(e.value),0===t)return a;var i=e.value.length;if(1>i)return a;var s=arguments.length;2===s?(n=0,r=i):3===s?(n=Math.max(n,0),r=i):(n=Math.max(n,0),r=Math.min(r,i)),h.assert(n),h.assert(r);for(var o=Object.create(null),c=l(e),d=n;r>d;++d)if(p.call(e.value,d)){var m=e.get(d);u.strictEqual(m.name,d);var g=d+t;m.name=g,o[g]=m,delete c[d]}return delete c.length,function(){for(var t in o){var n=o[t];u.strictEqual(n.name,+t),c[t]=n,e.value[t]=n.value}}}function o(e){u.ok(e instanceof r);var t=e.parentPath;if(!t)return e;var n=t.value,i=l(t);if(n[e.name]===e.value)i[e.name]=e;else if(f.check(n)){var a=n.indexOf(e.value);a>=0&&(i[e.name=a]=e)}else n[e.name]=e.value,i[e.name]=e;return u.strictEqual(n[e.name],e.value),u.strictEqual(e.parentPath.get(e.name),e),e}var u=e("assert"),c=Object.prototype,p=c.hasOwnProperty,d=e("./types"),f=d.builtInTypes.array,h=d.builtInTypes.number,m=Array.prototype,g=(m.slice,m.map,r.prototype);g.getValueProperty=function(e){return this.value[e]},g.get=function(e){for(var t=this,n=arguments,r=n.length,l=0;r>l;++l)t=i(t,n[l]);return t},g.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])},g.map=function(e,t){var n=[]; return this.each(function(t){n.push(e.call(this,t))},t),n},g.filter=function(e,t){var n=[];return this.each(function(t){e.call(this,t)&&n.push(t)},t),n},g.shift=function(){var e=s(this,-1),t=this.value.shift();return e(),t},g.unshift=function(e){var t=s(this,arguments.length),n=this.value.unshift.apply(this.value,arguments);return t(),n},g.push=function(e){return f.assert(this.value),delete l(this).length,this.value.push.apply(this.value,arguments)},g.pop=function(){f.assert(this.value);var e=l(this);return delete e[this.value.length-1],delete e.length,this.value.pop()},g.insertAt=function(e,t){var n=arguments.length,r=s(this,n-1,e);if(r===a)return this;e=Math.max(e,0);for(var l=1;n>l;++l)this.value[e+l-1]=arguments[l];return r(),this},g.insertBefore=function(e){for(var t=this.parentPath,n=arguments.length,r=[this.name],l=0;n>l;++l)r.push(arguments[l]);return t.insertAt.apply(t,r)},g.insertAfter=function(e){for(var t=this.parentPath,n=arguments.length,r=[this.name+1],l=0;n>l;++l)r.push(arguments[l]);return t.insertAt.apply(t,r)},g.replace=function(e){var t=[],n=this.parentPath.value,r=l(this.parentPath),i=arguments.length;if(o(this),f.check(n)){for(var a=n.length,c=s(this.parentPath,i-1,this.name+1),p=[this.name,1],d=0;i>d;++d)p.push(arguments[d]);var h=n.splice.apply(n,p);if(u.strictEqual(h[0],this.value),u.strictEqual(n.length,a-1+i),c(),0===i)delete this.value,delete r[this.name],this.__childCache=null;else{for(u.strictEqual(n[this.name],e),this.value!==e&&(this.value=e,this.__childCache=null),d=0;i>d;++d)t.push(this.parentPath.get(this.name+d));u.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):u.ok(!1,"Could not replace path");return t},t.exports=r},{"./types":170,assert:173}],168:[function(e,t,n){function r(t,n){o.ok(this instanceof r),o.ok(t instanceof e("./node-path")),v.assert(t.value);var l;n?(o.ok(n instanceof r),l=n.depth+1):(n=null,l=0),Object.defineProperties(this,{path:{value:t},node:{value:t.value},isGlobal:{value:!n,enumerable:!0},depth:{value:l},parent:{value:n},bindings:{value:{}}})}function l(e,t){var n=e.value;v.assert(n),p.CatchClause.check(n)?s(e.get("param"),t):i(e,t)}function i(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&&(h.check(n)?e.each(function(e){a(e,t)}):p.Function.check(n)?(e.get("params").each(function(e){s(e,t)}),a(e.get("body"),t)):p.VariableDeclarator.check(n)?(s(e.get("id"),t),a(e.get("init"),t)):"ImportSpecifier"===n.type||"ImportNamespaceSpecifier"===n.type||"ImportDefaultSpecifier"===n.type?s(e.get(n.name?"name":"id"),t):d.check(n)&&!f.check(n)&&u.eachField(n,function(n,r){var l=e.get(n);o.strictEqual(l.value,r),a(l,t)}))}function a(e,t){var n=e.value;if(!n||f.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(v.check(n)){if(p.CatchClause.check(n)){var r=n.param.name,l=m.call(t,r);i(e.get("body"),t),l||delete t[r]}}else i(e,t)}function s(e,t){var n=e.value;p.Pattern.assert(n),p.Identifier.check(n)?m.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 o=e("assert"),u=e("./types"),c=u.Type,p=u.namedTypes,d=p.Node,f=p.Expression,h=u.builtInTypes.array,m=Object.prototype.hasOwnProperty,g=u.builders,y=[p.Program,p.Function,p.CatchClause],v=c.or.apply(c,y);r.isEstablishedBy=function(e){return v.check(e)};var b=r.prototype;b.didScan=!1,b.declares=function(e){return this.scan(),m.call(this.bindings,e)},b.declareTemporary=function(e){e?o.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]=u.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(g.variableDeclaration("var",[g.variableDeclarator(e,t||null)])),e},b.scan=function(e){if(e||!this.didScan){for(var t in this.bindings)delete this.bindings[t];l(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=r},{"./node-path":165,"./types":170,assert:173}],169:[function(e,t,n){var r=e("../lib/types"),l=r.Type,i=r.builtInTypes,a=i.number;n.geq=function(e){return new l(function(t){return a.check(t)&&t>=e},a+" >= "+e)},n.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return!1},"true":function(){return!0},undefined:function(){}};var s=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)},s.toString())},{"../lib/types":170}],170:[function(e,t,n){function r(e,t){var n=this;h.ok(n instanceof r,n),h.strictEqual(b.call(e),x,e+" is not a function");var l=b.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&&b.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(", ")+"}":T.check(e)?"["+e.map(l).join(", ")+"]":JSON.stringify(e)}function i(e,t){var n=b.call(e);return Object.defineProperty(S,t,{enumerable:!0,value:new r(function(e){return b.call(e)===n},t)}),S[t]}function a(e,t){return e instanceof r?e:e instanceof o?e.type:T.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},M.check(t)?function(){return e+""}:t)}function s(e,t,n,r){var l=this;h.ok(l instanceof s),I.assert(e),t=a(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 c(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 p(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=O[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,a=i,s=t.length;s>a;++a)_.call(t,a)&&(t[i++]=t[a]);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),v=Object.prototype,b=v.toString,x=b.call(function(){}),E=b.call(""),_=v.hasOwnProperty,w=r.prototype;n.Type=r,w.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},w.toString=function(){var e=this.name;return I.check(e)?e:k.check(e)?e.call(this)+"":e+" type"};var S={};n.builtInTypes=S;var I=i("","string"),k=i(function(){},"function"),T=i([],"array"),C=i({},"object"),j=(i(/./,"RegExp"),i(new Date,"Date"),i(3,"number")),M=(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(a(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(T.check(e)),h.strictEqual(e.length,1,"only one element type is permitted for typed arrays"),a(e[0]).arrayOf()},w.arrayOf=function(){var e=this;return new r(function(t,n){return T.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 s(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 A=s.prototype;A.toString=function(){return JSON.stringify(this.name)+": "+this.type},A.getValue=function(e){var t=e[this.name];return M.check(t)?(this.defaultFn&&(t=this.defaultFn.call(e)),t):t},r.def=function(e){return I.assert(e),_.call(O,e)?O[e]:O[e]=new o(e)};var O=Object.create(null);o.fromValue=function(e){if(e&&"object"==typeof e){var t=e.type;if("string"==typeof t&&_.call(O,t)){var n=O[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(O,e));var t=O[e];return h.strictEqual(t.finalized,!0),t.supertypeList.slice(1)},n.computeSupertypeLookupTable=function(e){for(var t={},n=Object.keys(O),r=n.length,l=0;r>l;++l){var i=n[l],a=O[i];h.strictEqual(a.finalized,!0);for(var s=0;s<a.supertypeList.length;++s){var o=a.supertypeList[s];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,a=l.getValue(e);return i.check(a,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){I.assert(t),e.indexOf(t)<0&&e.push(t)}),this},Object.defineProperty(L,"buildable",{value:!1});var P={};n.builders=P;var N={};n.defineMethod=function(e,t){var n=N[e];return M.check(t)?delete N[e]:(k.assert(t),Object.defineProperty(N,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),I.arrayOf().assert(e.buildParams),e.buildable?e:(e.field("type",e.typeName,function(){return e.typeName}),Object.defineProperty(e,"buildable",{value:!0}),Object.defineProperty(P,u(e.typeName),{enumerable:!0,value:function(){function t(t,a){if(!_.call(i,t)){var s=e.allFields;h.ok(_.call(s,t),t);var o,u=s[t],c=u.type;if(j.check(a)&&r>a)o=n[a];else if(u.defaultFn)o=u.defaultFn.call(i);else{var p="no value or default function given for field "+JSON.stringify(t)+" of "+e.typeName+"("+e.buildParams.map(function(e){return s[e]}).join(", ")+")";h.ok(!1,p)}c.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(N);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 s(e,t,n,r),this};var D={};n.namedTypes=D,n.getFieldNames=c,n.getFieldValue=p,n.eachField=function(e,t,n){c(e).forEach(function(n){t.call(this,n,p(e,n))},n)},n.someField=function(e,t,n){return c(e).some(function(n){return t.call(this,n,p(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=O[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(D,this.typeName,{enumerable:!0,value:this.type}),Object.defineProperty(this,"finalized",{value:!0}),d(this.typeName,this.supertypeList)}},n.finalize=function(){Object.keys(O).forEach(function(e){O[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(e,t,n){},{}],173:[function(e,t,n){function r(e,t){return f.isUndefined(t)?""+t:f.isNumber(t)&&!isFinite(t)?t.toString():f.isFunction(t)||f.isRegExp(t)?t.toString():t}function l(e,t){return f.isString(e)?e.length<t?e:e.slice(0,t):e}function i(e){return l(JSON.stringify(e.actual,r),128)+" "+e.operator+" "+l(JSON.stringify(e.expected,r),128)}function a(e,t,n,r,l){throw new g.AssertionError({message:n,actual:e,expected:t,operator:r,stackStartFunction:l})}function s(e,t){e||a(e,!0,t,"==",g.ok)}function o(e,t){if(e===t)return!0;if(f.isBuffer(e)&&f.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 f.isDate(e)&&f.isDate(t)?e.getTime()===t.getTime():f.isRegExp(e)&&f.isRegExp(t)?e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.lastIndex===t.lastIndex&&e.ignoreCase===t.ignoreCase:f.isObject(e)||f.isObject(t)?c(e,t):e==t}function u(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function c(e,t){if(f.isNullOrUndefined(e)||f.isNullOrUndefined(t))return!1;if(e.prototype!==t.prototype)return!1;if(f.isPrimitive(e)||f.isPrimitive(t))return e===t;var n=u(e),r=u(t);if(n&&!r||!n&&r)return!1;if(n)return e=h.call(e),t=h.call(t),o(e,t);var l,i,a=y(e),s=y(t);if(a.length!=s.length)return!1;for(a.sort(),s.sort(),i=a.length-1;i>=0;i--)if(a[i]!=s[i])return!1;for(i=a.length-1;i>=0;i--)if(l=a[i],!o(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 d(e,t,n,r){var l;f.isString(n)&&(r=n,n=null);try{t()}catch(i){l=i}if(r=(n&&n.name?" ("+n.name+").":".")+(r?" "+r:"."),e&&!l&&a(l,n,"Missing expected exception"+r),!e&&p(l,n)&&a(l,n,"Got unwanted exception"+r),e&&l&&n&&!p(l,n)||!e&&l)throw l}var f=e("util/"),h=Array.prototype.slice,m=Object.prototype.hasOwnProperty,g=t.exports=s;g.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=i(this),this.generatedMessage=!0);var t=e.stackStartFunction||a;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var n=new Error;if(n.stack){var r=n.stack,l=t.name,s=r.indexOf("\n"+l);if(s>=0){var o=r.indexOf("\n",s+1);r=r.substring(o+1)}this.stack=r}}},f.inherits(g.AssertionError,Error),g.fail=a,g.ok=s,g.equal=function(e,t,n){e!=t&&a(e,t,n,"==",g.equal)},g.notEqual=function(e,t,n){e==t&&a(e,t,n,"!=",g.notEqual)},g.deepEqual=function(e,t,n){o(e,t)||a(e,t,n,"deepEqual",g.deepEqual)},g.notDeepEqual=function(e,t,n){o(e,t)&&a(e,t,n,"notDeepEqual",g.notDeepEqual)},g.strictEqual=function(e,t,n){e!==t&&a(e,t,n,"===",g.strictEqual)},g.notStrictEqual=function(e,t,n){e===t&&a(e,t,n,"!==",g.notStrictEqual)},g["throws"]=function(e,t,n){d.apply(this,[!0].concat(h.call(arguments)))},g.doesNotThrow=function(e,t){d.apply(this,[!1].concat(h.call(arguments)))},g.ifError=function(e){if(e)throw e};var y=Object.keys||function(e){var t=[];for(var n in e)m.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&&D(e.data)&&(e=e.data),l=+e.length}if(l>R)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+R.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 a;if(r.TYPED_ARRAY_SUPPORT&&"number"==typeof e.byteLength)n._set(e);else if(k(e))if(r.isBuffer(e))for(a=0;l>a;a++)n[a]=e.readUInt8(a);else for(a=0;l>a;a++)n[a]=(e[a]%256+256)%256;else if("string"===i)n.write(e,0,t);else if("number"===i&&!r.TYPED_ARRAY_SUPPORT)for(a=0;l>a;a++)n[a]=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 a=0;r>a;a++){var s=parseInt(t.substr(2*a,2),16);if(isNaN(s))throw new Error("Invalid hex string");e[n+a]=s}return a}function a(e,t,n,r){var l=O(C(t,e.length-n),e,n,r);return l}function s(e,t,n,r){var l=O(j(t),e,n,r);return l}function o(e,t,n,r){return s(e,t,n,r)}function u(e,t,n,r){var l=O(A(t),e,n,r);return l}function c(e,t,n,r){var l=O(M(t,e.length-n),e,n,r);return l}function p(e,t,n){return P.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+=T(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 v(e,t,n,l,i,a){if(!r.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||a>t)throw new RangeError("value is out of bounds");if(n+l>e.length)throw new RangeError("index out of range")}function b(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),N.write(e,t,n,r,23,4),n+4}function w(e,t,n,r,l){return l||E(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),N.write(e,t,n,r,52,8),n+8}function S(e){if(e=I(e).replace(U,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function I(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function k(e){return D(e)||r.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function T(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=[],a=0;r>a;a++){if(n=e.charCodeAt(a),n>55295&&57344>n){if(!l){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+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 j(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}function M(e,t){for(var n,r,l,i=[],a=0;a<e.length&&!((t-=2)<0);a++)n=e.charCodeAt(a),r=n>>8,l=n%256,i.push(l),i.push(r);return i}function A(e){return P.toByteArray(S(e))}function O(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 P=e("base64-js"),N=e("ieee754"),D=e("is-array");n.Buffer=r,n.SlowBuffer=l,n.INSPECT_MAX_BYTES=50,r.poolSize=8192;var R=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,a=Math.min(n,l);a>i&&e[i]===t[i];i++);return i!==a&&(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(!D(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 a=e[n];a.copy(l,i),i+=a.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=A(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||n===1/0?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 p(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 p=this.length-t;n?(n=Number(n),n>p&&(n=p)):n=p,r=String(r||"utf8").toLowerCase();var d;switch(r){case"hex":d=i(this,e,t,n);break;case"utf8":case"utf-8":d=a(this,e,t,n);break;case"ascii":d=s(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=c(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 a=0;i>a;a++)l[a]=this[a+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),N.read(this,e,!0,23,4)},r.prototype.readFloatBE=function(e,t){return t||y(e,4,this.length),N.read(this,e,!1,23,4)},r.prototype.readDoubleLE=function(e,t){return t||y(e,8,this.length),N.read(this,e,!0,52,8)},r.prototype.readDoubleBE=function(e,t){return t||y(e,8,this.length),N.read(this,e,!1,52,8)},r.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||v(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||v(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||v(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||v(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):b(this,e,t,!0),t+2},r.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):b(this,e,t,!1),t+2},r.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||v(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||v(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||v(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var l=0,i=1,a=0>e?1:0;for(this[t]=255&e;++l<n&&(i*=256);)this[t+l]=(e/i>>0)-a&255;return t+n},r.prototype.writeIntBE=function(e,t,n,r){e=+e,t>>>=0,r||v(this,e,t,n,Math.pow(2,8*n-1)-1,-Math.pow(2,8*n-1));var l=n-1,i=1,a=0>e?1:0;for(this[t+l]=255&e;--l>=0&&(i*=256);)this[t+l]=(e/i>>0)-a&255;return t+n},r.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||v(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||v(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e,this[t+1]=e>>>8):b(this,e,t,!0),t+2},r.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||v(this,e,t,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e):b(this,e,t,!1),t+2},r.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||v(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||v(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 w(this,e,t,!0,n)},r.prototype.writeDoubleBE=function(e,t,n){return w(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 a=0;i>a;a++)e[a+t]=this[a+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 U=/[^+\/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===a||t===p?62:t===s||t===d?63:o>t?-1:o+10>t?t-o+26+26:c+26>t?t-c:u+26>t?t-u+26:void 0}function n(e){function n(e){u[p++]=e}var r,l,a,s,o,u;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var c=e.length;o="="===e.charAt(c-2)?2:"="===e.charAt(c-1)?1:0,u=new i(3*e.length/4-o),a=o>0?e.length-4:e.length;var p=0;for(r=0,l=0;a>r;r+=4,l+=3)s=t(e.charAt(r))<<18|t(e.charAt(r+1))<<12|t(e.charAt(r+2))<<6|t(e.charAt(r+3)),n((16711680&s)>>16),n((65280&s)>>8),n(255&s);return 2===o?(s=t(e.charAt(r))<<2|t(e.charAt(r+1))>>4,n(255&s)):1===o&&(s=t(e.charAt(r))<<10|t(e.charAt(r+1))<<4|t(e.charAt(r+2))>>2,n(s>>8&255),n(255&s)),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,a,s=e.length%3,o="";for(l=0,a=e.length-s;a>l;l+=3)i=(e[l]<<16)+(e[l+1]<<8)+e[l+2],o+=n(i);switch(s){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,a="+".charCodeAt(0),s="/".charCodeAt(0),o="0".charCodeAt(0),u="a".charCodeAt(0),c="A".charCodeAt(0),p="-".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,a,s=8*l-r-1,o=(1<<s)-1,u=o>>1,c=-7,p=n?l-1:0,d=n?-1:1,f=e[t+p];for(p+=d,i=f&(1<<-c)-1,f>>=-c,c+=s;c>0;i=256*i+e[t+p],p+=d,c-=8);for(a=i&(1<<-c)-1,i>>=-c,c+=r;c>0;a=256*a+e[t+p],p+=d,c-=8);if(0===i)i=1-u;else{if(i===o)return a?0/0:(f?-1:1)*(1/0);a+=Math.pow(2,r),i-=u}return(f?-1:1)*a*Math.pow(2,i-r)},n.write=function(e,t,n,r,l,i){var a,s,o,u=8*i-l-1,c=(1<<u)-1,p=c>>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)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(o=Math.pow(2,-a))<1&&(a--,o*=2),t+=a+p>=1?d/o:d*Math.pow(2,1-p),t*o>=2&&(a++,o/=2),a+p>=c?(s=0,a=c):a+p>=1?(s=(t*o-1)*Math.pow(2,l),a+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,l),a=0));l>=8;e[n+f]=255&s,f+=h,s/=256,l-=8);for(a=a<<l|s,u+=l;u>0;e[n+f]=255&a,f+=h,a/=256,u-=8);e[n+f-h]|=128*m}},{}],178:[function(e,t,n){var r=Array.isArray,l=Object.prototype.toString;t.exports=r||function(e){return!!e&&"[object Array]"==l.call(e)}},{}],179:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function l(e){return"function"==typeof e}function i(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,i,o,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(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(l(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(r=arguments.length,i=new Array(r-1),o=1;r>o;o++)i[o-1]=arguments[o];n.apply(this,i)}else if(a(n)){for(r=arguments.length,i=new Array(r-1),o=1;r>o;o++)i[o-1]=arguments[o];for(u=n.slice(),r=u.length,o=0;r>o;o++)u[o].apply(this,i)}return!0},r.prototype.addListener=function(e,t){var n;if(!l(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,l(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned){var n;n=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,n&&n>0&&this._events[e].length>n&&(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},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!l(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,i,s;if(!l(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],i=n.length,r=-1,n===t||l(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=i;s-->0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(0>r)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.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],l(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?l(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?l(e._events[t])?1:e._events[t].length:0}},{}],180:[function(e,t,n){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,n){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 a=i>=0?arguments[i]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(n=a+"/"+n,l="/"===a.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="/"===a(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,t){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("/")),a=Math.min(l.length,i.length),s=a,o=0;a>o;o++)if(l[o]!==i[o]){s=o;break}for(var u=[],o=s;o<l.length;o++)u.push("..");return u=u.concat(i.slice(s)),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 a="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,n){function r(){if(!s){s=!0;for(var e,t=a.length;t;){e=a,a=[];for(var n=-1;++n<t;)e[n]();t=a.length}s=!1}}function l(){}var i=t.exports={},a=[],s=!1;i.nextTick=function(e){a.push(e),s||setTimeout(r,0)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=l,i.addListener=l,i.once=l,i.off=l,i.removeListener=l,i.removeAllListeners=l,i.emit=l,i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],184:[function(e,t,n){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":185}],185:[function(e,t,n){(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 a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t},s=e("core-util-is");s.inherits=e("inherits");var o=e("./_stream_readable"),u=e("./_stream_writable");s.inherits(r,o),i(a(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,n){function r(e){return this instanceof r?void l.call(this,e):new r(e)}t.exports=r;var l=e("./_stream_transform"),i=e("core-util-is");i.inherits=e("inherits"),i.inherits(r,l),r.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":188,"core-util-is":190,inherits:180}],187:[function(e,t,n){(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(T.isNullOrUndefined(n))t.reading=!1,t.ended||c(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!l){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&l){var s=new Error("stream.unshift() after end event");e.emit("error",s)}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&&p(e)),f(e,t);else l||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}function s(e){if(e>=M)e=M;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)||T.isNull(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:0>=e?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function u(e,t){var n=null;return T.isBuffer(t)||T.isString(t)||T.isNullOrUndefined(t)||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(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,p(e)}function p(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(j("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?n.nextTick(function(){d(e)}):d(e))}function d(e){j("emit readable"),e.emit("readable"),v(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&&(j("maybeReadMore read 0"),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}function m(e){return function(){var t=e._readableState;j("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&I.listenerCount(e,"data")&&(t.flowing=!0,v(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"),v(e),t.flowing&&!t.reading&&e.read(0)}function v(e){var t=e._readableState;if(j("flow",t.flowing),t.flowing)do var n=e.read();while(null!==n&&t.flowing)}function b(e,t){var n,r=t.buffer,l=t.length,i=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===l)n=null;else if(a)n=r.shift();else if(!e||e>=l)n=i?r.join(""):S.concat(r,l),r.length=0;else if(e<r[0].length){var s=r[0];n=s.slice(0,e),r[0]=s.slice(e)}else if(e===r[0].length)n=r.shift();else{n=i?"":new S(e);for(var o=0,u=0,c=r.length;c>u&&e>o;u++){var s=r[0],p=Math.min(e-o,s.length);i?n+=s.slice(0,p):s.copy(n,o,0,p),p<s.length?r[0]=s.slice(p):r.shift(),o+=p}}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 w=e("isarray"),S=e("buffer").Buffer;l.ReadableState=r;var I=e("events").EventEmitter;I.listenerCount||(I.listenerCount=function(e,t){return e.listeners(t).length});var k=e("stream"),T=e("core-util-is");T.inherits=e("inherits");var C,j=e("util");j=j&&j.debuglog?j.debuglog("stream"):function(){},T.inherits(l,k),l.prototype.push=function(e,t){var n=this._readableState;return T.isString(e)&&!n.objectMode&&(t=t||n.defaultEncoding,t!==n.encoding&&(e=new S(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 M=8388608;l.prototype.read=function(e){j("read",e);var t=this._readableState,n=e;if((!T.isNumber(e)||e>0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return j("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):p(this),null;if(e=o(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;j("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&(r=!0,j("length less than watermark",r)),(t.ended||t.reading)&&(r=!1,j("reading or ended",r)),r&&(j("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?b(e,t):null,T.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),T.isNull(l)||this.emit("data",l),l},l.prototype._read=function(e){this.emit("error",new Error("not implemented"))},l.prototype.pipe=function(e,t){function r(e){j("onunpipe"),e===p&&i()}function l(){j("onend"),e.end()}function i(){j("cleanup"),e.removeListener("close",o),e.removeListener("finish",u),e.removeListener("drain",g),e.removeListener("error",s),e.removeListener("unpipe",r),p.removeListener("end",l),p.removeListener("end",i),p.removeListener("data",a),!d.awaitDrain||e._writableState&&!e._writableState.needDrain||g()}function a(t){j("ondata");var n=e.write(t);!1===n&&(j("false write response, pause",p._readableState.awaitDrain),p._readableState.awaitDrain++,p.pause())}function s(t){j("onerror",t),c(),e.removeListener("error",s),0===I.listenerCount(e,"error")&&e.emit("error",t)}function o(){e.removeListener("finish",u),c()}function u(){j("onfinish"),e.removeListener("close",o),c()}function c(){j("unpipe"),p.unpipe(e)}var p=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,j("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):p.once("end",h),e.on("unpipe",r);var g=m(p);return e.on("drain",g),p.on("data",a),e._events&&e._events.error?w(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",o),e.once("finish",u),e.emit("pipe",p),d.flowing||(j("pipe resume"),p.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&&p(this,l);else{var i=this;n.nextTick(function(){j("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||(j("resume"),e.flowing=!0,e.reading||(j("resume read 0"),this.read(0)),g(this,e)),this},l.prototype.pause=function(){return j("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(j("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(j("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(j("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)T.isFunction(e[l])&&T.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){j("wrapped _read",t),n&&(n=!1,e.resume())},r},l._fromList=b}).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,n){function r(e,t){this.afterTransform=function(e,n){return l(t,e,n)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function l(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,o.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 i(e){if(!(this instanceof i))return new i(e);s.call(this,e),this._transformState=new r(e,this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,this.once("prefinish",function(){o.isFunction(this._flush)?this._flush(function(e){a(t,e)}):a(t)})}function a(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=i;var s=e("./_stream_duplex"),o=e("core-util-is");o.inherits=e("inherits"),o.inherits(i,s),i.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},i.prototype._transform=function(e,t,n){throw new Error("not implemented")},i.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)}},i.prototype._read=function(e){var t=this._transformState;o.isNull(t.writechunk)||!t.writecb||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))}},{"./_stream_duplex":185,"core-util-is":190,inherits:180}],189:[function(e,t,n){(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 a=t.decodeStrings===!1;this.decodeStrings=!a,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 w.call(this)):new i(t)}function a(e,t,r){var l=new Error("write after end");e.emit("error",l),n.nextTick(function(){r(l)})}function s(e,t,r,l){var i=!0;if(!(_.isBuffer(r)||_.isString(r)||_.isNullOrUndefined(r)||t.objectMode)){var a=new TypeError("Invalid non-string/buffer chunk");e.emit("error",a),n.nextTick(function(){l(a)}),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 a=t.objectMode?1:n.length;t.length+=a;var s=t.length<t.highWaterMark;return s||(t.needDrain=!0),t.writing||t.corked?t.buffer.push(new r(n,l,i)):c(e,t,!1,a,n,l,i),s}function c(e,t,n,r,l,i,a){t.writelen=r,t.writecb=a,t.writing=!0,t.sync=!0,n?e._writev(l,t.onwrite):e._write(l,i,t.onwrite),t.sync=!1}function p(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)p(e,r,l,t,i);else{var a=y(e,r);a||r.corked||r.bufferProcessing||!r.buffer.length||g(e,r),l?n.nextTick(function(){h(e,r,a,i)}):h(e,r,a,i)}}function h(e,t,n,r){n||m(e,t),t.pendingcb--,r(),b(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++,c(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,a=l.encoding,s=l.callback,o=t.objectMode?1:i.length;if(c(e,t,!1,o,i,a,s),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 v(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function b(e,t){var n=y(e,t);return n&&(0===t.pendingcb?(v(e,t),t.finished=!0,e.emit("finish")):v(e,t)),n}function x(e,t,r){t.ending=!0,b(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 w=e("stream");_.inherits(i,w),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?a(this,r,n):s(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 a(e){return"number"==typeof e}function s(e){return"string"==typeof e}function o(e){return"symbol"==typeof e}function u(e){return void 0===e}function c(e){return p(e)&&"[object RegExp]"===y(e)}function p(e){return"object"==typeof e&&null!==e}function d(e){return p(e)&&"[object Date]"===y(e)}function f(e){return p(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=a,n.isString=s,n.isSymbol=o,n.isUndefined=u,n.isRegExp=c,n.isObject=p,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,n){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,n){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":188}],194:[function(e,t,n){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":189}],195:[function(e,t,n){function r(){l.call(this)}t.exports=r;var l=e("events").EventEmitter,i=e("inherits");i(r,l),r.Readable=e("readable-stream/readable.js"),r.Writable=e("readable-stream/writable.js"),r.Duplex=e("readable-stream/duplex.js"),r.Transform=e("readable-stream/transform.js"),r.PassThrough=e("readable-stream/passthrough.js"),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&u.pause&&u.pause()}function r(){u.readable&&u.resume&&u.resume()}function i(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(o(),0===l.listenerCount(this,"error"))throw e}function o(){u.removeListener("data",n),e.removeListener("drain",r),u.removeListener("end",i),u.removeListener("close",a),u.removeListener("error",s),e.removeListener("error",s),u.removeListener("end",o),u.removeListener("close",o),e.removeListener("close",o)}var u=this;u.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(u.on("end",i),u.on("close",a));var c=!1;return u.on("error",s),e.on("error",s),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 a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e("buffer").Buffer,o=s.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=a;break;default:return void(this.write=l)}this.charBuffer=new s(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,n){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:a};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 a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){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 b(l)||(l=o(e,l,r)),l}var i=u(e,t);if(i)return i;var a=Object.keys(t),m=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),I(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.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(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(I(t))return c(t)}var y="",v=!1,x=["{","}"];if(h(t)&&(v=!0,x=["[","]"]),k(t)){var E=t.name?": "+t.name:"";y=" [Function"+E+"]"}if(_(t)&&(y=" "+RegExp.prototype.toString.call(t)),S(t)&&(y=" "+Date.prototype.toUTCString.call(t)),I(t)&&(y=" "+c(t)),0===a.length&&(!v||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 w;return w=v?p(e,t,r,m,a):a.map(function(n){return d(e,t,r,m,n,v)}),e.seen.pop(),f(w,y,x)}function u(e,t){if(E(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return v(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,l){for(var i=[],a=0,s=t.length;s>a;++a)i.push(A(t,String(a))?d(e,t,n,r,String(a),!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 a,s,u;if(u=Object.getOwnPropertyDescriptor(t,l)||{value:t[l]},u.get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),A(r,l)||(a="["+l+"]"),s||(e.seen.indexOf(u.value)<0?(s=g(n)?o(e,u.value,null):o(e,u.value,n-1),s.indexOf("\n")>-1&&(s=i?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),E(a)){if(i&&l.match(/^\d+$/))return s;a=JSON.stringify(""+l),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}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 v(e){return"number"==typeof e}function b(e){return"string"==typeof e}function x(e){return"symbol"==typeof e}function E(e){return void 0===e}function _(e){return w(e)&&"[object RegExp]"===C(e)}function w(e){return"object"==typeof e&&null!==e}function S(e){return w(e)&&"[object Date]"===C(e)}function I(e){return w(e)&&("[object Error]"===C(e)||e instanceof Error)}function k(e){return"function"==typeof e}function T(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 j(e){return 10>e?"0"+e.toString(10):e.toString(10)}function M(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),N[e.getMonth()],t].join(" ")}function A(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var O=/%[sdj%]/g;n.format=function(e){if(!b(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,a=String(e).replace(O,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}}),s=r[n];i>n;s=r[++n])a+=g(s)||!w(s)?" "+s:" "+l(s);return a},n.deprecate=function(e,l){function i(){if(!a){if(t.throwDeprecation)throw new Error(l);t.traceDeprecation?console.trace(l):console.error(l),a=!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 a=!1;return i};var L,P={};n.debuglog=function(e){if(E(L)&&(L=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!P[e])if(new RegExp("\\b"+e+"\\b","i").test(L)){var r=t.pid;P[e]=function(){var t=n.format.apply(n,arguments);console.error("%s %d: %s",e,r,t)}}else P[e]=function(){};return P[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=v,n.isString=b,n.isSymbol=x,n.isUndefined=E,n.isRegExp=_,n.isObject=w,n.isDate=S,n.isError=I,n.isFunction=k,n.isPrimitive=T,n.isBuffer=e("./support/isBuffer");var N=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",M(),n.format.apply(n,arguments))},n.inherits=e("inherits"),n._extend=function(e,t){if(!t||!w(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,n){(function(n){"use strict";function r(e){this.enabled=e&&void 0!==e.enabled?e.enabled:p}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 a=o[l[i]];n=a.open+n.replace(a.closeRe,a.open)+a.close}return n}function a(){var e={};return Object.keys(f).forEach(function(t){e[t]={get:function(){return l.call(this,[t])}}}),e}var s=e("escape-string-regexp"),o=e("ansi-styles"),u=e("strip-ansi"),c=e("has-ansi"),p=e("supports-color"),d=Object.defineProperties;"win32"===n.platform&&(o.blue.open="");var f=function(){var e={};return Object.keys(o).forEach(function(t){o[t].closeRe=new RegExp(s(o[t].close),"g"),e[t]={get:function(){return l.call(this,this._styles.concat(t))}}}),e}(),h=d(function(){},f);d(r.prototype,a()),t.exports=new r,t.exports.styles=o,t.exports.hasColor=c,t.exports.stripColor=u,t.exports.supportsColor=p}).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,n){"use strict";var r=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]}};r.colors.grey=r.colors.gray,Object.keys(r).forEach(function(e){var t=r[e];Object.keys(t).forEach(function(e){var n=t[e];r[e]=t[e]={open:"["+n[0]+"m",close:"["+n[1]+"m"}}),Object.defineProperty(r,e,{value:t,enumerable:!1})})},{}],202:[function(e,t,n){"use strict";var r=/[|\\{}()[\]^$+*?.]/g;t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(r,"\\$&")}},{}],203:[function(e,t,n){"use strict";var r=e("ansi-regex"),l=new RegExp(r().source);t.exports=l.test.bind(l)},{"ansi-regex":204}],204:[function(e,t,n){"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,n){"use strict";var r=e("ansi-regex")();t.exports=function(e){return"string"==typeof e?e.replace(r,""):e}},{"ansi-regex":206}],206:[function(e,t,n){arguments[4][204][0].apply(n,arguments)},{dup:204}],207:[function(e,t,n){(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=c.exec(e);c.lastIndex=0;var r=n[1]||n[2],l=o.join(t,r);try{return s.readFileSync(l,"utf8")}catch(i){throw new Error("An error occurred while trying to read the map file at "+l+"\n"+i)}}function a(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 s=e("fs"),o=e("path"),u=/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+;)?base64,(.*)$/gm,c=/(?:\/\/[@#][ \t]+sourceMappingURL=(.+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/gm;a.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},a.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")},a.prototype.toComment=function(){var e=this.toBase64();return"//# sourceMappingURL=data:application/json;base64,"+e},a.prototype.toObject=function(){return JSON.parse(this.toJSON())},a.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)},a.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},a.prototype.getProperty=function(e){return this.sourcemap[e]},n.fromObject=function(e){return new a(e)},n.fromJSON=function(e){return new a(e,{isJSON:!0})},n.fromBase64=function(e){return new a(e,{isEncoded:!0})},n.fromComment=function(e){return e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),new a(e,{isEncoded:!0,hasComment:!0})},n.fromMapFileComment=function(e,t){return new a(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(c);return c.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 c.lastIndex=0,e.replace(c,"")},n.__defineGetter__("commentRegex",function(){return u.lastIndex=0,u}),n.__defineGetter__("mapFileCommentRegex",function(){return c.lastIndex=0,c})}).call(this,e("buffer").Buffer)},{buffer:175,fs:172,path:182}],209:[function(e,t,n){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,n){"use strict";var r=e("./$");t.exports=function(e){return function(t){var n,l=r.toObject(this),i=r.toLength(l.length),a=r.toIndex(arguments[1],i);if(e&&t!=t){for(;i>a;)if(n=l[a++],n!=n)return!0}else for(;i>a;a++)if((e||a in l)&&l[a]===t)return e||a;return!e&&-1}}},{"./$":223}],211:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.ctx");t.exports=function(e){var t=1==e,n=2==e,i=3==e,a=4==e,s=6==e,o=5==e||s;return function(u){for(var c,p,d=Object(r.assertDefined(this)),f=r.ES5Object(d),h=l(u,arguments[1],3),m=r.toLength(f.length),g=0,y=t?Array(m):n?[]:void 0;m>g;g++)if((o||g in f)&&(c=f[g],p=h(c,g,d),e))if(t)y[g]=p;else if(p)switch(e){case 3:return!0;case 5:return c;case 6:return g;case 2:y.push(c)}else if(a)return!1;return s?-1:i||a?a:y}}},{"./$":223,"./$.ctx":218}],212:[function(e,t,n){function r(e,t,n){if(!e)throw TypeError(n?t+n:t)}var l=e("./$");r.def=l.assertDefined,r.fn=function(e){if(!l.isFunction(e))throw TypeError(e+" is not a function!");return e},r.obj=function(e){if(!l.isObject(e))throw TypeError(e+" is not an object!");return e},r.inst=function(e,t,n){if(!(e instanceof t))throw TypeError(n+": use the 'new' operator!");return e},t.exports=r},{"./$":223}],213:[function(e,t,n){var r=e("./$");t.exports=Object.assign||function(e,t){for(var n=Object(r.assertDefined(e)),l=arguments.length,i=1;l>i;)for(var a,s=r.ES5Object(arguments[i++]),o=r.getKeys(s),u=o.length,c=0;u>c;)n[a=o[c++]]=s[a];return n}},{"./$":223}],214:[function(e,t,n){function r(e){return a.call(e).slice(8,-1)}var l=e("./$"),i=e("./$.wks")("toStringTag"),a={}.toString;r.classof=function(e){var t,n;return void 0==e?void 0===e?"Undefined":"Null":"string"==typeof(n=(t=Object(e))[i])?n:r(t)},r.set=function(e,t,n){e&&!l.has(e=n?e:e.prototype,i)&&l.hide(e,i,t)},t.exports=r},{"./$":223,"./$.wks":234}],215:[function(e,t,n){"use strict";function r(e,t){if(!d(e))return("string"==typeof e?"S":"P")+e;if(m(e))return"F";if(!c(e,g)){if(!t)return"E";f(e,g,++_)}return"O"+e[g]}function l(e,t){var n,l=r(t);if("F"!=l)return e[y][l];for(n=e[b];n;n=n.n)if(n.k==t)return n}var i=e("./$"),a=e("./$.ctx"),s=e("./$.uid").safe,o=e("./$.assert"),u=e("./$.iter"),c=i.has,p=i.set,d=i.isObject,f=i.hide,h=u.step,m=Object.isFrozen||i.core.Object.isFrozen,g=s("id"),y=s("O1"),v=s("last"),b=s("first"),x=s("iter"),E=i.DESC?s("size"):"size",_=0;t.exports={getConstructor:function(e,t,n){function r(l){var a=o.inst(this,r,e);p(a,y,i.create(null)),p(a,E,0),p(a,v,void 0),p(a,b,void 0),void 0!=l&&u.forOf(l,t,a[n],a)}return i.mix(r.prototype,{clear:function(){for(var e=this,t=e[y],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[v]=void 0,e[E]=0},"delete":function(e){var t=this,n=l(t,e);if(n){var r=n.n,i=n.p;delete t[y][n.i],n.r=!0,i&&(i.n=r),r&&(r.p=i),t[b]==n&&(t[b]=r),t[v]==n&&(t[v]=i),t[E]--}return!!n},forEach:function(e){for(var t,n=a(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!!l(this,e)}}),i.DESC&&i.setDesc(r.prototype,"size",{get:function(){return o.def(this[E])}}),r},def:function(e,t,n){var i,a,s=l(e,t);return s?s.v=n:(e[v]=s={i:a=r(t,!0),k:t,v:n,p:i=e[v],n:void 0,r:!1},e[b]||(e[b]=s),i&&(i.n=s),e[E]++,"F"!=a&&(e[y][a]=s)),e},getEntry:l,getIterConstructor:function(){return function(e,t){p(this,x,{o:e,k:t})}},next:function(){for(var e=this[x],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?h(0,n.k):"value"==t?h(0,n.v):h(0,[n.k,n.v]):(e.o=void 0,h(1))}}},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.iter":222,"./$.uid":232}],216:[function(e,t,n){"use strict";function r(e,t){return v.call(e.array,function(e){return e[0]===t})}function l(e){return e[g]||p(e,g,{array:[],get:function(e){var t=r(this,e);return t?t[1]:void 0},has:function(e){return!!r(this,e)},set:function(e,t){var n=r(this,e);n?n[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}})[g]}var i=e("./$"),a=e("./$.uid").safe,s=e("./$.assert"),o=e("./$.iter").forOf,u=i.has,c=i.isObject,p=i.hide,d=Object.isFrozen||i.core.Object.isFrozen,f=0,h=a("id"),m=a("weak"),g=a("leak"),y=e("./$.array-methods"),v=y(5),b=y(6);t.exports={getConstructor:function(e,t,n){function r(l){i.set(s.inst(this,r,e),h,f++),void 0!=l&&o(l,t,this[n],this)}return i.mix(r.prototype,{"delete":function(e){return c(e)?d(e)?l(this)["delete"](e):u(e,m)&&u(e[m],this[h])&&delete e[m][this[h]]:!1},has:function(e){return c(e)?d(e)?l(this).has(e):u(e,m)&&u(e[m],this[h]):!1}}),r},def:function(e,t,n){return d(s.obj(t))?l(e).set(t,n):(u(t,m)||p(t,m,{}),t[m][e[h]]=n),e},leakStore:l,WEAK:m,ID:h}},{"./$":223,"./$.array-methods":211,"./$.assert":212,"./$.iter":222,"./$.uid":232}],217:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.def"),i=e("./$.iter"),a=e("./$.assert").inst;t.exports=function(t,n,s,o,u){function c(e,t){var n=h[e];r.FW&&(h[e]=function(e,r){var l=n.call(this,0===e?0:e,r);return t?this:l})}var p=r.g[t],d=p,f=o?"set":"add",h=d&&d.prototype,m={};if(r.isFunction(d)&&(u||!i.BUGGY&&h.forEach&&h.entries)){var g,y=new d,v=y[f](u?{}:-0,1);(i.fail(function(e){new d(e)})||i.DANGER_CLOSING)&&(d=function(e){a(this,d,t);var n=new p;return void 0!=e&&i.forOf(e,o,n[f],n),n},d.prototype=h,r.FW&&(h.constructor=d)),u||y.forEach(function(e,t){g=1/t===-(1/0)}),g&&(c("delete"),c("has"),o&&c("get")),(g||v!==y)&&c(f,!0)}else d=s.getConstructor(t,o,f),r.mix(d.prototype,n);return e("./$.cof").set(d,t),e("./$.species")(d),m[t]=d,l(l.G+l.W+l.F*(d!=p),m),u||i.std(d,t,s.getIterConstructor(),s.next,o?"key+value":"value",!o,!0),d}},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.def":219,"./$.iter":222,"./$.species":229}],218:[function(e,t,n){var r=e("./$.assert").fn;t.exports=function(e,t,n){if(r(e),~n&&void 0===t)return e;switch(n){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,n){function r(e,t){return function(){return e.apply(t,arguments)}}function l(e,t,n){var u,c,p,d,f=e&l.G,h=f?a:e&l.S?a[t]:(a[t]||{}).prototype,m=f?s:s[t]||(s[t]={});f&&(n=t);for(u in n)c=!(e&l.F)&&h&&u in h,c&&u in m||(p=c?h[u]:n[u],f&&!o(h[u])?d=n[u]:e&l.B&&c?d=r(p,a):e&l.W&&h[u]==p?!function(e){d=function(t){return this instanceof e?new e(t):e(t)},d.prototype=e.prototype}(p):d=e&l.P&&o(p)?r(Function.call,p):p,i.hide(m,u,d))}var i=e("./$"),a=i.g,s=i.core,o=i.isFunction;l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,t.exports=l},{"./$":223}],220:[function(e,t,n){t.exports=function(e){return e.FW=!1,e.path=e.core,e}},{}],221:[function(e,t,n){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,n){"use strict";function r(e,t){o.hide(e,f,t),h in[]&&o.hide(e,h,t)}function l(e,t,n,l){var i=e.prototype,a=i[f]||i[h]||l&&i[l]||n;if(o.FW&&r(i,a),a!==n){var s=o.getProto(a.call(new e));c.set(s,t+" Iterator",!0),o.FW&&o.has(i,h)&&r(s,o.that)}return m[t]=a,m[t+" Iterator"]=o.that,a}function i(e){var t=o.g.Symbol,n=e[t&&t.iterator||h],r=n||e[f]||m[c.classof(e)];return d(r.call(e))}function a(e){var t=e["return"];void 0!==t&&d(t.call(e))}function s(e,t,n,r){try{return r?t(d(n)[0],n[1]):t(n)}catch(l){throw a(e),l}}var o=e("./$"),u=e("./$.ctx"),c=e("./$.cof"),p=e("./$.def"),d=e("./$.assert").obj,f=e("./$.wks")("iterator"),h="@@iterator",m={},g={},y="keys"in[]&&!("next"in[].keys());r(g,o.that);var v=!0;!function(){try{var e=[1].keys();e["return"]=function(){v=!1},Array.from(e,function(){throw 2})}catch(t){}}();var b=t.exports={BUGGY:y,DANGER_CLOSING:v,fail:function(e){var t=!0;try{var n=[[{},1]],r=n[f](),l=r.next;r.next=function(){return t=!1,l.call(this)},n[f]=function(){return r},e(n)}catch(i){}return t},Iterators:m,prototype:g,step:function(e,t){return{value:t,done:!!e}},stepCall:s,close:a,is:function(e){var t=Object(e),n=o.g.Symbol,r=n&&n.iterator||h;return r in t||f in t||o.has(m,c.classof(t))},get:i,set:r,create:function(e,t,n,r){e.prototype=o.create(r||b.prototype,{next:o.desc(1,n)}),c.set(e,t+" Iterator")},define:l,std:function(e,t,n,r,i,a,s){function u(e){return function(){return new n(this,e)}}b.create(n,t,r);var c,d,f=u("key+value"),h=u("value"),m=e.prototype;if("value"==i?h=l(e,t,h,"values"):f=l(e,t,f,"entries"),i&&(c={entries:f,keys:a?h:u("key"),values:h},p(p.P+p.F*y,t,c),s))for(d in c)d in m||o.hide(m,d,c[d])},forOf:function(e,t,n,r){for(var l,o=i(e),c=u(n,r,t?2:1);!(l=o.next()).done;)if(s(o,c,l.value,t)===!1)return a(o)}}},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.ctx":218,"./$.def":219,"./$.wks":234}],223:[function(e,t,n){"use strict";function r(e){return isNaN(e=+e)?0:(e>0?m:h)(e)}function l(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}function i(e,t,n){return e[t]=n,e}function a(e){return v?function(t,n,r){return x.setDesc(t,n,l(e,r))}:i}function s(e){return null!==e&&("object"==typeof e||"function"==typeof e)}function o(e){return"function"==typeof e}function u(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}var c="undefined"!=typeof self?self:Function("return this")(),p={},d=Object.defineProperty,f={}.hasOwnProperty,h=Math.ceil,m=Math.floor,g=Math.max,y=Math.min,v=!!function(){try{return 2==d({},"a",{get:function(){return 2}}).a}catch(e){}}(),b=a(1),x=t.exports=e("./$.fw")({g:c,core:p,html:c.document&&document.documentElement,isObject:s,isFunction:o,it:function(e){return e},that:function(){return this},toInteger:r,toLength:function(e){return e>0?y(r(e),9007199254740991):0},toIndex:function(e,t){return e=r(e),0>e?g(e+t,0):y(e,t)},has:function(e,t){return f.call(e,t)},create:Object.create,getProto:Object.getPrototypeOf,DESC:v,desc:l,getDesc:Object.getOwnPropertyDescriptor,setDesc:d,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:u,ES5Object:Object,toObject:function(e){return x.ES5Object(u(e))},hide:b,def:a(0),set:c.Symbol?i: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=c)},{"./$.fw":220}],224:[function(e,t,n){var r=e("./$");t.exports=function(e,t){for(var n,l=r.toObject(e),i=r.getKeys(l),a=i.length,s=0;a>s;)if(l[n=i[s++]]===t)return n}},{"./$":223}],225:[function(e,t,n){var r=e("./$"),l=e("./$.assert").obj;t.exports=function(e){return l(e),r.getSymbols?r.getNames(e).concat(r.getSymbols(e)):r.getNames(e)}},{"./$":223,"./$.assert":212}],226:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.invoke"),i=e("./$.assert").fn;t.exports=function(){for(var e=i(this),t=arguments.length,n=Array(t),a=0,s=r.path._,o=!1;t>a;)(n[a]=arguments[a++])===s&&(o=!0);return function(){var r,i=this,a=arguments.length,u=0,c=0;if(!o&&!a)return l(e,n,i);if(r=n.slice(),o)for(;t>u;u++)r[u]===s&&(r[u]=arguments[c++]);for(;a>c;)r.push(arguments[c++]);return l(e,r,i)}}},{"./$":223,"./$.assert":212,"./$.invoke":221}],227:[function(e,t,n){"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,n){var r=e("./$"),l=e("./$.assert");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(t,n){try{n=e("./$.ctx")(Function.call,r.getDesc(Object.prototype,"__proto__").set,2),n({},[])}catch(i){t=!0}return function(e,i){return l.obj(e),l(null===i||r.isObject(i),i,": can't set as prototype!"),t?e.__proto__=i:n(e,i),e}}():void 0)},{"./$":223,"./$.assert":212,"./$.ctx":218}],229:[function(e,t,n){var r=e("./$");t.exports=function(t){r.DESC&&r.FW&&r.setDesc(t,e("./$.wks")("species"),{configurable:!0,get:r.that})}},{"./$":223,"./$.wks":234}],230:[function(e,t,n){"use strict";var r=e("./$");t.exports=function(e){return function(t){var n,l,i=String(r.assertDefined(this)),a=r.toInteger(t),s=i.length;return 0>a||a>=s?e?"":void 0:(n=i.charCodeAt(a),55296>n||n>56319||a+1===s||(l=i.charCodeAt(a+1))<56320||l>57343?e?i.charAt(a):n:e?i.slice(a,a+2):(n-55296<<10)+(l-56320)+65536)}}},{"./$":223}],231:[function(e,t,n){"use strict";function r(){var e=+this;if(o.has(x,e)){var t=x[e];delete x[e],t()}}function l(e){r.call(e.data)}var i,a,s,o=e("./$"),u=e("./$.ctx"),c=e("./$.cof"),p=e("./$.invoke"),d=o.g,f=o.isFunction,h=d.setImmediate,m=d.clearImmediate,g=d.postMessage,y=d.addEventListener,v=d.MessageChannel,b=0,x={},E="onreadystatechange";f(h)&&f(m)||(h=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return x[++b]=function(){p(f(e)?e:Function(e),t)},i(b),b},m=function(e){delete x[e]},"process"==c(d.process)?i=function(e){d.process.nextTick(u(r,e,1))}:y&&f(g)&&!o.g.importScripts?(i=function(e){g(e,"*")},y("message",l,!1)):f(v)?(a=new v,s=a.port2,a.port1.onmessage=l,i=u(s.postMessage,s,1)):i=o.g.document&&E in document.createElement("script")?function(e){o.html.appendChild(document.createElement("script"))[E]=function(){o.html.removeChild(this),r.call(e)}}:function(e){setTimeout(u(r,e,1),0)}),t.exports={set:h,clear:m}},{"./$":223,"./$.cof":214,"./$.ctx":218,"./$.invoke":221}],232:[function(e,t,n){function r(e){return"Symbol("+e+")_"+(++l+Math.random()).toString(36)}var l=0;r.safe=e("./$").g.Symbol||r,t.exports=r},{"./$":223}],233:[function(e,t,n){var r=e("./$"),l=e("./$.wks")("unscopables");!r.FW||l in[]||r.hide(Array.prototype,l,{}),t.exports=function(e){r.FW&&([][l][e]=!0)}},{"./$":223,"./$.wks":234}],234:[function(e,t,n){var r=e("./$").g,l={};t.exports=function(t){return l[t]||(l[t]=r.Symbol&&r.Symbol[t]||e("./$.uid").safe("Symbol."+t))}},{"./$":223,"./$.uid":232}],235:[function(e,t,n){"use strict";function r(e,t){return this instanceof r?(this[d]=m(e),void(this[c]=!!t)):new r(e,t)}function l(e){function t(e,t,n){this[d]=m(e),this[c]=e[c],this[p]=a(t,n,e[c]?2:1)}return y(t,"Chain",e,v),g(t.prototype,i.that),t}var i=e("./$"),a=e("./$.ctx"),s=e("./$.uid").safe,o=e("./$.def"),u=e("./$.iter"),c=s("entries"),p=s("fn"),d=s("iter"),f=u.forOf,h=u.stepCall,m=u.get,g=u.set,y=u.create;y(r,"Wrapper",function(){return this[d].next()});var v=r.prototype;g(v,function(){return this[d]});var b=l(function(){var e=this[d].next();return e.done?e:u.step(0,h(this[d],this[p],e.value,this[c]))}),x=l(function(){for(;;){var e=this[d].next();if(e.done||h(this[d],this[p],e.value,this[c]))return e}});i.mix(v,{of:function(e,t){f(this,this[c],e,t)},array:function(e,t){var n=[];return f(void 0!=e?this.map(e,t):this,!1,n.push,n),n},filter:function(e,t){return new x(this,e,t)},map:function(e,t){return new b(this,e,t)}}),r.isIterable=u.is,r.getIterator=m,o(o.G+o.F,{$for:r})},{"./$":223,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.uid":232}],236:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.def"),i=e("./$.assert").fn;l(l.P+l.F,"Array",{turn:function(e,t){i(e);for(var n=void 0==t?[]:Object(t),l=r.ES5Object(this),a=r.toLength(l.length),s=0;a>s&&e(n,l[s],s++,this)!==!1;);return n}}),e("./$.unscope")("turn")},{"./$":223,"./$.assert":212,"./$.def":219,"./$.unscope":233}],237:[function(e,t,n){"use strict";function r(e){var t=this,n={};return o(t,c,function(e){return void 0!==e&&e in t?l.has(n,e)?n[e]:n[e]=i(t[e],t,-1):p.call(t)})[c](e)}var l=e("./$"),i=e("./$.ctx"),a=e("./$.def"),s=e("./$.invoke"),o=l.hide,u=e("./$.assert").fn,c=l.DESC?e("./$.uid")("tie"):"toLocaleString",p={}.toLocaleString;l.core._=l.path._=l.path._||{},a(a.P+a.F,"Function",{part:e("./$.partial"),only:function(e,t){var n=u(this),r=l.toLength(e),i=arguments.length>1;return function(){for(var e=Math.min(r,arguments.length),l=Array(e),a=0;e>a;)l[a]=arguments[a++];return s(n,l,i?t:this)}}}),o(l.path._,"toString",function(){return c}),o(Object.prototype,c,r),l.DESC||o(Array.prototype,c,r)},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.def":219,"./$.invoke":221,"./$.partial":226,"./$.uid":232}],238:[function(e,t,n){function r(e){return e>9?e:"0"+e}function l(e){return function(t,n){function l(t){return i[e+t]()}var i=this,s=p[a.has(p,n)?n:d];return String(t).replace(u,function(e){switch(e){case"s":return l(f);case"ss":return r(l(f));case"m":return l(h);case"mm":return r(l(h));case"h":return l(m);case"hh":return r(l(m));case"D":return l(g);case"DD":return r(l(g));case"W":return s[0][l("Day")];case"N":return l(y)+1;case"NN":return r(l(y)+1);case"M":return s[2][l(y)];case"MM":return s[1][l(y)];case"Y":return l(v);case"YY":return r(l(v)%100)}return e})}}function i(e,t){function n(e){var n=[];return a.each.call(t.months.split(","),function(t){n.push(t.replace(c,"$"+e))}),n}return p[e]=[t.weekdays.split(","),n(1),n(2)],o}var a=e("./$"),s=e("./$.def"),o=a.core,u=/\b\w\w?\b/g,c=/:(.*)\|(.*)$/,p={},d="en",f="Seconds",h="Minutes",m="Hours",g="Date",y="Month",v="FullYear";s(s.P+s.F,g,{format:l("get"),formatUTC:l("getUTC")}),i(d,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"}),i("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"}),o.locale=function(e){return a.has(p,e)?d=e:d},o.addLocale=i},{"./$":223,"./$.def":219}],239:[function(e,t,n){var r=e("./$"),l=e("./$.def"),i=e("./$.partial");l(l.G+l.F,{delay:function(e){return new(r.core.Promise||r.g.Promise)(function(t){setTimeout(i.call(t,!0),e)})}})},{"./$":223,"./$.def":219,"./$.partial":226}],240:[function(e,t,n){function r(e){var t=u.create(null);return void 0!=e&&(g.is(e)?g.forOf(e,!0,function(e,n){t[e]=n}):d(t,e)),t}function l(e,t){u.set(this,h,{o:b(e),a:v(e),i:0,k:t})}function i(e){return function(t){return new l(t,e)}}function a(e,t){return"function"==typeof e?e:t}function s(e){ var t=1==e,n=4==e;return function(l,i,s){var o,u,p,d=c(i,s,3),f=b(l),h=t||7==e||2==e?new(a(this,r)):void 0;for(o in f)if(x(f,o)&&(u=f[o],p=d(u,o,l),e))if(t)h[o]=p;else if(p)switch(e){case 2:h[o]=u;break;case 3:return!0;case 5:return u;case 6:return o;case 7:h[p[0]]=p[1]}else if(n)return!1;return 3==e||n?n:h}}function o(e){return function(t,n,l){m.fn(n);var i,s,o,u=b(t),c=v(u),p=c.length,d=0;for(e?i=void 0==l?new(a(this,r)):Object(l):arguments.length<3?(m(p,"Reduce of empty object with no initial value"),i=u[c[d++]]):i=Object(l);p>d;)if(x(u,s=c[d++]))if(o=n(i,u[s],s,t),e){if(o===!1)break}else i=o;return i}}var u=e("./$"),c=e("./$.ctx"),p=e("./$.def"),d=e("./$.assign"),f=e("./$.keyof"),h=e("./$.uid").safe("iter"),m=e("./$.assert"),g=e("./$.iter"),y=g.step,v=u.getKeys,b=u.toObject,x=u.has;r.prototype=null,g.create(l,"Dict",function(){var e,t=this[h],n=t.o,r=t.a,l=t.k;do if(t.i>=r.length)return t.o=void 0,y(1);while(!x(n,e=r[t.i++]));return"key"==l?y(0,e):"value"==l?y(0,n[e]):y(0,[e,n[e]])});var E=s(6);p(p.G+p.F,{Dict:u.mix(r,{keys:i("key"),values:i("value"),entries:i("key+value"),forEach:s(0),map:s(1),filter:s(2),some:s(3),every:s(4),find:s(5),findKey:E,mapPairs:s(7),reduce:o(!1),turn:o(!0),keyOf:f,includes:function(e,t){return void 0!==(t==t?f(e,t):E(e,function(e){return e!=e}))},has:x,get:function(e,t){return x(e,t)?e[t]:void 0},set:u.def,isDict:function(e){return u.isObject(e)&&u.getProto(e)===r.prototype}})})},{"./$":223,"./$.assert":212,"./$.assign":213,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.keyof":224,"./$.uid":232}],241:[function(e,t,n){var r=e("./$.def");r(r.G+r.F,{global:e("./$").g})},{"./$":223,"./$.def":219}],242:[function(e,t,n){var r=e("./$").core,l=e("./$.iter");r.isIterable=l.is,r.getIterator=l.get},{"./$":223,"./$.iter":222}],243:[function(e,t,n){var r=e("./$"),l=e("./$.def"),i={},a=!0;r.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){i[e]=function(){return a&&r.g.console&&r.isFunction(console[e])?Function.apply.call(console[e],console,arguments):void 0}}),l(l.G+l.F,{log:e("./$.assign")(i.log,i,{enable:function(){a=!0},disable:function(){a=!1}})})},{"./$":223,"./$.assign":213,"./$.def":219}],244:[function(e,t,n){"use strict";function r(e){l.set(this,i,{l:l.toLength(e),i:0})}var l=e("./$"),i=e("./$.uid").safe("iter"),a=e("./$.iter"),s=a.step,o="Number";a.create(r,o,function(){var e=this[i],t=e.i++;return t<e.l?s(0,t):s(1)}),a.define(Number,o,function(){return new r(this)})},{"./$":223,"./$.iter":222,"./$.uid":232}],245:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.def"),i=e("./$.invoke"),a={};a.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},r.FW&&r.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&&(a[e]=function(){for(var e=[+this],n=0;arguments.length>n;)e.push(arguments[n++]);return i(t,e)})}),l(l.P+l.F,"Number",a)},{"./$":223,"./$.def":219,"./$.invoke":221}],246:[function(e,t,n){function r(e,t){for(var n,r=a(l.toObject(t)),i=r.length,s=0;i>s;)l.setDesc(e,n=r[s++],l.getDesc(t,n));return e}var l=e("./$"),i=e("./$.def"),a=e("./$.own-keys");i(i.S+i.F,"Object",{isObject:l.isObject,classof:e("./$.cof").classof,define:r,make:function(e,t){return r(l.create(e),t)}})},{"./$":223,"./$.cof":214,"./$.def":219,"./$.own-keys":225}],247:[function(e,t,n){var r,l=e("./$.def"),i=e("./$.replacer"),a={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"},s={};for(r in a)s[a[r]]=r;l(l.P+l.F,"String",{escapeHTML:i(/[&<>"']/g,a),unescapeHTML:i(/&(?:amp|lt|gt|quot|apos);/g,s)})},{"./$.def":219,"./$.replacer":227}],248:[function(e,t,n){function r(e,t){return function(n){var r,l=T(n),i=0,a=[];for(r in l)r!=h&&w(l,r)&&a.push(r);for(;t>i;)w(l,r=e[i++])&&(~x.call(a,r)||a.push(r));return a}}function l(e){return!u.isObject(e)}function i(){}function a(e){return function(){return e.apply(u.ES5Object(this),arguments)}}function s(e){return function(t,n){m.fn(t);var r=T(this),l=C(r.length),i=e?l-1:0,a=e?-1:1;if(arguments.length<2)for(;;){if(i in r){n=r[i],i+=a;break}i+=a,m(e?i>=0:l>i,"Reduce of empty array with no initial value")}for(;e?i>=0:l>i;i+=a)i in r&&(n=t(n,r[i],i,this));return n}}function o(e){return e>9?e:"0"+e}var u=e("./$"),c=e("./$.cof"),p=e("./$.def"),d=e("./$.invoke"),f=e("./$.array-methods"),h=e("./$.uid").safe("__proto__"),m=e("./$.assert"),g=m.obj,y=Object.prototype,v=[],b=v.slice,x=v.indexOf,E=c.classof,_=Object.defineProperties,w=u.has,S=u.setDesc,I=u.getDesc,k=u.isFunction,T=u.toObject,C=u.toLength,j=!1;if(!u.DESC){try{j=8==S(document.createElement("div"),"x",{get:function(){return 8}}).x}catch(M){}u.setDesc=function(e,t,n){if(j)try{return S(e,t,n)}catch(r){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(g(e)[t]=n.value),e},u.getDesc=function(e,t){if(j)try{return I(e,t)}catch(n){}return w(e,t)?u.desc(!y.propertyIsEnumerable.call(e,t),e[t]):void 0},_=function(e,t){g(e);for(var n,r=u.getKeys(t),l=r.length,i=0;l>i;)u.setDesc(e,n=r[i++],t[n]);return e}}p(p.S+p.F*!u.DESC,"Object",{getOwnPropertyDescriptor:u.getDesc,defineProperty:u.setDesc,defineProperties:_});var A="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),O=A.concat("length","prototype"),L=A.length,P=function(){var e,t=document.createElement("iframe"),n=L;for(t.style.display="none",u.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[A[n]];return P()};p(p.S,"Object",{getPrototypeOf:u.getProto=u.getProto||function(e){return e=Object(m.def(e)),w(e,h)?e[h]:k(e.constructor)&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?y:null},getOwnPropertyNames:u.getNames=u.getNames||r(O,O.length,!0),create:u.create=u.create||function(e,t){var n;return null!==e?(i.prototype=g(e),n=new i,i.prototype=null,n[h]=e):n=P(),void 0===t?n:_(n,t)},keys:u.getKeys=u.getKeys||r(A,L,!1),seal:u.it,freeze:u.it,preventExtensions:u.it,isSealed:l,isFrozen:l,isExtensible:u.isObject}),p(p.P,"Function",{bind:function(e){function t(){var l=r.concat(b.call(arguments));return d(n,l,this instanceof t?u.create(n.prototype):e)}var n=m.fn(this),r=b.call(arguments,1);return n.prototype&&(t.prototype=n.prototype),t}}),0 in Object("z")&&"z"=="z"[0]||(u.ES5Object=function(e){return"String"==c(e)?e.split(""):Object(e)}),p(p.P+p.F*(u.ES5Object!=Object),"Array",{slice:a(b),join:a(v.join)}),p(p.S,"Array",{isArray:function(e){return"Array"==c(e)}}),p(p.P,"Array",{forEach:u.each=u.each||f(0),map:f(1),filter:f(2),some:f(3),every:f(4),reduce:s(!1),reduceRight:s(!0),indexOf:x=x||e("./$.array-includes")(!1),lastIndexOf:function(e,t){var n=T(this),r=C(n.length),l=r-1;for(arguments.length>1&&(l=Math.min(l,u.toInteger(t))),0>l&&(l=C(r+l));l>=0;l--)if(l in n&&n[l]===e)return l;return-1}}),p(p.P,"String",{trim:e("./$.replacer")(/^\s*([\s\S]*\S)?\s*$/,"$1")}),p(p.S,"Date",{now:function(){return+new Date}}),p(p.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)+"-"+o(e.getUTCMonth()+1)+"-"+o(e.getUTCDate())+"T"+o(e.getUTCHours())+":"+o(e.getUTCMinutes())+":"+o(e.getUTCSeconds())+"."+(n>99?n:"0"+o(n))+"Z"}}),"Object"==E(function(){return arguments}())&&(c.classof=function(e){var t=E(e);return"Object"==t&&k(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,t,n){"use strict";var r=e("./$"),l=e("./$.def"),i=r.toIndex;l(l.P,"Array",{copyWithin:function(e,t){var n=Object(r.assertDefined(this)),l=r.toLength(n.length),a=i(e,l),s=i(t,l),o=arguments[2],u=void 0===o?l:i(o,l),c=Math.min(u-s,l-a),p=1;for(a>s&&s+c>a&&(p=-1,s=s+c-1,a=a+c-1);c-->0;)s in n?n[a]=n[s]:delete n[a],a+=p,s+=p;return n}}),e("./$.unscope")("copyWithin")},{"./$":223,"./$.def":219,"./$.unscope":233}],250:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.def"),i=r.toIndex;l(l.P,"Array",{fill:function(e){for(var t=Object(r.assertDefined(this)),n=r.toLength(t.length),l=i(arguments[1],n),a=arguments[2],s=void 0===a?n:i(a,n);s>l;)t[l++]=e;return t}}),e("./$.unscope")("fill")},{"./$":223,"./$.def":219,"./$.unscope":233}],251:[function(e,t,n){var r=e("./$.def");r(r.P,"Array",{findIndex:e("./$.array-methods")(6)}),e("./$.unscope")("findIndex")},{"./$.array-methods":211,"./$.def":219,"./$.unscope":233}],252:[function(e,t,n){var r=e("./$.def");r(r.P,"Array",{find:e("./$.array-methods")(5)}),e("./$.unscope")("find")},{"./$.array-methods":211,"./$.def":219,"./$.unscope":233}],253:[function(e,t,n){var r=e("./$"),l=e("./$.ctx"),i=e("./$.def"),a=e("./$.iter"),s=a.stepCall;i(i.S+i.F*a.DANGER_CLOSING,"Array",{from:function(e){var t,n,i,o,u=Object(r.assertDefined(e)),c=arguments[1],p=void 0!==c,d=p?l(c,arguments[2],2):void 0,f=0;if(a.is(u))for(o=a.get(u),n=new("function"==typeof this?this:Array);!(i=o.next()).done;f++)n[f]=p?s(o,d,[i.value,f],!0):i.value;else for(n=new("function"==typeof this?this:Array)(t=r.toLength(u.length));t>f;f++)n[f]=p?d(u[f],f):u[f];return n.length=f,n}})},{"./$":223,"./$.ctx":218,"./$.def":219,"./$.iter":222}],254:[function(e,t,n){var r=e("./$"),l=e("./$.unscope"),i=e("./$.uid").safe("iter"),a=e("./$.iter"),s=a.step,o=a.Iterators;a.std(Array,"Array",function(e,t){r.set(this,i,{o:r.toObject(e),i:0,k:t})},function(){var e=this[i],t=e.o,n=e.k,r=e.i++;return!t||r>=t.length?(e.o=void 0,s(1)):"key"==n?s(0,r):"value"==n?s(0,t[r]):s(0,[r,t[r]])},"value"),o.Arguments=o.Array,l("keys"),l("values"),l("entries")},{"./$":223,"./$.iter":222,"./$.uid":232,"./$.unscope":233}],255:[function(e,t,n){var r=e("./$.def");r(r.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,t,n){e("./$.species")(Array)},{"./$.species":229}],257:[function(e,t,n){"use strict";var r=e("./$"),l="name",i=r.setDesc,a=Function.prototype;l in a||r.FW&&r.DESC&&i(a,l,{configurable:!0,get:function(){var e=String(this).match(/^\s*function ([^ (]*)/),t=e?e[1]:"";return r.has(this,l)||i(this,l,r.desc(5,t)),t},set:function(e){r.has(this,l)||i(this,l,r.desc(0,e))}})},{"./$":223}],258:[function(e,t,n){"use strict";var r=e("./$.collection-strong");e("./$.collection")("Map",{get:function(e){var t=r.getEntry(this,e);return t&&t.v},set:function(e,t){return r.def(this,0===e?0:e,t)}},r,!0)},{"./$.collection":217,"./$.collection-strong":215}],259:[function(e,t,n){function r(e){return isFinite(e=+e)&&0!=e?0>e?-r(-e):p(e+d(e*e+1)):e}function l(e){return 0==(e=+e)?e:e>-1e-6&&1e-6>e?e+e*e/2:c(e)-1}var i=1/0,a=e("./$.def"),s=Math.E,o=Math.pow,u=Math.abs,c=Math.exp,p=Math.log,d=Math.sqrt,f=Math.ceil,h=Math.floor,m=Math.sign||function(e){return 0==(e=+e)||e!=e?e:0>e?-1:1};a(a.S,"Math",{acosh:function(e){return(e=+e)<1?0/0:isFinite(e)?p(e/s+d(e+1)*d(e-1)/s)+1:e},asinh:r,atanh:function(e){return 0==(e=+e)?e:p((1+e)/(1-e))/2},cbrt:function(e){return m(e=+e)*o(u(e),1/3)},clz32:function(e){return(e>>>=0)?32-e.toString(2).length:32},cosh:function(e){return(c(e=+e)+c(-e))/2},expm1:l,fround:function(e){return new Float32Array([e])[0]},hypot:function(e,t){for(var n,r=0,l=arguments.length,a=l,s=Array(l),u=-i;l--;){if(n=s[l]=+arguments[l],n==i||n==-i)return i;n>u&&(u=n)}for(u=n||1;a--;)r+=o(s[a]/u,2);return u*d(r)},imul:function(e,t){var n=65535,r=+e,l=+t,i=n&r,a=n&l;return 0|i*a+((n&r>>>16)*a+i*(n&l>>>16)<<16>>>0)},log1p:function(e){return(e=+e)>-1e-8&&1e-8>e?e-e*e/2:p(1+e)},log10:function(e){return p(e)/Math.LN10},log2:function(e){return p(e)/Math.LN2},sign:m,sinh:function(e){return u(e=+e)<1?(l(e)-l(-e))/2:(c(e-1)-c(-e-1))*(s/2)},tanh:function(e){var t=l(e=+e),n=l(-e);return t==i?1:n==i?-1:(t-n)/(c(e)+c(-e))},trunc:function(e){return(e>0?h:f)(e)}})},{"./$.def":219}],260:[function(e,t,n){"use strict";function r(e){var t,n;if(s(t=e.valueOf)&&!a(n=t.call(e)))return n;if(s(t=e.toString)&&!a(n=t.call(e)))return n;throw TypeError("Can't convert object to number")}function l(e){if(a(e)&&(e=r(e)),"string"==typeof e&&e.length>2&&48==e.charCodeAt(0)){var t=!1;switch(e.charCodeAt(1)){case 66:case 98:t=!0;case 79:case 111:return parseInt(e.slice(2),t?2:8)}}return+e}var i=e("./$"),a=i.isObject,s=i.isFunction,o="Number",u=i.g[o],c=u,p=u.prototype;!i.FW||u("0o1")&&u("0b1")||(u=function d(e){return this instanceof d?new c(l(e)):l(e)},i.each.call(i.DESC?i.getNames(c):"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){i.has(c,e)&&!i.has(u,e)&&i.setDesc(u,e,i.getDesc(c,e))}),u.prototype=p,p.constructor=u,i.hide(i.g,o,u))},{"./$":223}],261:[function(e,t,n){function r(e){return!l.isObject(e)&&isFinite(e)&&s(e)===e}var l=e("./$"),i=e("./$.def"),a=Math.abs,s=Math.floor,o=9007199254740991;i(i.S,"Number",{EPSILON:Math.pow(2,-52),isFinite:function(e){return"number"==typeof e&&isFinite(e)},isInteger:r,isNaN:function(e){return e!=e},isSafeInteger:function(e){return r(e)&&a(e)<=o},MAX_SAFE_INTEGER:o,MIN_SAFE_INTEGER:-o,parseFloat:parseFloat,parseInt:parseInt})},{"./$":223,"./$.def":219}],262:[function(e,t,n){var r=e("./$.def");r(r.S,"Object",{assign:e("./$.assign")})},{"./$.assign":213,"./$.def":219}],263:[function(e,t,n){var r=e("./$.def");r(r.S,"Object",{is:function(e,t){return e===t?0!==e||1/e===1/t:e!=e&&t!=t}})},{"./$.def":219}],264:[function(e,t,n){var r=e("./$.def");r(r.S,"Object",{setPrototypeOf:e("./$.set-proto")})},{"./$.def":219,"./$.set-proto":228}],265:[function(e,t,n){function r(e,t){var n=(l.core.Object||{})[e]||Object[e],r=0,o={};o[e]=1==t?function(e){return a(e)?n(e):e}:2==t?function(e){return a(e)?n(e):!0}:3==t?function(e){return a(e)?n(e):!1}:4==t?function(e,t){return n(s(e),t)}:5==t?function(e){return n(Object(l.assertDefined(e)))}:function(e){return n(s(e))};try{n("z")}catch(u){r=1}i(i.S+i.F*r,"Object",o)}var l=e("./$"),i=e("./$.def"),a=l.isObject,s=l.toObject;r("freeze",1),r("seal",1),r("preventExtensions",1),r("isFrozen",2),r("isSealed",2),r("isExtensible",3),r("getOwnPropertyDescriptor",4),r("getPrototypeOf",5),r("keys"),r("getOwnPropertyNames")},{"./$":223,"./$.def":219}],266:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.cof"),i={};i[e("./$.wks")("toStringTag")]="z",r.FW&&"z"!=l(i)&&r.hide(Object.prototype,"toString",function(){return"[object "+l.classof(this)+"]"})},{"./$":223,"./$.cof":214,"./$.wks":234}],267:[function(e,t,n){"use strict";function r(e){var t=w(e)[p];return void 0!=t?t:e}var l,i=e("./$"),a=e("./$.ctx"),s=e("./$.cof"),o=e("./$.def"),u=e("./$.assert"),c=e("./$.iter"),p=e("./$.wks")("species"),d=e("./$.uid").safe("record"),f=c.forOf,h="Promise",m=i.g,g=m.process,y=g&&g.nextTick||e("./$.task").set,v=m[h],b=v,x=i.isFunction,E=i.isObject,_=u.fn,w=u.obj;x(v)&&x(v.resolve)&&v.resolve(l=new v(function(){}))==l||function(){function e(e){var t;return E(e)&&(t=e.then),x(t)?t:!1}function t(e){var n,r=e[d],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)&&y(function(){var i=n.p,a=n.v,o=1==n.s,u=0;if(r&&!t(i))setTimeout(function(){t(i)||("process"==s(g)?g.emit("unhandledRejection",a,i):m.console&&x(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(h+"-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 r(e){var t=this;t.d||(t.d=!0,t=t.r||t,t.v=e,t.s=2,n(t,!0))}function l(t){var i,s,o=this;if(!o.d){o.d=!0,o=o.r||o;try{(i=e(t))?(s={r:o,d:!1},i.call(t,a(l,s,1),a(r,s,1))):(o.v=t,o.s=1,n(o))}catch(u){r.call(s||{r:o,d:!1},u)}}}v=function(e){_(e);var t={p:u.inst(this,v,h),c:[],s:0,d:!1,v:void 0,h:!1};i.hide(this,d,t);try{e(a(l,t,1),a(r,t,1))}catch(n){r.call(t,n)}},i.mix(v.prototype,{then:function(e,t){var r=w(w(this).constructor)[p],l={ok:x(e)?e:!0,fail:x(t)?t:!1},i=l.P=new(void 0!=r?r:v)(function(e,t){l.res=_(e),l.rej=_(t)}),a=this[d];return a.c.push(l),a.s&&n(a),i},"catch":function(e){return this.then(void 0,e)}})}(),o(o.G+o.W+o.F*(v!=b),{Promise:v}),o(o.S,h,{reject:function(e){return new(r(this))(function(t,n){n(e)})},resolve:function(e){return E(e)&&d in e&&i.getProto(e)===this.prototype?e:new(r(this))(function(t){t(e)})}}),o(o.S+o.F*(c.fail(function(e){v.all(e)["catch"](function(){})})||c.DANGER_CLOSING),h,{all:function(e){var t=r(this),n=[];return new t(function(r,l){f(e,!1,n.push,n);var a=n.length,s=Array(a);a?i.each.call(n,function(e,n){t.resolve(e).then(function(e){s[n]=e,--a||r(s)},l)}):r(s)})},race:function(e){var t=r(this);return new t(function(n,r){f(e,!1,function(e){t.resolve(e).then(n,r)})})}}),s.set(v,h),e("./$.species")(v)},{"./$":223,"./$.assert":212,"./$.cof":214,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.species":229,"./$.task":231,"./$.uid":232,"./$.wks":234}],268:[function(e,t,n){function r(e){var t,n=[];for(t in e)n.push(t);s.set(this,p,{o:e,a:n,i:0})}function l(e){return function(t){b(t);try{return e.apply(void 0,arguments),!0}catch(n){return!1}}}function i(e,t){var n,r=arguments.length<3?e:arguments[2],l=m(b(e),t);return l?s.has(l,"value")?l.value:void 0===l.get?void 0:l.get.call(r):h(n=y(e))?i(n,t,r):void 0}function a(e,t,n){var r,l,i=arguments.length<4?e:arguments[3],o=m(b(e),t);if(!o){if(h(l=y(e)))return a(l,t,n,i);o=s.desc(0)}return s.has(o,"value")?o.writable!==!1&&h(i)?(r=m(i,t)||s.desc(0),r.value=n,g(i,t,r),!0):!1:void 0===o.set?!1:(o.set.call(i,n),!0)}var s=e("./$"),o=e("./$.def"),u=e("./$.set-proto"),c=e("./$.iter"),p=e("./$.uid").safe("iter"),d=c.step,f=e("./$.assert"),h=s.isObject,m=s.getDesc,g=s.setDesc,y=s.getProto,v=Function.apply,b=f.obj,x=Object.isExtensible||s.it;c.create(r,"Object",function(){var e,t=this[p],n=t.a;do if(t.i>=n.length)return d(1);while(!((e=n[t.i++])in t.o));return d(0,e)});var E={apply:e("./$.ctx")(Function.call,v,3),construct:function(e,t){var n=f.fn(arguments.length<3?e:arguments[2]).prototype,r=s.create(h(n)?n:Object.prototype),l=v.call(e,r,t);return h(l)?l:r},defineProperty:l(g),deleteProperty:function(e,t){var n=m(b(e),t);return n&&!n.configurable?!1:delete e[t]},enumerate:function(e){return new r(b(e))},get:i,getOwnPropertyDescriptor:function(e,t){return m(b(e),t)},getPrototypeOf:function(e){return y(b(e))},has:function(e,t){return t in e},isExtensible:function(e){return!!x(b(e))},ownKeys:e("./$.own-keys"),preventExtensions:l(Object.preventExtensions||s.it),set:a};u&&(E.setPrototypeOf=function(e,t){return u(b(e),t),!0}),o(o.G,{Reflect:{}}),o(o.S,"Reflect",E)},{"./$":223,"./$.assert":212,"./$.ctx":218,"./$.def":219,"./$.iter":222,"./$.own-keys":225,"./$.set-proto":228,"./$.uid":232}],269:[function(e,t,n){var r=e("./$"),l=e("./$.cof"),i=r.g.RegExp,a=i,s=i.prototype;r.FW&&r.DESC&&(function(){try{return"/a/i"==i(/a/g,"i")}catch(e){}}()||(i=function(e,t){return new a("RegExp"==l(e)&&void 0!==t?e.source:e,t)},r.each.call(r.getNames(a),function(e){e in i||r.setDesc(i,e,{configurable:!0,get:function(){return a[e]},set:function(t){a[e]=t}})}),s.constructor=i,i.prototype=s,r.hide(r.g,"RegExp",i)),"g"!=/./g.flags&&r.setDesc(s,"flags",{configurable:!0,get:e("./$.replacer")(/^.*\/(\w*)$/,"$1")})),e("./$.species")(i)},{"./$":223,"./$.cof":214,"./$.replacer":227,"./$.species":229}],270:[function(e,t,n){"use strict";var r=e("./$.collection-strong");e("./$.collection")("Set",{add:function(e){return r.def(this,e=0===e?0:e,e)}},r)},{"./$.collection":217,"./$.collection-strong":215}],271:[function(e,t,n){var r=e("./$.def");r(r.P,"String",{codePointAt:e("./$.string-at")(!1)})},{"./$.def":219,"./$.string-at":230}],272:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.cof"),i=e("./$.def"),a=r.toLength;i(i.P,"String",{endsWith:function(e){if("RegExp"==l(e))throw TypeError();var t=String(r.assertDefined(this)),n=arguments[1],i=a(t.length),s=void 0===n?i:Math.min(a(n),i);return e+="",t.slice(s-e.length,s)===e}})},{"./$":223,"./$.cof":214,"./$.def":219}],273:[function(e,t,n){var r=e("./$.def"),l=e("./$").toIndex,i=String.fromCharCode;r(r.S,"String",{fromCodePoint:function(e){for(var t,n=[],r=arguments.length,a=0;r>a;){if(t=+arguments[a++],l(t,1114111)!==t)throw RangeError(t+" is not a valid code point");n.push(65536>t?i(t):i(((t-=65536)>>10)+55296,t%1024+56320))}return n.join("")}})},{"./$":223,"./$.def":219}],274:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.cof"),i=e("./$.def");i(i.P,"String",{includes:function(e){if("RegExp"==l(e))throw TypeError();return!!~String(r.assertDefined(this)).indexOf(e,arguments[1])}})},{"./$":223,"./$.cof":214,"./$.def":219}],275:[function(e,t,n){var r=e("./$").set,l=e("./$.string-at")(!0),i=e("./$.uid").safe("iter"),a=e("./$.iter"),s=a.step;a.std(String,"String",function(e){r(this,i,{o:String(e),i:0})},function(){var e,t=this[i],n=t.o,r=t.i;return r>=n.length?s(1):(e=l.call(n,r),t.i+=e.length,s(0,e))})},{"./$":223,"./$.iter":222,"./$.string-at":230,"./$.uid":232}],276:[function(e,t,n){var r=e("./$"),l=e("./$.def");l(l.S,"String",{raw:function(e){for(var t=r.toObject(e.raw),n=r.toLength(t.length),l=arguments.length,i=[],a=0;n>a;)i.push(String(t[a++])),l>a&&i.push(String(arguments[a]));return i.join("")}})},{"./$":223,"./$.def":219}],277:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.def");l(l.P,"String",{repeat:function(e){var t=String(r.assertDefined(this)),n="",l=r.toInteger(e);if(0>l||l==1/0)throw RangeError("Count can't be negative");for(;l>0;(l>>>=1)&&(t+=t))1&l&&(n+=t);return n}})},{"./$":223,"./$.def":219}],278:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.cof"),i=e("./$.def");i(i.P,"String",{startsWith:function(e){if("RegExp"==l(e))throw TypeError();var t=String(r.assertDefined(this)),n=r.toLength(Math.min(arguments[1],t.length));return e+="",t.slice(n,n+e.length)===e}})},{"./$":223,"./$.cof":214,"./$.def":219}],279:[function(e,t,n){"use strict";function r(e){var t=v[e]=l.set(l.create(f.prototype),g,e);return l.DESC&&m&&l.setDesc(Object.prototype,e,{configurable:!0,set:function(t){c(this,e,t)}}),t}var l=e("./$"),i=e("./$.cof").set,a=e("./$.uid"),s=e("./$.def"),o=e("./$.keyof"),u=l.has,c=l.hide,p=l.getNames,d=l.toObject,f=l.g.Symbol,h=f,m=!1,g=a.safe("tag"),y={},v={};l.isFunction(f)||(f=function(e){if(this instanceof f)throw TypeError("Symbol is not a constructor");return r(a(e))},c(f.prototype,"toString",function(){return this[g]})),s(s.G+s.W,{Symbol:f});var b={"for":function(e){return u(y,e+="")?y[e]:y[e]=f(e)},keyFor:function(e){return o(y,e)},pure:a.safe,set:l.set,useSetter:function(){m=!0},useSimple:function(){m=!1}};l.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),function(t){var n=e("./$.wks")(t);b[t]=f===h?n:r(n)}),m=!0,s(s.S,"Symbol",b),s(s.S+s.F*(f!=h),"Object",{getOwnPropertyNames:function(e){for(var t,n=p(d(e)),r=[],l=0;n.length>l;)u(v,t=n[l++])||r.push(t);return r},getOwnPropertySymbols:function(e){for(var t,n=p(d(e)),r=[],l=0;n.length>l;)u(v,t=n[l++])&&r.push(v[t]);return r}}),i(f,"Symbol"),i(Math,"Math",!0),i(l.g.JSON,"JSON",!0)},{"./$":223,"./$.cof":214,"./$.def":219,"./$.keyof":224,"./$.uid":232,"./$.wks":234}],280:[function(e,t,n){"use strict";var r=e("./$"),l=e("./$.collection-weak"),i=l.leakStore,a=l.ID,s=l.WEAK,o=r.has,u=r.isObject,c=Object.isFrozen||r.core.Object.isFrozen,p={},d=e("./$.collection")("WeakMap",{get:function(e){if(u(e)){if(c(e))return i(this).get(e);if(o(e,s))return e[s][this[a]]}},set:function(e,t){return l.def(this,e,t)}},l,!0,!0);r.FW&&7!=(new d).set((Object.freeze||Object)(p),7).get(p)&&r.each.call(["delete","has","get","set"],function(e){var t=d.prototype[e];d.prototype[e]=function(n,r){if(u(n)&&c(n)){var l=i(this)[e](n,r);return"set"==e?this:l}return t.call(this,n,r)}})},{"./$":223,"./$.collection":217,"./$.collection-weak":216}],281:[function(e,t,n){"use strict";var r=e("./$.collection-weak");e("./$.collection")("WeakSet",{add:function(e){return r.def(this,e,!0)}},r,!1,!0)},{"./$.collection":217,"./$.collection-weak":216}],282:[function(e,t,n){var r=e("./$.def");r(r.P,"Array",{includes:e("./$.array-includes")(!0)}),e("./$.unscope")("includes")},{"./$.array-includes":210,"./$.def":219,"./$.unscope":233}],283:[function(e,t,n){var r=e("./$"),l=e("./$.def"),i=e("./$.own-keys");l(l.S,"Object",{getOwnPropertyDescriptors:function(e){var t=r.toObject(e),n={};return r.each.call(i(t),function(e){r.setDesc(n,e,r.desc(0,r.getDesc(t,e)))}),n}})},{"./$":223,"./$.def":219,"./$.own-keys":225}],284:[function(e,t,n){function r(e){return function(t){var n,r=l.toObject(t),i=l.getKeys(t),a=i.length,s=0,o=Array(a);if(e)for(;a>s;)o[s]=[n=i[s++],r[n]];else for(;a>s;)o[s]=r[i[s++]];return o}}var l=e("./$"),i=e("./$.def");i(i.S,"Object",{values:r(!1),entries:r(!0)})},{"./$":223,"./$.def":219}],285:[function(e,t,n){var r=e("./$.def");r(r.S,"RegExp",{escape:e("./$.replacer")(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",!0)})},{"./$.def":219,"./$.replacer":227}],286:[function(e,t,n){var r=e("./$.def");r(r.P,"String",{at:e("./$.string-at")(!0)})},{"./$.def":219,"./$.string-at":230}],287:[function(e,t,n){function r(t,n){l.each.call(t.split(","),function(t){void 0==n&&t in a.Array?s[t]=a.Array[t]:t in[]&&(s[t]=e("./$.ctx")(Function.call,[][t],n))})}var l=e("./$"),i=e("./$.def"),a=l.core,s={};r("pop,reverse,shift,keys,values,entries",1),r("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3),r("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill,turn"),i(i.S,"Array",s)},{"./$":223,"./$.ctx":218,"./$.def":219}],288:[function(e,t,n){e("./es6.array.iterator");var r=e("./$"),l=e("./$.iter").Iterators,i=e("./$.wks")("iterator"),a=r.g.NodeList;!r.FW||!a||i in a.prototype||r.hide(a.prototype,i,l.Array),l.NodeList=l.Array},{"./$":223,"./$.iter":222,"./$.wks":234,"./es6.array.iterator":254}],289:[function(e,t,n){var r=e("./$.def"),l=e("./$.task");r(r.G+r.B,{setImmediate:l.set,clearImmediate:l.clear})},{"./$.def":219,"./$.task":231}],290:[function(e,t,n){function r(e){return o?function(t,n){return e(a(s,[].slice.call(arguments,2),l.isFunction(t)?t:Function(t)),n)}:e}var l=e("./$"),i=e("./$.def"),a=e("./$.invoke"),s=e("./$.partial"),o=!!l.g.navigator&&/MSIE .\./.test(navigator.userAgent);i(i.G+i.B+i.F*o,{setTimeout:r(l.g.setTimeout),setInterval:r(l.g.setInterval)})},{"./$":223,"./$.def":219,"./$.invoke":221,"./$.partial":226}],291:[function(e,t,n){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[c++%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 a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var l=n.formatters[r];if("function"==typeof l){var i=a[s];t=l.call(e,i),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var o=l.log||n.log||console.log.bind(console);o.apply(e,a)}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 a(){n.enable("")}function s(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=a,n.enable=i,n.enabled=s,n.humanize=e("ms"),n.names=[],n.skips=[],n.formatters={};var u,c=0},{ms:294}],293:[function(e,t,n){(function(r){function l(){var e=(r.env.DEBUG_COLORS||"").trim().toLowerCase();return 0===e.length?c.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+" "+e[0]+"[3"+l+"m +"+n.humanize(this.diff)+""}else e[0]=(new Date).toUTCString()+" "+r+" "+e[0];return e}function a(){return f.write(p.format.apply(this,arguments)+"\n")}function s(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 c.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 a=e("net");n=new a.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 c=e("tty"),p=e("util");n=t.exports=e("./debug"),n.log=a,n.formatArgs=i,n.save=s,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===p.inspect.length?function(e,t){return p.inspect(e,void 0,void 0,t)}:function(e,t){return p.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,n){function r(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*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*u;case"minutes":case"minute":case"mins":case"min":case"m":return n*o;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 l(e){return e>=c?Math.round(e/c)+"d":e>=u?Math.round(e/u)+"h":e>=o?Math.round(e/o)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function i(e){return a(e,c,"day")||a(e,u,"hour")||a(e,o,"minute")||a(e,s,"second")||e+" ms"}function a(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,o=60*s,u=60*o,c=24*u,p=365.25*c;t.exports=function(e,t){return t=t||{},"string"==typeof e?r(e):t["long"]?i(e):l(e)}},{}],295:[function(e,t,n){"use strict";function r(e){var t=0,n=0,r=0;for(var l in e){var i=e[l],a=i[0],s=i[1];(a>n||a===n&&s>r)&&(n=a,r=s,t=+l)}return t}var l=e("repeating"),i=/^(?:( )+|\t+)/;t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");var t,n,a=0,s=0,o=0,u={};e.split(/\n/g).forEach(function(e){if(e){var r,l=e.match(i);l?(r=l[0].length,l[1]?s++:a++):r=0;var c=r-o;o=r,c?(n=c>0,t=u[n?c:-c],t?t[0]++:t=u[c]=[1,0]):t&&(t[1]+=+n)}});var c,p,d=r(u);return d?s>=a?(c="space",p=l(" ",d)):(c="tab",p=l(" ",d)):(c=null,p=""),{amount:d,type:c,indent:p}}},{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 a(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 s(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 c(){}function p(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 c;return n.traverse(e,t)}function h(e,t){var n=new c;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,a,s,o=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(a=0,i=t.length;i>a;a+=1)l=n(t[a]),l.extendedRange=[0,e.range[0]],o.push(l);e.leadingComments=o}return e}for(a=0,i=t.length;i>a;a+=1)o.push(m(n(t[a]),r));return s=0,f(e,{enter:function(e){for(var t;s<o.length&&(t=o[s],!(t.extendedRange[1]>e.range[0]));)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),o.splice(s,1)):s+=1;return s===o.length?b.Break:o[s].extendedRange[0]>e.range[1]?b.Skip:void 0}}),s=0,f(e,{leave:function(e){for(var t;s<o.length&&(t=o[s],!(e.range[1]<t.extendedRange[0]));)e.range[1]===t.extendedRange[0]?(e.trailingComments||(e.trailingComments=[]),e.trailingComments.push(t),o.splice(s,1)):s+=1;return s===o.length?b.Break:o[s].extendedRange[0]>e.range[1]?b.Skip:void 0}}),e}var y,v,b,x,E,_,w,S,I;return v=Array.isArray,v||(v=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),t(r),t(a),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"]},w={},S={},I={},b={Break:w,Skip:S,Remove:I},o.prototype.replace=function(e){this.parent[this.key]=e},o.prototype.remove=function(){return v(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},c.prototype.path=function(){function e(e,t){if(v(t))for(r=0,l=t.length;l>r;++r)e.push(t[r]);else e.push(t)}var t,n,r,l,i,a;if(!this.__current.path)return null;for(i=[],t=2,n=this.__leavelist.length;n>t;++t)a=this.__leavelist[t],e(i,a.path);return e(i,this.__current.path),i},c.prototype.type=function(){var e=this.current();return e.type||this.__current.wrap},c.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},c.prototype.current=function(){return this.__current.node},c.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},c.prototype.notify=function(e){this.__state=e},c.prototype.skip=function(){this.notify(S)},c.prototype["break"]=function(){this.notify(w)},c.prototype.remove=function(){this.notify(I)},c.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=s(E(this.__keys),t.keys))},c.prototype.traverse=function(e,t){var n,r,l,i,a,s,o,c,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(s=this.__execute(t.enter,l),this.__state===w||s===w)return;if(n.push(g),r.push(l),this.__state===S||s===S)continue;if(i=l.node,a=l.wrap||i.type,h=this.__keys[a],!h){if(!this.__fallback)throw new Error("Unknown node type "+a+".");h=_(i)}for(c=h.length;(c-=1)>=0;)if(o=h[c],m=i[o])if(v(m)){for(f=m.length;(f-=1)>=0;)if(m[f]){if(d(a,h[c]))l=new u(m[f],[o,f],"Property",null);else{if(!p(m[f]))continue;l=new u(m[f],[o,f],null,null)}n.push(l)}}else p(m)&&n.push(new u(m,o,null,null))}}else if(l=r.pop(),s=this.__execute(t.leave,l),this.__state===w||s===w)return},c.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,a,s,c,f,h,m,g,y,b,x;for(this.__initialize(e,t),y={},r=this.__worklist,l=this.__leavelist,b={root:e},c=new u(e,null,null,new o(b,"root")),r.push(c),l.push(c);r.length;)if(c=r.pop(),c!==y){if(s=this.__execute(t.enter,c),void 0!==s&&s!==w&&s!==S&&s!==I&&(c.ref.replace(s),c.node=s),(this.__state===I||s===I)&&(n(c),c.node=null),this.__state===w||s===w)return b.root;if(i=c.node,i&&(r.push(y),l.push(c),this.__state!==S&&s!==S)){if(a=c.wrap||i.type,m=this.__keys[a],!m){if(!this.__fallback)throw new Error("Unknown node type "+a+".");m=_(i)}for(f=m.length;(f-=1)>=0;)if(x=m[f],g=i[x])if(v(g)){for(h=g.length;(h-=1)>=0;)if(g[h]){if(d(a,m[f]))c=new u(g[h],[x,h],"Property",new o(g,h));else{if(!p(g[h]))continue;c=new u(g[h],[x,h],null,new o(g,h))}r.push(c)}}else p(g)&&r.push(new u(g,x,null,new o(i,x)))}}else if(c=l.pop(),s=this.__execute(t.leave,c),void 0!==s&&s!==w&&s!==S&&s!==I&&c.ref.replace(s),(this.__state===I||s===I)&&n(c),this.__state===w||s===w)return b.root;return b.root},e.version="1.8.1-dev",e.Syntax=y,e.traverse=f,e.replace=h,e.attachComments=g,e.VisitorKeys=x,e.VisitorOption=b,e.Controller=c,e.cloneEnvironment=function(){return l({})},e})},{}],297:[function(e,t,n){!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 a(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:a,trailingStatement:i}}()},{}],298:[function(e,t,n){!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 a(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 s(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:a,isIdentifierPart:s}}()},{}],299:[function(e,t,n){!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 a(e,t){return"null"===e||"true"===e||"false"===e||l(e,t)}function s(e){return"eval"===e||"arguments"===e}function o(e){var t,n,r;if(0===e.length)return!1;if(r=e.charCodeAt(0),!p.isIdentifierStart(r)||92===r)return!1;for(t=1,n=e.length;n>t;++t)if(r=e.charCodeAt(t),!p.isIdentifierPart(r)||92===r)return!1;return!0}function u(e,t){return o(e)&&!i(e,t)}function c(e,t){return o(e)&&!a(e,t)}var p=e("./code");t.exports={isKeywordES5:r,isKeywordES6:l,isReservedWordES5:i,isReservedWordES6:a,isRestrictedWord:s,isIdentifierName:o,isIdentifierES5:u,isIdentifierES6:c}}()},{"./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,n){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,n){t.exports=e("./globals.json")},{"./globals.json":301}],303:[function(e,t,n){var r=e("is-nan"),l=e("is-finite");t.exports=Number.isInteger||function(e){return"number"==typeof e&&!r(e)&&l(e)&&parseInt(e,10)===e}},{"is-finite":304,"is-nan":305}],304:[function(e,t,n){"use strict";t.exports=Number.isFinite||function(e){return"number"!=typeof e||e!==e||e===1/0||e===-(1/0)?!1:!0}},{}],305:[function(e,t,n){"use strict";t.exports=function(e){return e!==e}},{}],306:[function(e,t,n){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,n){var r=[],l=[];t.exports=function(e,t){if(e===t)return 0;var n=e.length,i=t.length;if(0===n)return i;if(0===i)return n;for(var a,s,o,u,c=0,p=0;n>c;)l[c]=e.charCodeAt(c),r[c]=++c;for(;i>p;)for(a=t.charCodeAt(p),o=p++,s=p,c=0;n>c;c++)u=a===l[c]?o:o+1,o=r[c],s=r[c]=o>s?u>s?s+1:u:u>o?o+1:u;return s}},{}],308:[function(e,t,n){function r(e,t,n){ return t in e?e[t]:n}function l(e,t){var n=r.bind(null,t||{}),l=n("transform",Function.prototype),a=n("padding"," "),s=n("before"," "),o=n("after"," | "),u=n("start",1),c=Array.isArray(e),p=c?e:e.split("\n"),d=u+p.length-1,f=String(d).length,h=p.map(function(e,t){var n=u+t,r={before:s,number:n,width:f,after:o,line:e};return l(r),r.before+i(r.number,f,a)+r.after+r.line});return c?h:h.join("\n")}var i=e("left-pad");t.exports=l},{"left-pad":309}],309:[function(e,t,n){function r(e,t,n){e=String(e);var r=-1;for(n||(n=" "),t-=e.length;++r<t;)e=n+e;return e}t.exports=r},{}],310:[function(e,t,n){function r(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=r},{}],311:[function(e,t,n){function r(e,t,n){var r=e?e.length:0;return n&&i(e,t,n)&&(t=!1),r?l(e,t):[]}var l=e("../internal/baseFlatten"),i=e("../internal/isIterateeCall");t.exports=r},{"../internal/baseFlatten":339,"../internal/isIterateeCall":382}],312:[function(e,t,n){function r(e){var t=e?e.length:0;return t?e[t-1]:void 0}t.exports=r},{}],313:[function(e,t,n){function r(){var e=arguments,t=e[0];if(!t||!t.length)return t;for(var n=0,r=l,i=e.length;++n<i;)for(var s=0,o=e[n];(s=r(t,o,s))>-1;)a.call(t,s,1);return t}var l=e("../internal/baseIndexOf"),i=Array.prototype,a=i.splice;t.exports=r},{"../internal/baseIndexOf":345}],314:[function(e,t,n){function r(e,t,n,r){var o=e?e.length:0;return o?(null!=t&&"boolean"!=typeof t&&(r=n,n=a(e,t,r)?null:t,t=!1),n=null==n?n:l(n,r,3),t?s(e,n):i(e,n)):[]}var l=e("../internal/baseCallback"),i=e("../internal/baseUniq"),a=e("../internal/isIterateeCall"),s=e("../internal/sortedUniq");t.exports=r},{"../internal/baseCallback":333,"../internal/baseUniq":360,"../internal/isIterateeCall":382,"../internal/sortedUniq":388}],315:[function(e,t,n){t.exports=e("./includes")},{"./includes":319}],316:[function(e,t,n){t.exports=e("./forEach")},{"./forEach":317}],317:[function(e,t,n){var r=e("../internal/arrayEach"),l=e("../internal/baseEach"),i=e("../internal/createForEach"),a=i(r,l);t.exports=a},{"../internal/arrayEach":327,"../internal/baseEach":337,"../internal/createForEach":372}],318:[function(e,t,n){var r=e("../internal/createAggregator"),l=Object.prototype,i=l.hasOwnProperty,a=r(function(e,t,n){i.call(e,n)?e[n].push(t):e[n]=[t]});t.exports=a},{"../internal/createAggregator":367}],319:[function(e,t,n){function r(e,t,n,r){var p=e?e.length:0;return s(p)||(e=u(e),p=e.length),p?(n="number"!=typeof n||r&&a(t,n,r)?0:0>n?c(p+n,0):n||0,"string"==typeof e||!i(e)&&o(e)?p>n&&e.indexOf(t,n)>-1:l(e,t,n)>-1):!1}var l=e("../internal/baseIndexOf"),i=e("../lang/isArray"),a=e("../internal/isIterateeCall"),s=e("../internal/isLength"),o=e("../lang/isString"),u=e("../object/values"),c=Math.max;t.exports=r},{"../internal/baseIndexOf":345,"../internal/isIterateeCall":382,"../internal/isLength":383,"../lang/isArray":392,"../lang/isString":401,"../object/values":411}],320:[function(e,t,n){function r(e,t,n){var r=s(e)?l:a;return t=i(t,n,3),r(e,t)}var l=e("../internal/arrayMap"),i=e("../internal/baseCallback"),a=e("../internal/baseMap"),s=e("../lang/isArray");t.exports=r},{"../internal/arrayMap":328,"../internal/baseCallback":333,"../internal/baseMap":350,"../lang/isArray":392}],321:[function(e,t,n){var r=e("../internal/arrayReduceRight"),l=e("../internal/baseEachRight"),i=e("../internal/createReduce"),a=i(r,l);t.exports=a},{"../internal/arrayReduceRight":329,"../internal/baseEachRight":338,"../internal/createReduce":373}],322:[function(e,t,n){function r(e,t,n){var r=s(e)?l:a;return n&&o(e,t,n)&&(t=null),("function"!=typeof t||"undefined"!=typeof n)&&(t=i(t,n,3)),r(e,t)}var l=e("../internal/arraySome"),i=e("../internal/baseCallback"),a=e("../internal/baseSome"),s=e("../lang/isArray"),o=e("../internal/isIterateeCall");t.exports=r},{"../internal/arraySome":330,"../internal/baseCallback":333,"../internal/baseSome":357,"../internal/isIterateeCall":382,"../lang/isArray":392}],323:[function(e,t,n){function r(e,t,n){if(null==e)return[];var r=-1,c=e.length,p=u(c)?Array(c):[];return n&&o(e,t,n)&&(t=null),t=l(t,n,3),i(e,function(e,n,l){p[++r]={criteria:t(e,n,l),index:r,value:e}}),a(p,s)}var l=e("../internal/baseCallback"),i=e("../internal/baseEach"),a=e("../internal/baseSortBy"),s=e("../internal/compareAscending"),o=e("../internal/isIterateeCall"),u=e("../internal/isLength");t.exports=r},{"../internal/baseCallback":333,"../internal/baseEach":337,"../internal/baseSortBy":358,"../internal/compareAscending":366,"../internal/isIterateeCall":382,"../internal/isLength":383}],324:[function(e,t,n){function r(e,t){if("function"!=typeof e)throw new TypeError(l);return t=i("undefined"==typeof t?e.length-1:+t||0,0),function(){for(var n=arguments,r=-1,l=i(n.length-t,0),a=Array(l);++r<l;)a[r]=n[t+r];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(r=-1;++r<t;)s[r]=n[r];return s[t]=a,e.apply(this,s)}}var l="Expected a function",i=Math.max;t.exports=r},{}],325:[function(e,t,n){(function(n){function r(e){var t=e?e.length:0;for(this.data={hash:s(null),set:new a};t--;)this.push(e[t])}var l=e("./cachePush"),i=e("../lang/isNative"),a=i(a=n.Set)&&a,s=i(s=Object.create)&&s;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,n){function r(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}t.exports=r},{}],327:[function(e,t,n){function r(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}t.exports=r},{}],328:[function(e,t,n){function r(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=r},{}],329:[function(e,t,n){function r(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=r},{}],330:[function(e,t,n){function r(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}t.exports=r},{}],331:[function(e,t,n){function r(e,t){return"undefined"==typeof e?t:e}t.exports=r},{}],332:[function(e,t,n){function r(e,t,n){var r=i(t);if(!n)return l(t,e,r);for(var a=-1,s=r.length;++a<s;){var o=r[a],u=e[o],c=n(u,t[o],o,e,t);(c===c?c===u:u!==u)&&("undefined"!=typeof u||o in e)||(e[o]=c)}return e}var l=e("./baseCopy"),i=e("../object/keys");t.exports=r},{"../object/keys":408,"./baseCopy":336}],333:[function(e,t,n){function r(e,t,n){var r=typeof e;return"function"==r?"undefined"==typeof t?e:s(e,t,n):null==e?o:"object"==r?l(e):"undefined"==typeof t?a(e+""):i(e+"",t)}var l=e("./baseMatches"),i=e("./baseMatchesProperty"),a=e("./baseProperty"),s=e("./bindCallback"),o=e("../utility/identity");t.exports=r},{"../utility/identity":415,"./baseMatches":351,"./baseMatchesProperty":352,"./baseProperty":355,"./bindCallback":362}],334:[function(e,t,n){function r(e,t,n,m,g,y,v){var x;if(n&&(x=g?n(e,m,g):n(e)),"undefined"!=typeof x)return x;if(!d(e))return e;var E=p(e);if(E){if(x=o(e),!t)return l(e,x)}else{var w=B.call(e),S=w==b;if(w!=_&&w!=h&&(!S||g))return R[w]?u(e,w,t):g?e:{};if(x=c(S?{}:e),!t)return a(e,x,f(e))}y||(y=[]),v||(v=[]);for(var I=y.length;I--;)if(y[I]==e)return v[I];return y.push(e),v.push(x),(E?i:s)(e,function(l,i){x[i]=r(l,t,n,i,e,y,v)}),x}var l=e("./arrayCopy"),i=e("./arrayEach"),a=e("./baseCopy"),s=e("./baseForOwn"),o=e("./initCloneArray"),u=e("./initCloneByTag"),c=e("./initCloneObject"),p=e("../lang/isArray"),d=e("../lang/isObject"),f=e("../object/keys"),h="[object Arguments]",m="[object Array]",g="[object Boolean]",y="[object Date]",v="[object Error]",b="[object Function]",x="[object Map]",E="[object Number]",_="[object Object]",w="[object RegExp]",S="[object Set]",I="[object String]",k="[object WeakMap]",T="[object ArrayBuffer]",C="[object Float32Array]",j="[object Float64Array]",M="[object Int8Array]",A="[object Int16Array]",O="[object Int32Array]",L="[object Uint8Array]",P="[object Uint8ClampedArray]",N="[object Uint16Array]",D="[object Uint32Array]",R={};R[h]=R[m]=R[T]=R[g]=R[y]=R[C]=R[j]=R[M]=R[A]=R[O]=R[E]=R[_]=R[w]=R[I]=R[L]=R[P]=R[N]=R[D]=!0,R[v]=R[b]=R[x]=R[S]=R[k]=!1;var F=Object.prototype,B=F.toString;t.exports=r},{"../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,n){function r(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=r},{}],336:[function(e,t,n){function r(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=r},{}],337:[function(e,t,n){var r=e("./baseForOwn"),l=e("./createBaseEach"),i=l(r);t.exports=i},{"./baseForOwn":342,"./createBaseEach":369}],338:[function(e,t,n){var r=e("./baseForOwnRight"),l=e("./createBaseEach"),i=l(r,!0);t.exports=i},{"./baseForOwnRight":343,"./createBaseEach":369}],339:[function(e,t,n){function r(e,t,n){for(var o=-1,u=e.length,c=-1,p=[];++o<u;){var d=e[o];if(s(d)&&a(d.length)&&(i(d)||l(d))){t&&(d=r(d,t,n));var f=-1,h=d.length;for(p.length+=h;++f<h;)p[++c]=d[f]}else n||(p[++c]=d)}return p}var l=e("../lang/isArguments"),i=e("../lang/isArray"),a=e("./isLength"),s=e("./isObjectLike");t.exports=r},{"../lang/isArguments":391,"../lang/isArray":392,"./isLength":383,"./isObjectLike":384}],340:[function(e,t,n){var r=e("./createBaseFor"),l=r();t.exports=l},{"./createBaseFor":370}],341:[function(e,t,n){function r(e,t){return l(e,t,i)}var l=e("./baseFor"),i=e("../object/keysIn");t.exports=r},{"../object/keysIn":409,"./baseFor":340}],342:[function(e,t,n){function r(e,t){return l(e,t,i)}var l=e("./baseFor"),i=e("../object/keys");t.exports=r},{"../object/keys":408,"./baseFor":340}],343:[function(e,t,n){function r(e,t){return l(e,t,i)}var l=e("./baseForRight"),i=e("../object/keys");t.exports=r},{"../object/keys":408,"./baseForRight":344}],344:[function(e,t,n){var r=e("./createBaseFor"),l=r(!0);t.exports=l},{"./createBaseFor":370}],345:[function(e,t,n){function r(e,t,n){if(t!==t)return l(e,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}var l=e("./indexOfNaN");t.exports=r},{"./indexOfNaN":377}],346:[function(e,t,n){function r(e,t,n,i,a,s){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:l(e,t,r,n,i,a,s)}var l=e("./baseIsEqualDeep");t.exports=r},{"./baseIsEqualDeep":347}],347:[function(e,t,n){function r(e,t,n,r,f,g,y){var v=s(e),b=s(t),x=c,E=c;v||(x=m.call(e),x==u?x=d:x!=d&&(v=o(e))),b||(E=m.call(t),E==u?E=d:E!=d&&(b=o(t)));var _=x==d||f&&x==p,w=E==d||f&&E==p,S=x==E;if(S&&!v&&!_)return i(e,t,x);if(f){if(!(S||_&&w))return!1}else{var I=_&&h.call(e,"__wrapped__"),k=w&&h.call(t,"__wrapped__");if(I||k)return n(I?e.value():e,k?t.value():t,r,f,g,y);if(!S)return!1}g||(g=[]),y||(y=[]);for(var T=g.length;T--;)if(g[T]==e)return y[T]==t;g.push(e),y.push(t);var C=(v?l:a)(e,t,n,r,f,g,y);return g.pop(),y.pop(),C}var l=e("./equalArrays"),i=e("./equalByTag"),a=e("./equalObjects"),s=e("../lang/isArray"),o=e("../lang/isTypedArray"),u="[object Arguments]",c="[object Array]",p="[object Function]",d="[object Object]",f=Object.prototype,h=f.hasOwnProperty,m=f.toString;t.exports=r},{"../lang/isArray":392,"../lang/isTypedArray":402,"./equalArrays":374,"./equalByTag":375,"./equalObjects":376}],348:[function(e,t,n){function r(e){return"function"==typeof e||!1}t.exports=r},{}],349:[function(e,t,n){function r(e,t,n,r,i){for(var a=-1,s=t.length,o=!i;++a<s;)if(o&&r[a]?n[a]!==e[t[a]]:!(t[a]in e))return!1;for(a=-1;++a<s;){var u=t[a],c=e[u],p=n[a];if(o&&r[a])var d="undefined"!=typeof c||u in e;else d=i?i(c,p,u):void 0,"undefined"==typeof d&&(d=l(p,c,i,!0));if(!d)return!1}return!0}var l=e("./baseIsEqual");t.exports=r},{"./baseIsEqual":346}],350:[function(e,t,n){function r(e,t){var n=[];return l(e,function(e,r,l){n.push(t(e,r,l))}),n}var l=e("./baseEach");t.exports=r},{"./baseEach":337}],351:[function(e,t,n){function r(e){var t=s(e),n=t.length;if(!n)return i(!0);if(1==n){var r=t[0],u=e[r];if(a(u))return function(e){return null!=e&&e[r]===u&&("undefined"!=typeof u||r in o(e))}}for(var c=Array(n),p=Array(n);n--;)u=e[t[n]],c[n]=u,p[n]=a(u);return function(e){return null!=e&&l(o(e),t,c,p)}}var l=e("./baseIsMatch"),i=e("../utility/constant"),a=e("./isStrictComparable"),s=e("../object/keys"),o=e("./toObject");t.exports=r},{"../object/keys":408,"../utility/constant":414,"./baseIsMatch":349,"./isStrictComparable":385,"./toObject":389}],352:[function(e,t,n){function r(e,t){return i(t)?function(n){return null!=n&&n[e]===t&&("undefined"!=typeof t||e in a(n))}:function(n){return null!=n&&l(t,n[e],null,!0)}}var l=e("./baseIsEqual"),i=e("./isStrictComparable"),a=e("./toObject");t.exports=r},{"./baseIsEqual":346,"./isStrictComparable":385,"./toObject":389}],353:[function(e,t,n){function r(e,t,n,d,f){if(!u(e))return e;var h=o(t.length)&&(s(t)||p(t));return(h?l:i)(t,function(t,l,i){if(c(t))return d||(d=[]),f||(f=[]),a(e,i,l,r,n,d,f);var s=e[l],o=n?n(s,t,l,e,i):void 0,u="undefined"==typeof o;u&&(o=t),!h&&"undefined"==typeof o||!u&&(o===o?o===s:s!==s)||(e[l]=o)}),e}var l=e("./arrayEach"),i=e("./baseForOwn"),a=e("./baseMergeDeep"),s=e("../lang/isArray"),o=e("./isLength"),u=e("../lang/isObject"),c=e("./isObjectLike"),p=e("../lang/isTypedArray");t.exports=r},{"../lang/isArray":392,"../lang/isObject":398,"../lang/isTypedArray":402,"./arrayEach":327,"./baseForOwn":342,"./baseMergeDeep":354,"./isLength":383,"./isObjectLike":384}],354:[function(e,t,n){function r(e,t,n,r,p,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=p?p(g,m,n,e,t):void 0,v="undefined"==typeof y;v&&(y=m,s(m.length)&&(a(m)||u(m))?y=a(g)?g:g&&g.length?l(g):[]:o(m)||i(m)?y=i(g)?c(g):o(g)?g:{}:v=!1),d.push(m),f.push(y),v?e[n]=r(y,m,p,d,f):(y===y?y!==g:g===g)&&(e[n]=y)}var l=e("./arrayCopy"),i=e("../lang/isArguments"),a=e("../lang/isArray"),s=e("./isLength"),o=e("../lang/isPlainObject"),u=e("../lang/isTypedArray"),c=e("../lang/toPlainObject");t.exports=r},{"../lang/isArguments":391,"../lang/isArray":392,"../lang/isPlainObject":399,"../lang/isTypedArray":402,"../lang/toPlainObject":403,"./arrayCopy":326,"./isLength":383}],355:[function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}t.exports=r},{}],356:[function(e,t,n){function r(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=r},{}],357:[function(e,t,n){function r(e,t){var n;return l(e,function(e,r,l){return n=t(e,r,l),!n}),!!n}var l=e("./baseEach");t.exports=r},{"./baseEach":337}],358:[function(e,t,n){function r(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}t.exports=r},{}],359:[function(e,t,n){function r(e){return"string"==typeof e?e:null==e?"":e+""}t.exports=r},{}],360:[function(e,t,n){function r(e,t){var n=-1,r=l,s=e.length,o=!0,u=o&&s>=200,c=u?a():null,p=[];c?(r=i,o=!1):(u=!1,c=t?[]:p);e:for(;++n<s;){var d=e[n],f=t?t(d,n,e):d;if(o&&d===d){for(var h=c.length;h--;)if(c[h]===f)continue e;t&&c.push(f),p.push(d)}else r(c,f,0)<0&&((t||u)&&c.push(f),p.push(d))}return p}var l=e("./baseIndexOf"),i=e("./cacheIndexOf"),a=e("./createCache");t.exports=r},{"./baseIndexOf":345,"./cacheIndexOf":364,"./createCache":371}],361:[function(e,t,n){function r(e,t){for(var n=-1,r=t.length,l=Array(r);++n<r;)l[n]=e[t[n]];return l}t.exports=r},{}],362:[function(e,t,n){function r(e,t,n){if("function"!=typeof e)return l;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,a){return e.call(t,n,r,l,i,a)}}return function(){return e.apply(t,arguments)}}var l=e("../utility/identity");t.exports=r},{"../utility/identity":415}],363:[function(e,t,n){(function(n){function r(e){return s.call(e,0)}var l=e("../utility/constant"),i=e("../lang/isNative"),a=i(a=n.ArrayBuffer)&&a,s=i(s=a&&new a(0).slice)&&s,o=Math.floor,u=i(u=n.Uint8Array)&&u,c=function(){try{var e=i(e=n.Float64Array)&&e,t=new e(new a(10),0,1)&&e}catch(r){}return t}(),p=c?c.BYTES_PER_ELEMENT:0;s||(r=a&&u?function(e){var t=e.byteLength,n=c?o(t/p):0,r=n*p,l=new a(t);if(n){var i=new c(l,0,n);i.set(new c(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,n){function r(e,t){var n=e.data,r="string"==typeof t||l(t)?n.set.has(t):n.hash[t];return r?0:-1}var l=e("../lang/isObject");t.exports=r},{"../lang/isObject":398}],365:[function(e,t,n){function r(e){var t=this.data;"string"==typeof e||l(e)?t.set.add(e):t.hash[e]=!0}var l=e("../lang/isObject");t.exports=r},{"../lang/isObject":398}],366:[function(e,t,n){function r(e,t){return l(e.criteria,t.criteria)||e.index-t.index}var l=e("./baseCompareAscending");t.exports=r},{"./baseCompareAscending":335}],367:[function(e,t,n){function r(e,t){return function(n,r,s){var o=t?t():{};if(r=l(r,s,3),a(n))for(var u=-1,c=n.length;++u<c;){var p=n[u];e(o,p,r(p,u,n),n)}else i(n,function(t,n,l){e(o,t,r(t,n,l),l)});return o}}var l=e("./baseCallback"),i=e("./baseEach"),a=e("../lang/isArray");t.exports=r},{"../lang/isArray":392,"./baseCallback":333,"./baseEach":337}],368:[function(e,t,n){function r(e){return function(){var t=arguments,n=t.length,r=t[0];if(2>n||null==r)return r;var a=t[n-2],s=t[n-1],o=t[3];n>3&&"function"==typeof a?(a=l(a,s,5),n-=2):(a=n>2&&"function"==typeof s?s:null,n-=a?1:0),o&&i(t[1],t[2],o)&&(a=3==n?null:a,n=2);for(var u=0;++u<n;){var c=t[u];c&&e(r,c,a)}return r}}var l=e("./bindCallback"),i=e("./isIterateeCall");t.exports=r},{"./bindCallback":362,"./isIterateeCall":382}],369:[function(e,t,n){function r(e,t){return function(n,r){var a=n?n.length:0;if(!l(a))return e(n,r);for(var s=t?a:-1,o=i(n);(t?s--:++s<a)&&r(o[s],s,o)!==!1;);return n}}var l=e("./isLength"),i=e("./toObject");t.exports=r},{"./isLength":383,"./toObject":389}],370:[function(e,t,n){function r(e){return function(t,n,r){for(var i=l(t),a=r(t),s=a.length,o=e?s:-1;e?o--:++o<s;){var u=a[o];if(n(i[u],u,i)===!1)break}return t}}var l=e("./toObject");t.exports=r},{"./toObject":389}],371:[function(e,t,n){(function(n){var r=e("./SetCache"),l=e("../utility/constant"),i=e("../lang/isNative"),a=i(a=n.Set)&&a,s=i(s=Object.create)&&s,o=s&&a?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,n){function r(e,t){return function(n,r,a){return"function"==typeof r&&"undefined"==typeof a&&i(n)?e(n,r):t(n,l(r,a,3))}}var l=e("./bindCallback"),i=e("../lang/isArray");t.exports=r},{"../lang/isArray":392,"./bindCallback":362}],373:[function(e,t,n){function r(e,t){return function(n,r,s,o){var u=arguments.length<3;return"function"==typeof r&&"undefined"==typeof o&&a(n)?e(n,r,s,u):i(n,l(r,o,4),s,u,t)}}var l=e("./baseCallback"),i=e("./baseReduce"),a=e("../lang/isArray");t.exports=r},{"../lang/isArray":392,"./baseCallback":333,"./baseReduce":356}],374:[function(e,t,n){function r(e,t,n,r,l,i,a){var s=-1,o=e.length,u=t.length,c=!0;if(o!=u&&!(l&&u>o))return!1;for(;c&&++s<o;){var p=e[s],d=t[s];if(c=void 0,r&&(c=l?r(d,p,s):r(p,d,s)),"undefined"==typeof c)if(l)for(var f=u;f--&&(d=t[f],!(c=p&&p===d||n(p,d,r,l,i,a))););else c=p&&p===d||n(p,d,r,l,i,a)}return!!c}t.exports=r},{}],375:[function(e,t,n){function r(e,t,n){switch(n){case l:case i:return+e==+t;case a: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 o:case u:return e==t+""}return!1}var l="[object Boolean]",i="[object Date]",a="[object Error]",s="[object Number]",o="[object RegExp]",u="[object String]";t.exports=r},{}],376:[function(e,t,n){function r(e,t,n,r,i,s,o){var u=l(e),c=u.length,p=l(t),d=p.length;if(c!=d&&!i)return!1;for(var f=i,h=-1;++h<c;){var m=u[h],g=i?m in t:a.call(t,m);if(g){var y=e[m],v=t[m];g=void 0,r&&(g=i?r(v,y,m):r(y,v,m)),"undefined"==typeof g&&(g=y&&y===v||n(y,v,r,i,s,o))}if(!g)return!1;f||(f="constructor"==m)}if(!f){var b=e.constructor,x=t.constructor;if(b!=x&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof x&&x instanceof x))return!1}return!0}var l=e("../object/keys"),i=Object.prototype,a=i.hasOwnProperty;t.exports=r},{"../object/keys":408}],377:[function(e,t,n){function r(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=r},{}],378:[function(e,t,n){function r(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&i.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var l=Object.prototype,i=l.hasOwnProperty;t.exports=r},{}],379:[function(e,t,n){function r(e,t,n){var r=e.constructor;switch(t){case c:return l(e);case i:case a:return new r(+e);case p:case d:case f:case h:case m:case g:case y:case v:case b:var E=e.buffer;return new r(n?l(E):E,e.byteOffset,e.length);case s:case u:return new r(e);case o:var _=new r(e.source,x.exec(e));_.lastIndex=e.lastIndex}return _}var l=e("./bufferClone"),i="[object Boolean]",a="[object Date]",s="[object Number]",o="[object RegExp]",u="[object String]",c="[object ArrayBuffer]",p="[object Float32Array]",d="[object Float64Array]",f="[object Int8Array]",h="[object Int16Array]",m="[object Int32Array]",g="[object Uint8Array]",y="[object Uint8ClampedArray]",v="[object Uint16Array]",b="[object Uint32Array]",x=/\w*$/;t.exports=r},{"./bufferClone":363}],380:[function(e,t,n){function r(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}t.exports=r},{}],381:[function(e,t,n){function r(e,t){return e=+e,t=null==t?l:t,e>-1&&e%1==0&&t>e}var l=Math.pow(2,53)-1;t.exports=r},{}],382:[function(e,t,n){function r(e,t,n){if(!a(n))return!1;var r=typeof t;if("number"==r)var s=n.length,o=i(s)&&l(t,s);else o="string"==r&&t in n;if(o){var u=n[t];return e===e?e===u:u!==u}return!1}var l=e("./isIndex"),i=e("./isLength"),a=e("../lang/isObject");t.exports=r},{"../lang/isObject":398,"./isIndex":381,"./isLength":383}],383:[function(e,t,n){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&l>=e}var l=Math.pow(2,53)-1;t.exports=r},{}],384:[function(e,t,n){function r(e){return!!e&&"object"==typeof e}t.exports=r},{}],385:[function(e,t,n){function r(e){return e===e&&(0===e?1/e>0:!l(e))}var l=e("../lang/isObject");t.exports=r},{"../lang/isObject":398}],386:[function(e,t,n){function r(e){var t;if(!i(e)||u.call(e)!=a||!o.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t)))return!1;var n;return l(e,function(e,t){n=t}),"undefined"==typeof n||o.call(e,n)}var l=e("./baseForIn"),i=e("./isObjectLike"),a="[object Object]",s=Object.prototype,o=s.hasOwnProperty,u=s.toString;t.exports=r},{"./baseForIn":341,"./isObjectLike":384}],387:[function(e,t,n){function r(e){for(var t=o(e),n=t.length,r=n&&e.length,c=r&&s(r)&&(i(e)||u.nonEnumArgs&&l(e)),d=-1,f=[];++d<n;){var h=t[d];(c&&a(h,r)||p.call(e,h))&&f.push(h)}return f}var l=e("../lang/isArguments"),i=e("../lang/isArray"),a=e("./isIndex"),s=e("./isLength"),o=e("../object/keysIn"),u=e("../support"),c=Object.prototype,p=c.hasOwnProperty;t.exports=r},{"../lang/isArguments":391,"../lang/isArray":392,"../object/keysIn":409,"../support":413,"./isIndex":381,"./isLength":383}],388:[function(e,t,n){function r(e,t){for(var n,r=-1,l=e.length,i=-1,a=[];++r<l;){var s=e[r],o=t?t(s,r,e):s;r&&n===o||(n=o,a[++i]=s)}return a}t.exports=r},{}],389:[function(e,t,n){function r(e){return l(e)?e:Object(e)}var l=e("../lang/isObject");t.exports=r},{"../lang/isObject":398}],390:[function(e,t,n){function r(e,t,n){return t="function"==typeof t&&i(t,n,1),l(e,!0,t)}var l=e("../internal/baseClone"),i=e("../internal/bindCallback");t.exports=r},{"../internal/baseClone":334,"../internal/bindCallback":362}],391:[function(e,t,n){function r(e){var t=i(e)?e.length:void 0;return l(t)&&o.call(e)==a}var l=e("../internal/isLength"),i=e("../internal/isObjectLike"),a="[object Arguments]",s=Object.prototype,o=s.toString;t.exports=r},{"../internal/isLength":383,"../internal/isObjectLike":384}],392:[function(e,t,n){var r=e("../internal/isLength"),l=e("./isNative"),i=e("../internal/isObjectLike"),a="[object Array]",s=Object.prototype,o=s.toString,u=l(u=Array.isArray)&&u,c=u||function(e){return i(e)&&r(e.length)&&o.call(e)==a};t.exports=c},{"../internal/isLength":383,"../internal/isObjectLike":384,"./isNative":396}],393:[function(e,t,n){function r(e){return e===!0||e===!1||l(e)&&s.call(e)==i}var l=e("../internal/isObjectLike"),i="[object Boolean]",a=Object.prototype,s=a.toString;t.exports=r},{"../internal/isObjectLike":384}],394:[function(e,t,n){function r(e){if(null==e)return!0;var t=e.length;return s(t)&&(i(e)||u(e)||l(e)||o(e)&&a(e.splice))?!t:!c(e).length}var l=e("./isArguments"),i=e("./isArray"),a=e("./isFunction"),s=e("../internal/isLength"),o=e("../internal/isObjectLike"),u=e("./isString"),c=e("../object/keys");t.exports=r},{"../internal/isLength":383,"../internal/isObjectLike":384,"../object/keys":408,"./isArguments":391,"./isArray":392,"./isFunction":395,"./isString":401}],395:[function(e,t,n){(function(n){var r=e("../internal/baseIsFunction"),l=e("./isNative"),i="[object Function]",a=Object.prototype,s=a.toString,o=l(o=n.Uint8Array)&&o,u=r(/x/)||o&&!r(o)?function(e){return s.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,n){function r(e){return null==e?!1:c.call(e)==a?p.test(u.call(e)):i(e)&&s.test(e)}var l=e("../string/escapeRegExp"),i=e("../internal/isObjectLike"),a="[object Function]",s=/^\[object .+?Constructor\]$/,o=Object.prototype,u=Function.prototype.toString,c=o.toString,p=RegExp("^"+l(c).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},{"../internal/isObjectLike":384,"../string/escapeRegExp":412}],397:[function(e,t,n){function r(e){return"number"==typeof e||l(e)&&s.call(e)==i}var l=e("../internal/isObjectLike"),i="[object Number]",a=Object.prototype,s=a.toString;t.exports=r},{"../internal/isObjectLike":384}],398:[function(e,t,n){function r(e){var t=typeof e;return"function"==t||!!e&&"object"==t}t.exports=r},{}],399:[function(e,t,n){var r=e("./isNative"),l=e("../internal/shimIsPlainObject"),i="[object Object]",a=Object.prototype,s=a.toString,o=r(o=Object.getPrototypeOf)&&o,u=o?function(e){if(!e||s.call(e)!=i)return!1;var t=e.valueOf,n=r(t)&&(n=o(t))&&o(n);return n?e==n||o(e)==n:l(e)}:l;t.exports=u},{"../internal/shimIsPlainObject":386,"./isNative":396}],400:[function(e,t,n){function r(e){return l(e)&&s.call(e)==i||!1}var l=e("../internal/isObjectLike"),i="[object RegExp]",a=Object.prototype,s=a.toString;t.exports=r},{"../internal/isObjectLike":384}],401:[function(e,t,n){function r(e){return"string"==typeof e||l(e)&&s.call(e)==i}var l=e("../internal/isObjectLike"),i="[object String]",a=Object.prototype,s=a.toString;t.exports=r},{"../internal/isObjectLike":384}],402:[function(e,t,n){function r(e){return i(e)&&l(e.length)&&!!j[A.call(e)]}var l=e("../internal/isLength"),i=e("../internal/isObjectLike"),a="[object Arguments]",s="[object Array]",o="[object Boolean]",u="[object Date]",c="[object Error]",p="[object Function]",d="[object Map]",f="[object Number]",h="[object Object]",m="[object RegExp]",g="[object Set]",y="[object String]",v="[object WeakMap]",b="[object ArrayBuffer]",x="[object Float32Array]",E="[object Float64Array]",_="[object Int8Array]",w="[object Int16Array]",S="[object Int32Array]",I="[object Uint8Array]",k="[object Uint8ClampedArray]",T="[object Uint16Array]",C="[object Uint32Array]",j={};j[x]=j[E]=j[_]=j[w]=j[S]=j[I]=j[k]=j[T]=j[C]=!0,j[a]=j[s]=j[b]=j[o]=j[u]=j[c]=j[p]=j[d]=j[f]=j[h]=j[m]=j[g]=j[y]=j[v]=!1;var M=Object.prototype,A=M.toString;t.exports=r},{"../internal/isLength":383,"../internal/isObjectLike":384}],403:[function(e,t,n){function r(e){return l(e,i(e))}var l=e("../internal/baseCopy"),i=e("../object/keysIn");t.exports=r},{"../internal/baseCopy":336,"../object/keysIn":409}],404:[function(e,t,n){var r=e("../internal/baseAssign"),l=e("../internal/createAssigner"),i=l(r);t.exports=i},{"../internal/baseAssign":332,"../internal/createAssigner":368}],405:[function(e,t,n){var r=e("./assign"),l=e("../internal/assignDefaults"),i=e("../function/restParam"),a=i(function(e){var t=e[0];return null==t?t:(e.push(l),r.apply(void 0,e))});t.exports=a},{"../function/restParam":324,"../internal/assignDefaults":331,"./assign":404}],406:[function(e,t,n){t.exports=e("./assign")},{"./assign":404}],407:[function(e,t,n){function r(e,t){return e?i.call(e,t):!1}var l=Object.prototype,i=l.hasOwnProperty;t.exports=r},{}],408:[function(e,t,n){var r=e("../internal/isLength"),l=e("../lang/isNative"),i=e("../lang/isObject"),a=e("../internal/shimKeys"),s=l(s=Object.keys)&&s,o=s?function(e){if(e)var t=e.constructor,n=e.length;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&n&&r(n)?a(e):i(e)?s(e):[]}:a;t.exports=o},{"../internal/isLength":383,"../internal/shimKeys":387,"../lang/isNative":396,"../lang/isObject":398}],409:[function(e,t,n){function r(e){if(null==e)return[];o(e)||(e=Object(e));var t=e.length;t=t&&s(t)&&(i(e)||u.nonEnumArgs&&l(e))&&t||0;for(var n=e.constructor,r=-1,c="function"==typeof n&&n.prototype===e,d=Array(t),f=t>0;++r<t;)d[r]=r+"";for(var h in e)f&&a(h,t)||"constructor"==h&&(c||!p.call(e,h))||d.push(h);return d}var l=e("../lang/isArguments"),i=e("../lang/isArray"),a=e("../internal/isIndex"),s=e("../internal/isLength"),o=e("../lang/isObject"),u=e("../support"),c=Object.prototype,p=c.hasOwnProperty;t.exports=r},{"../internal/isIndex":381,"../internal/isLength":383,"../lang/isArguments":391,"../lang/isArray":392,"../lang/isObject":398,"../support":413}],410:[function(e,t,n){var r=e("../internal/baseMerge"),l=e("../internal/createAssigner"),i=l(r);t.exports=i},{"../internal/baseMerge":353,"../internal/createAssigner":368}],411:[function(e,t,n){function r(e){return l(e,i(e))}var l=e("../internal/baseValues"),i=e("./keys");t.exports=r},{"../internal/baseValues":361,"./keys":408}],412:[function(e,t,n){function r(e){return e=l(e),e&&a.test(e)?e.replace(i,"\\$&"):e}var l=e("../internal/baseToString"),i=/[.*+?^${}()|[\]\/\\]/g,a=RegExp(i.source);t.exports=r},{"../internal/baseToString":359}],413:[function(e,t,n){(function(e){var n=Object.prototype,r=(r=e.window)&&r.document,l=n.propertyIsEnumerable,i={};!function(e){i.funcDecomp=/\bthis\b/.test(function(){return this}),i.funcNames="string"==typeof Function.name;try{i.dom=11===r.createDocumentFragment().nodeType}catch(t){i.dom=!1}try{i.nonEnumArgs=!l.call(arguments,1)}catch(t){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,n){function r(e){return function(){return e}}t.exports=r},{}],415:[function(e,t,n){function r(e){return e}t.exports=r},{}],416:[function(e,t,n){(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,r,l){return a(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 a(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 s(t,n).match(e):!1}function s(e,t){if(!(this instanceof s))return new s(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(S)}),this.debug(this.pattern,n),n=n.map(function(e,t,n){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 c(e,t){if(t||(t=this instanceof s?this.options:{}),e="undefined"==typeof e?this.pattern:e,"undefined"==typeof e)throw new Error("undefined pattern");return t.nobrace||!e.match(/\{.*\}/)?[e]:v(e)}function p(e,t){function n(){if(i){switch(i){case"*":s+=x,o=!0;break;case"?":s+=b,o=!0;break;default:s+="\\"+i}g.debug("clearStateChar %j %j",i,s),i=!1}}var r=this.options;if(!r.noglobstar&&"**"===e)return y;if(""===e)return"";for(var l,i,a,s="",o=!!r.nocase,u=!1,c=[],p=!1,d=-1,f=-1,m="."===e.charAt(0)?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",g=this,v=0,E=e.length;E>v&&(a=e.charAt(v));v++)if(this.debug("%s %s %s %j",e,v,s,a),u&&w[a])s+="\\"+a,u=!1;else switch(a){case"/":return!1;case"\\":n(),u=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",e,v,s,a),p){this.debug(" in class"),"!"===a&&v===f+1&&(a="^"),s+=a;continue}g.debug("call clearStateChar %j",i),n(),i=a,r.noext&&n();continue;case"(":if(p){s+="(";continue}if(!i){s+="\\(";continue}l=i,c.push({type:l,start:v-1,reStart:s.length}),s+="!"===i?"(?:(?!":"(?:",this.debug("plType %j %j",i,s),i=!1;continue;case")":if(p||!c.length){s+="\\)";continue}switch(n(),o=!0,s+=")",l=c.pop().type){case"!":s+="[^/]*?)";break;case"?":case"+":case"*":s+=l;case"@":}continue;case"|":if(p||!c.length||u){s+="\\|",u=!1;continue}n(),s+="|";continue;case"[":if(n(),p){s+="\\"+a;continue}p=!0,f=v,d=s.length,s+=a;continue;case"]":if(v===f+1||!p){s+="\\"+a,u=!1;continue}if(p){var _=e.substring(f+1,v);try{new RegExp("["+_+"]")}catch(S){var k=this.parse(_,I);s=s.substr(0,d)+"\\["+k[0]+"\\]",o=o||k[1],p=!1;continue}}o=!0,p=!1,s+=a;continue;default:n(),u?u=!1:!w[a]||"^"===a&&p||(s+="\\"),s+=a}if(p){var _=e.substr(f+1),k=this.parse(_,I);s=s.substr(0,d)+"\\["+k[0],o=o||k[1]}for(var T;T=c.pop();){var C=s.slice(T.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 j="*"===T.type?x:"?"===T.type?b:"\\"+T.type;o=!0,s=s.slice(0,T.reStart)+j+"\\("+C}n(),u&&(s+="\\\\");var M=!1;switch(s.charAt(0)){case".":case"[":case"(":M=!0}if(""!==s&&o&&(s="(?=.)"+s),M&&(s=m+s),t===I)return[s,o];if(!o)return h(e);var A=r.nocase?"i":"",O=new RegExp("^"+s+"$",A);return O._glob=e,O._src=s,O}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(S),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,a=r.length;a>i;i++){var s=r[i],o=e;n.matchBase&&1===s.length&&(o=[l]);var u=this.matchOne(o,s,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=a,a.Minimatch=s;var g=!1;"undefined"!=typeof n&&"win32"===n.platform&&(g=!0);var y=a.GLOBSTAR=s.GLOBSTAR={},v=e("brace-expansion"),b="[^/]",x=b+"*?",E="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_="(?:(?!(?:\\/|^)\\.).)*?",w=r("().*{}+?[]^$\\!"),S=/\/+/;a.filter=l,a.defaults=function(e){if(!e||!Object.keys(e).length)return a;var t=a,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},s.defaults=function(e){return e&&Object.keys(e).length?a.defaults(e).Minimatch:s},s.prototype.debug=function(){},s.prototype.make=o,s.prototype.parseNegate=u,a.braceExpand=function(e,t){return c(e,t)},s.prototype.braceExpand=c,s.prototype.parse=p;var I={};a.makeRe=function(e,t){return new s(e,t||{}).makeRe()},s.prototype.makeRe=d,a.match=function(e,t,n){n=n||{};var r=new s(t,n);return e=e.filter(function(e){return r.match(e)}),r.options.nonull&&!e.length&&e.push(t),e},s.prototype.match=f,s.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,a=e.length,s=t.length;a>l&&s>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 c=l,p=i+1;if(p===s){for(this.debug("** at the end");a>l;l++)if("."===e[l]||".."===e[l]||!r.dot&&"."===e[l].charAt(0))return!1;return!0}e:for(;a>c;){var d=e[c];if(this.debug("\nglobstar while",e,c,t,p,d),this.matchOne(e.slice(c),t.slice(p),n))return this.debug("globstar found match!",c,a,d),!0;if("."===d||".."===d||!r.dot&&"."===d.charAt(0)){this.debug("dot detected!",e,c,t,p);break e}this.debug("globstar swallow a segment, and continue"),c++}return n&&(this.debug("\n>>> no match, partial?",e,c,t,p),c===a)?!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===a&&i===s)return!0;if(l===a)return n;if(i===s){var h=l===a-1&&""===e[l];return h}throw new Error("wtf?")}}).call(this,e("_process"))},{_process:183,"brace-expansion":417}],417:[function(e,t,n){function r(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function l(e){return e.split("\\\\").join(m).split("\\{").join(g).split("\\}").join(y).split("\\,").join(v).split("\\.").join(b)}function i(e){return e.split(m).join("\\").split(g).join("{").split(y).join("}").split(v).join(",").split(b).join(".")}function a(e){if(!e)return[""];var t=[],n=h("{","}",e);if(!n)return e.split(",");var r=n.pre,l=n.body,i=n.post,s=r.split(",");s[s.length-1]+="{"+l+"}";var o=a(i);return i.length&&(s[s.length-1]+=o.shift(),s.push.apply(s,o)),t.push.apply(t,s),t}function s(e){return e?d(l(e),!0).map(i):[]}function o(e){return"{"+e+"}"}function u(e){return/^-?0\d/.test(e)}function c(e,t){return t>=e}function p(e,t){return e>=t}function d(e,t){var n=[],l=h("{","}",e);if(!l||/\$$/.test(l.pre))return[e];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(l.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(l.body),m=i||s,g=/^(.*,)+(.+)?$/.test(l.body);if(!m&&!g)return l.post.match(/,.*}/)?(e=l.pre+"{"+l.body+y+l.post,d(e)):[e];var v;if(m)v=l.body.split(/\.\./);else if(v=a(l.body),1===v.length&&(v=d(v[0],!1).map(o),1===v.length)){var b=l.post.length?d(l.post,!1):[""];return b.map(function(e){return l.pre+v[0]+e})}var x,E=l.pre,b=l.post.length?d(l.post,!1):[""];if(m){var _=r(v[0]),w=r(v[1]),S=Math.max(v[0].length,v[1].length),I=3==v.length?Math.abs(r(v[2])):1,k=c,T=_>w;T&&(I*=-1,k=p);var C=v.some(u);x=[];for(var j=_;k(j,w);j+=I){var M;if(s)M=String.fromCharCode(j),"\\"===M&&(M="");else if(M=String(j),C){var A=S-M.length;if(A>0){var O=new Array(A+1).join("0");M=0>j?"-"+O+M.slice(1):O+M}}x.push(M)}}else x=f(v,function(e){return d(e,!1)});for(var L=0;L<x.length;L++)for(var P=0;P<b.length;P++){var N=E+x[L]+b[P];(!t||m||N)&&n.push(N)}return n}var f=e("concat-map"),h=e("balanced-match");t.exports=s;var m="\x00SLASH"+Math.random()+"\x00",g="\x00OPEN"+Math.random()+"\x00",y="\x00CLOSE"+Math.random()+"\x00",v="\x00COMMA"+Math.random()+"\x00",b="\x00PERIOD"+Math.random()+"\x00"},{"balanced-match":418,"concat-map":419}],418:[function(e,t,n){function r(e,t,n){for(var l=0,i={},a=!1,s=0;s<n.length;s++)if(e==n.substr(s,e.length))"start"in i||(i.start=s),l++;else if(t==n.substr(s,t.length)&&"start"in i&&(a=!0,l--,!l))return i.end=s,i.pre=n.substr(0,i.start),i.body=i.end-i.start>1?n.substring(i.start+e.length,i.end):"",i.post=n.slice(i.end+t.length),i;if(l&&a){var o=i.start+e.length;return i=r(e,t,n.substr(o)),i&&(i.start+=o,i.end+=o,i.pre=n.slice(0,o)+i.pre),i}}t.exports=r},{}],419:[function(e,t,n){t.exports=function(e,t){for(var n=[],l=0;l<e.length;l++){var i=t(e[l],l);r(i)?n.push.apply(n,i):n.push(i)}return n};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],420:[function(e,t,n){(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(p)try{p.call(c,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(c,e):(g.prototype=e||null,new g)}function a(){do var e=s(m.call(h.call(y(),36),2));while(f.call(v,e));return v[e]=e}function s(e){var t={};return t[e]=!0,Object.keys(t)[0]}function o(e){return i(null)}function u(e){function t(t){function n(n,r){return n===s?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](s)}var l=a(),s=i(null);return e=e||o,n.forget=function(e){f.call(e,l)&&e[l](s,!0)},n}var c=Object,p=Object.defineProperty,d=Object.create;l(p),l(d);var f=l(Object.prototype.hasOwnProperty),h=l(Number.prototype.toString),m=l(String.prototype.slice),g=function(){},y=Math.random,v=i(null);r(n,"makeUniqueKey",a);var b=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function(e){for(var t=b(e),n=0,r=0,l=t.length;l>n;++n)f.call(v,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),p.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 c.literal(-1)}function i(e){return p.BreakStatement.check(e)||p.ContinueStatement.check(e)||p.ReturnStatement.check(e)||p.ThrowStatement.check(e)}function a(e){return new Error("all declarations should have been transformed into assignments before the Exploder began its work: "+JSON.stringify(e))}function s(e){var t=e.type;return"normal"===t?!m.call(e,"target"):"break"===t||"continue"===t?!m.call(e,"value")&&p.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"),c=(u.builtInTypes.array,u.builders),p=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){p.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){p.Expression.check(e)&&(e=c.expressionStatement(e)),p.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 c.expressionStatement(c.assignmentExpression("=",e,t))},g.contextProperty=function(e,t){return c.memberExpression(this.contextId,t?c.literal(e):c.identifier(e),!!t)};var y={prev:!0,next:!0,sent:!0,rval:!0};g.isVolatileContextProperty=function(e){if(p.MemberExpression.check(e)){if(e.computed)return!0;if(p.Identifier.check(e.object)&&p.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){p.Expression.assert(e.value),this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))},g.clearPendingException=function(e,t){p.Literal.assert(e);var n=c.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(c.breakStatement())},g.jumpIf=function(e,t){p.Expression.assert(e),p.Literal.assert(t),this.emit(c.ifStatement(e,c.blockStatement([this.assign(this.contextProperty("next"),t),c.breakStatement()])))},g.jumpIfNot=function(e,t){p.Expression.assert(e),p.Literal.assert(t);var n;n=p.UnaryExpression.check(e)&&"!"===e.operator?e.argument:c.unaryExpression("!",e),this.emit(c.ifStatement(n,c.blockStatement([this.assign(this.contextProperty("next"),t),c.breakStatement()])))};var v=0;g.makeTempVar=function(){return this.contextProperty("t"+v++)},g.getContextFunction=function(e){var t=c.functionExpression(e||null,[this.contextId],c.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,a){t.marked.hasOwnProperty(a)&&(n.push(c.switchCase(c.literal(a),e=[])),r=!1),r||(e.push(l),i(l)&&(r=!0))}),this.finalLoc.value=this.listing.length,n.push(c.switchCase(this.finalLoc,[]),c.switchCase(c.literal("end"),[c.returnStatement(c.callExpression(this.contextProperty("stop"),[]))])),c.whileStatement(c.literal(1),c.switchStatement(c.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),n))},g.getTryLocsList=function(){if(0===this.tryEntries.length)return null;var e=0;return c.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),c.arrayExpression(i)}))},g.explode=function(e,t){o.ok(e instanceof u.NodePath);var n=e.value,r=this;if(p.Node.assert(n),p.Statement.check(n))return r.explodeStatement(e);if(p.Expression.check(n))return r.explodeExpression(e,t);if(p.Declaration.check(n))throw a(n);switch(n.type){case"Program":return e.get("body").map(r.explodeStatement,r);case"VariableDeclarator":throw a(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(p.Statement.assert(n),t?p.Identifier.assert(t):t=null,p.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 a=l(),i=l();r.mark(a),r.jumpIfNot(r.explodeExpression(e.get("test")),i),r.leapManager.withEntry(new d.LoopEntry(i,a,t),function(){r.explodeStatement(e.get("body"))}),r.jump(a),r.mark(i);break;case"DoWhileStatement":var s=l(),m=l(),i=l();r.mark(s),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")),s),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":p.Identifier.assert(n.left);var g=l(),i=l(),v=r.makeTempVar();r.emitAssign(v,c.callExpression(h.runtimeProperty("keys"),[r.explodeExpression(e.get("right"))])),r.mark(g);var b=r.makeTempVar();r.jumpIf(c.memberExpression(c.assignmentExpression("=",b,c.callExpression(v,[])),c.identifier("done"),!1),i),r.emitAssign(n.left,c.memberExpression(b,c.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,w=[],S=n.cases||[],I=S.length-1;I>=0;--I){var k=S[I];p.SwitchCase.assert(k),k.test?_=c.conditionalExpression(c.binaryExpression("===",x,k.test),w[I]=l(),_):w[I]=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(w[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 T=n.alternate&&l(),i=l();r.jumpIfNot(r.explodeExpression(e.get("test")),T||i),r.explodeStatement(e.get("consequent")),T&&(r.jump(i),r.mark(T),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 j=C&&l(),M=j&&new d.CatchEntry(j,C.param),A=n.finalizer&&l(),O=A&&new d.FinallyEntry(A,i),L=new d.TryEntry(r.getUnmarkedCurrentLoc(),M,O);r.tryEntries.push(L),r.updateContextPrevLoc(L.firstLoc),r.leapManager.withEntry(L,function(){if(r.explodeStatement(e.get("block")),j){r.jump(A?A:i),r.updateContextPrevLoc(r.mark(j));var t=e.get("handler","body"),n=r.makeTempVar();r.clearPendingException(L.firstLoc,n);var l=t.scope,a=C.param.name;p.CatchClause.assert(l.node),o.strictEqual(l.lookup(a),l),u.visit(t,{visitIdentifier:function(e){return h.isReference(e,a)&&e.scope.lookup(a)===l?n:void this.traverse(e)},visitFunction:function(e){return e.scope.declares(a)?!1:void this.traverse(e)}}),r.leapManager.withEntry(M,function(){r.explodeStatement(t)})}A&&(r.updateContextPrevLoc(r.mark(A)),r.leapManager.withEntry(O,function(){r.explodeStatement(e.get("finalizer"))}),r.emit(c.returnStatement(c.callExpression(r.contextProperty("finish"),[O.firstLoc]))))}),r.mark(i);break;case"ThrowStatement":r.emit(c.throwStatement(r.explodeExpression(e.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(n.type))}},g.emitAbruptCompletion=function(e){s(e)||o.ok(!1,"invalid completion record: "+JSON.stringify(e)),o.notStrictEqual(e.type,"normal","normal completions are not abrupt");var t=[c.literal(e.type)];"break"===e.type||"continue"===e.type?(p.Literal.assert(e.target),t[1]=e.target):("return"===e.type||"throw"===e.type)&&e.value&&(p.Expression.assert(e.value),t[1]=e.value),this.emit(c.returnStatement(c.callExpression(this.contextProperty("abrupt"),t)))},g.getUnmarkedCurrentLoc=function(){return c.literal(this.listing.length)},g.updateContextPrevLoc=function(e){e?(p.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 p.Expression.assert(e),t?void s.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=s.explodeExpression(t,n);return n||(e||d&&(s.isVolatileContextProperty(r)||f.hasSideEffects(r)))&&(r=s.emitAssign(e||s.makeTempVar(),r)),r}o.ok(e instanceof u.NodePath);var i=e.value;if(!i)return i;p.Expression.assert(i);var a,s=this;if(!f.containsLeap(i))return n(i);var d=f.containsLeap.onlyChildren(i);switch(i.type){case"MemberExpression":return n(c.memberExpression(s.explodeExpression(e.get("object")),i.computed?r(null,e.get("property")):i.property,i.computed));case"CallExpression":var h=e.get("callee"),m=s.explodeExpression(h);return!p.MemberExpression.check(h.node)&&p.MemberExpression.check(m)&&(m=c.sequenceExpression([c.literal(0),m])),n(c.callExpression(m,e.get("arguments").map(function(e){return r(null,e)})));case"NewExpression":return n(c.newExpression(r(null,e.get("callee")),e.get("arguments").map(function(e){return r(null,e)})));case"ObjectExpression":return n(c.objectExpression(e.get("properties").map(function(e){return c.property(e.value.kind,e.value.key,r(null,e.get("value")))})));case"ArrayExpression":return n(c.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?a=s.explodeExpression(e,t):s.explodeExpression(e,!0)}),a;case"LogicalExpression":var y=l();t||(a=s.makeTempVar());var v=r(a,e.get("left"));return"&&"===i.operator?s.jumpIfNot(v,y):(o.strictEqual(i.operator,"||"),s.jumpIf(v,y)),r(a,e.get("right"),t),s.mark(y),a;case"ConditionalExpression":var b=l(),y=l(),x=s.explodeExpression(e.get("test"));return s.jumpIfNot(x,b),t||(a=s.makeTempVar()),r(a,e.get("consequent"),t),s.jump(y),s.mark(b),r(a,e.get("alternate"),t),s.mark(y),a;case"UnaryExpression":return n(c.unaryExpression(i.operator,s.explodeExpression(e.get("argument")),!!i.prefix));case"BinaryExpression":return n(c.binaryExpression(i.operator,r(null,e.get("left")),r(null,e.get("right"))));case"AssignmentExpression":return n(c.assignmentExpression(i.operator,s.explodeExpression(e.get("left")),s.explodeExpression(e.get("right"))));case"UpdateExpression":return n(c.updateExpression(i.operator,s.explodeExpression(e.get("argument")),i.prefix));case"YieldExpression":var y=l(),E=i.argument&&s.explodeExpression(e.get("argument"));if(E&&i.delegate){var a=s.makeTempVar();return s.emit(c.returnStatement(c.callExpression(s.contextProperty("delegateYield"),[E,c.literal(a.property.name),y]))),s.mark(y),a}return s.emitAssign(s.contextProperty("next"),y),s.emit(c.returnStatement(E||null)),s.mark(y),s.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,a=l.builders,s=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(a.assignmentExpression("=",e.id,e.init)):t&&r.push(e.id)}),0===r.length?null:1===r.length?r[0]:a.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?a.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,a.expressionStatement(a.assignmentExpression("=",t.id,a.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(e){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){s.call(o,e)||u.push(a.variableDeclarator(n[e],null))}),0===u.length?null:a.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 a(e){r.call(this),h.Literal.assert(e),this.breakLoc=e}function s(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 c(e,t){r.call(this),h.Literal.assert(e),h.Identifier.assert(t),this.breakLoc=e,this.label=t}function p(t){d.ok(this instanceof p);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(a,r),n.SwitchEntry=a,m(s,r),n.TryEntry=s,m(o,r),n.CatchEntry=o,m(u,r),n.FinallyEntry=u,m(c,r),n.LabeledEntry=c;var g=p.prototype;n.LeapManager=p,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 c))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||(s.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 a.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(c,r.type)?!1:u.call(t,r.type)?!0:n(r)}return r.onlyChildren=n,r}var l=e("assert"),i=e("private").makeAccessor(),a=e("ast-types"),s=a.builtInTypes.array,o=a.namedTypes,u=Object.prototype.hasOwnProperty,c={FunctionExpression:!0},p={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)&&(p[f]=d[f]);n.hasSideEffects=r("hasSideEffects",p),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,a=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)a.call(t,l)&&!a.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,a=(r.builtInTypes.array,r.builtInTypes.object,r.NodePath),s=e("./hoist").hoist,o=e("./emit").Emitter,u=e("./util").runtimeProperty;n.transform=function(e,t){t=t||{};var n=e instanceof a?e:new a(e);return c.visit(n,t),e=n.value,t.madeChanges=c.wasChangeReported(),e};var c=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&&p.visit(e.get("body"));var r=t.id||(t.id=e.scope.parent.declareTemporary("callee$")),a=[],c=e.value.body;c.body=c.body.filter(function(e){return e&&null!=e._blockHoist?(a.push(e),!1):!0});var d=i.identifier(t.id.name+"$"),f=e.scope.declareTemporary("context$"),h=s(e),m=new o(f);m.explode(e.get("body")),h&&h.declarations.length>0&&a.push(h);var g=[m.getContextFunction(d),n?i.literal(null):r,i.thisExpression()],y=m.getTryLocsList();y&&g.push(y);var v=i.callExpression(u(n?"async":"wrap"),g);if(a.push(i.returnStatement(v)),t.body=i.blockStatement(a),t.body._declarations=c._declarations,n)return void(t.async=!1);if(!l.FunctionDeclaration.check(t))return l.FunctionExpression.assert(t),i.callExpression(u("mark"),[t]);for(var b=e.parent;b&&!l.BlockStatement.check(b.value)&&!l.Program.check(b.value);)b=b.parent;if(b){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=b.get("body");E.value.length}E.push(x)}}}}),p=r.PathVisitor.fromMethodsObject({visitFunction:function(e){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,n){(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 a(n,r)}function l(){e("./runtime")}{var i=(e("assert"),e("path")),a=(e("fs"),e("through")),s=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=s}).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&&!p.paused;){var e=u.shift();if(null===e)return p.emit("end");p.emit("data",e)}}function a(){p.writable=!1,t.call(p),!p.readable&&p.autoDestroy&&p.destroy()}e=e||function(e){this.queue(e)},t=t||function(){this.queue(null)};var s=!1,o=!1,u=[],c=!1,p=new i;return p.readable=p.writable=!0,p.paused=!1,p.autoDestroy=!(n&&n.autoDestroy===!1),p.write=function(t){return e.call(this,t),!p.paused},p.queue=p.push=function(e){return c?p:(null==e&&(c=!0),u.push(e),l(),p)},p.on("end",function(){p.readable=!1,!p.writable&&p.autoDestroy&&r.nextTick(function(){p.destroy()})}),p.end=function(e){return s?void 0:(s=!0,arguments.length&&p.write(e),a(),p)},p.destroy=function(){return o?void 0:(o=!0,s=!0,u.length=0,p.writable=p.readable=!1,p.emit("close"),p)},p.pause=function(){return p.paused?void 0:(p.paused=!0,p)},p.resume=function(){return p.paused&&(p.paused=!1,p.emit("resume")),l(),p.paused||p.emit("drain"),p},p}var i=e("stream");n=t.exports=l,l.through=l}).call(this,e("_process"))},{_process:183,stream:195}],430:[function(e,t,n){(function(e){!function(e){"use strict";function n(e,t,n,r){return new a(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 a(e,t,n,l){ function i(t,l){if(o===b)throw new Error("Generator is already running");if(o===x)return p();for(;;){var i=s.delegate;if(i){var a=r(i.iterator[t],i.iterator,l);if("throw"===a.type){s.delegate=null,t="throw",l=a.arg;continue}t="next",l=d;var u=a.arg;if(!u.done)return o=v,u;s[i.resultName]=u.value,s.next=i.nextLoc,s.delegate=null}if("next"===t){if(o===y&&"undefined"!=typeof l)throw new TypeError("attempt to send "+JSON.stringify(l)+" to newborn generator");o===v?s.sent=l:delete s.sent}else if("throw"===t){if(o===y)throw o=x,l;s.dispatchException(l)&&(t="next",l=d)}else"return"===t&&s.abrupt("return",l);o=b;var a=r(e,n,s);if("normal"===a.type){o=s.done?x:v;var u={value:a.arg,done:s.done};if(a.arg!==E)return u;s.delegate&&"next"===t&&(l=d)}else"throw"===a.type&&(o=x,"next"===t?s.dispatchException(a.arg):l=a.arg)}}var a=t?Object.create(t.prototype):this,s=new u(l),o=y;return a.next=i.bind(a,"next"),a["throw"]=i.bind(a,"throw"),a["return"]=i.bind(a,"return"),a}function s(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(s,this),this.reset()}function c(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:p}}function p(){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",v="suspendedYield",b="executing",x="completed",E={},_=i.prototype=a.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(a,s){function o(e){var t=r(this,null,e);if("throw"===t.type)return void s(t.arg);var n=t.arg;n.done?a(n.value):Promise.resolve(n.value).then(c,p)}var u=n(e,t,l,i),c=o.bind(u.next),p=o.bind(u["throw"]);c()})},_[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=c,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 a=f.call(l,"catchLoc"),s=f.call(l,"finallyLoc");if(a&&s){if(this.prev<l.catchLoc)return t(l.catchLoc,!0);if(this.prev<l.finallyLoc)return t(l.finallyLoc)}else if(a){if(this.prev<l.catchLoc)return t(l.catchLoc,!0)}else{if(!s)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:c(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,n){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,a="object"==typeof n&&n&&n.exports==i&&n,s="object"==typeof t&&t;(s.global===s||s.window===s)&&(l=s);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,c=56319,p=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)},v=h.toString,b=function(e){return"[object Array]"==v.call(e)},x=function(e){return"number"==typeof e||"[object Number]"==v.call(e)},E="0000",_=function(e,t){var n=String(e);return n.length<t?(E+n).slice(-t):n},w=function(e){return Number(e).toString(16).toUpperCase()},S=[].slice,I=function(e){for(var t,n=-1,r=e.length,l=r-1,i=[],a=!0,s=0;++n<r;)if(t=e[n],a)i.push(t),s=t,a=!1;else if(t==s+1){if(n!=l){s=t;continue}a=!0,i.push(t+1)}else i.push(s+1,t),s=t;return a||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},T=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,a=e.length;if(0>t||t>1114111)throw RangeError(o.codePointRange);for(;a>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},j=function(e,t){for(var n,r,l=0,i=e.slice(),a=t.length;a>l;)n=t[l],r=t[l+1]-1,i=n==r?C(i,n):A(i,n,r),l+=2;return i},M=function(e,t){for(var n,r,l=0,i=e.slice(),a=t.length;a>l;)n=t[l],r=t[l+1]-1,i=n==r?k(i,n):T(i,n,r),l+=2;return i},A=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,a=!1,s=e.length;s>i;){if(r=e[i],l=e[i+1],a){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,a=!0):r>=t&&n+1>=l&&(e[i]=t,e[i+1]=n+1,a=!0)}i+=2}return a||e.push(t,n+1),e},O=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],O(e,n)&&i.push(n),++r;return I(i)},P=function(e){return!e.length},N=function(e){return 2==e.length&&e[0]+1==e[1]},D=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},R=Math.floor,F=function(e){return parseInt(R((e-65536)/1024)+u,10)},B=function(e){return parseInt((e-65536)%1024+p,10)},U=String.fromCharCode,$=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?"\\"+U(e):e>=32&&126>=e?U(e):255>=e?"\\x"+_(w(e),2):"\\u"+_(w(e),4)},V=function(e){var t,n=e.length,r=e.charCodeAt(0);return r>=u&&c>=r&&n>1?(t=e.charCodeAt(1),1024*(r-u)+t-p+65536):r},q=function(e){var t,n,r="",l=0,i=e.length;if(N(e))return $(e[0]);for(;i>l;)t=e[l],n=e[l+1]-1,r+=t==n?$(t):t+1==n?$(t)+$(n):$(t)+"-"+$(n),l+=2;return"["+r+"]"},H=function(e){for(var t,n,r=[],l=[],i=[],a=[],s=0,o=e.length;o>s;)t=e[s],n=e[s+1]-1,u>t?(u>n&&i.push(t,n+1),n>=u&&c>=n&&(i.push(t,u),r.push(u,n+1)),n>=p&&d>=n&&(i.push(t,u),r.push(u,c+1),l.push(p,n+1)),n>d&&(i.push(t,u),r.push(u,c+1),l.push(p,d+1),65535>=n?i.push(d+1,n+1):(i.push(d+1,65536),a.push(65536,n+1)))):t>=u&&c>=t?(n>=u&&c>=n&&r.push(t,n+1),n>=p&&d>=n&&(r.push(t,c+1),l.push(p,n+1)),n>d&&(r.push(t,c+1),l.push(p,d+1),65535>=n?i.push(d+1,n+1):(i.push(d+1,65536),a.push(65536,n+1)))):t>=p&&d>=t?(n>=p&&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),a.push(65536,n+1)))):t>d&&65535>=t?65535>=n?i.push(t,n+1):(i.push(t,65536),a.push(65536,n+1)):a.push(t,n+1),s+=2;return{loneHighSurrogates:r,loneLowSurrogates:l,bmp:i,astral:a}},G=function(e){for(var t,n,r,l,i,a,s=[],o=[],u=!1,c=-1,p=e.length;++c<p;)if(t=e[c],n=e[c+1]){for(r=t[0],l=t[1],i=n[0],a=n[1],o=l;i&&r[0]==i[0]&&r[1]==i[1];)o=N(a)?C(o,a[0]):A(o,a[0],a[1]-1),++c,t=e[c],r=t[0],l=t[1],n=e[c+1],i=n&&n[0],a=n&&n[1],u=!0;s.push([r,u?o:l]),u=!1}else s.push(t);return W(s)},W=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],a=l[1];for(n=t;++n<e.length;){var s=e[n],o=s[1],u=o[0],c=o[1];i==u&&a==c&&(r[0]=N(s[0])?C(r[0],s[0][0]):A(r[0],s[0][0],s[0][1]-1),e.splice(n,1),--n)}}return e},z=function(e){if(!e.length)return[];for(var t,n,r,l,i,a,s=0,o=0,u=0,c=[],f=e.length;f>s;){t=e[s],n=e[s+1]-1,r=F(t),l=B(t),i=F(n),a=B(n);var h=l==p,m=a==d,g=!1;r==i||h&&m?(c.push([[r,i+1],[l,a+1]]),g=!0):c.push([[r,r+1],[l,d+1]]),!g&&i>r+1&&(m?(c.push([[r+1,i+1],[p,a+1]]),g=!0):c.push([[r+1,i],[p,d+1]])),g||c.push([[i,i+1],[p,a+1]]),o=r,u=i,s+=2}return G(c)},X=function(e){var t=[];return y(e,function(e){var n=e[0],r=e[1];t.push(q(n)+q(r))}),t.join("|")},J=function(e,t){var n=[],r=H(e),l=r.loneHighSurrogates,i=r.loneLowSurrogates,a=r.bmp,s=r.astral,o=(!P(r.astral),!P(l)),u=!P(i),c=z(s);return t&&(a=j(a,l),o=!1,a=j(a,i),u=!1),P(a)||n.push(q(a)),c.length&&n.push(X(c)),o&&n.push(q(l)+"(?![\\uDC00-\\uDFFF])"),u&&n.push("(?:[^\\uD800-\\uDBFF]|^)"+q(i)),n.join("|")},Y=function(e){return arguments.length>1&&(e=S.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=j(t.data,e.data),t):(arguments.length>1&&(e=S.call(arguments)),b(e)?(y(e,function(e){t.add(e)}),t):(t.data=C(t.data,x(e)?e:V(e)),t))},remove:function(e){var t=this;return null==e?t:e instanceof Y?(t.data=M(t.data,e.data),t):(arguments.length>1&&(e=S.call(arguments)),b(e)?(y(e,function(e){t.remove(e)}),t):(t.data=k(t.data,x(e)?e:V(e)),t))},addRange:function(e,t){var n=this;return n.data=A(n.data,x(e)?e:V(e),x(t)?t:V(t)),n},removeRange:function(e,t){var n=this,r=x(e)?e:V(e),l=x(t)?t:V(t);return n.data=T(n.data,r,l),n},intersection:function(e){var t=this,n=e instanceof Y?D(e.data):e;return t.data=L(t.data,n),t},contains:function(e){return O(this.data,x(e)?e:V(e))},clone:function(){var e=new Y;return e.data=this.data.slice(0),e},toString:function(e){var t=J(this.data,e?e.bmpOnly:!1);return t.replace(f,"\\0$1")},toRegExp:function(e){return RegExp(this.toString(),e||"")},valueOf:function(){return D(this.data)}}),K.toArray=K.valueOf,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return Y}):i&&!i.nodeType?a?a.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 a="";++l<i;){var s=Number(arguments[l]);if(!isFinite(s)||0>s||s>1114111||T(s)!=s)throw RangeError("Invalid code point: "+s);65535>=s?r.push(s):(s-=65536,e=(s>>10)+55296,t=s%1024+56320,r.push(e,t)),(l+1==i||r.length>n)&&(a+=k.apply(null,r),r.length=0)}return a}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 a(e){var t=e.type;if(a.hasOwnProperty(t)&&"function"==typeof a[t])return a[t](e);throw Error("Invalid node type: "+t)}function s(e){i(e.type,"alternative");var t=e.body,n=t?t.length:0;if(1==n)return b(t[0]);for(var r=-1,l="";++r<n;)l+=b(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"),a(e)}function c(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 p(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"),a(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 a(t[0]);for(var r=-1,l="";++r<n;)0!=r&&(l+="|"),l+=a(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+=a(n[0]);else for(var l=-1;++l<r;)t+=a(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 v(e){return i(e.type,"reference"),"\\"+e.matchIndex}function b(e){return i(e.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value"),a(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,w=E[typeof r]&&r,S=E[typeof n]&&n&&!n.nodeType&&n,I=w&&S&&"object"==typeof t&&t;!I||I.global!==I&&I.window!==I&&I.self!==I||(_=I);var k=String.fromCharCode,T=Math.floor;a.alternative=s,a.anchor=o,a.characterClass=c,a.characterClassEscape=p,a.characterClassRange=d,a.disjunction=h,a.dot=m,a.group=g,a.quantifier=y,a.reference=v,a.value=x,"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return{generate:a}}):w&&S?w.generate=a:_.regjsgen={generate:a}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],435:[function(e,t,n){!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 a(e,t,n,r){return r=r||0,i(e,t,Y-(n.length+r),Y)}function s(e){var t=e[0],n=t.charCodeAt(0);if(J){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 c(e){return n({type:"characterClassEscape",value:e,range:[Y-2,Y]})}function p(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 v(t){t=t||1;var n=e.substring(Y,Y+t);return Y+=t||1,n}function b(e){if(!x(e))throw SyntaxError("character: "+e)}function x(t){return e.indexOf(t,Y)===Y?v(t.length):void 0}function E(){return e[Y]}function _(t){return e.indexOf(t,Y)===Y}function w(t){return e[Y+1]===t}function S(t){var n=e.substring(Y),r=n.match(t);return r&&(r.range=[],r.range[0]=Y,v(r[0].length),r.range[1]=Y),r}function I(){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=T();)t.push(e);return 1===t.length?t[0]:h(t,n,Y)}function T(){if(Y>=e.length||_("|")||_(")"))return null;var t=j();if(t)return t;var n=A();if(!n)throw SyntaxError("Expected atom");var l=M()||!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 a=I();if(!a)throw SyntaxError("Expected disjunction");b(")");var s=d(l,y(a),i,Y);return"normal"==l&&X&&z++,s}function j(){return x("^")?l("start",1):x("$")?l("end",1):x("\\b")?l("boundary",2):x("\\B")?l("not-boundary",2):C("(?=","lookahead","(?!","negativeLookahead")}function M(){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=S(/^\{([0-9]+)\}/))n=parseInt(e[1],10),t=f(n,n,e.range[0],e.range[1]);else if(e=S(/^\{([0-9]+),\}/))n=parseInt(e[1],10),t=f(n,void 0,e.range[0],e.range[1]);else if(e=S(/^\{([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 A(){var e;if(e=S(/^[^^$\\.*+?(){[|]/))return s(e);if(x("."))return u();if(x("\\")){if(e=P(),!e)throw SyntaxError("atomEscape");return e}return(e=B())?e:C("(?:","ignore","(","normal")}function O(e){if(J){var t,r;if("unicodeEscape"==e.kind&&(t=e.codePoint)>=55296&&56319>=t&&_("\\")&&w("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 P(!0)}function P(e){var t;if(t=N())return t;if(e){if(x("b"))return a("singleEscape",8,"\\b");if(x("B"))throw SyntaxError("\\B not possible inside of CharacterClass")}return t=D()}function N(){var e,t;if(e=S(/^(?!0)\d+/)){t=e[0];var n=parseInt(e[0],10);return z>=n?p(e[0]):(W.push(n),v(-e[0].length),(e=S(/^[0-7]{1,3}/))?a("octal",parseInt(e[0],8),e[0],1):(e=s(S(/^[89]/)),r(e,e.range[0]-1)))}return(e=S(/^[0-7]{1,3}/))?(t=e[0],/^0{1,3}$/.test(t)?a("null",0,"0",t.length+1):a("octal",parseInt(t,8),t,1)):(e=S(/^[dDsSwW]/))?c(e[0]):!1}function D(){var e;if(e=S(/^[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 a("singleEscape",t,"\\"+e[0])}return(e=S(/^c([a-zA-Z])/))?a("controlLetter",e[1].charCodeAt(0)%32,e[1],2):(e=S(/^x([0-9a-fA-F]{2})/))?a("hexadecimalEscape",parseInt(e[1],16),e[1],2):(e=S(/^u([0-9a-fA-F]{4})/))?O(a("unicodeEscape",parseInt(e[1],16),e[1],2)):J&&(e=S(/^u\{([0-9a-fA-F]+)\}/))?a("unicodeCodePointEscape",parseInt(e[1],16),e[1],4):F()}function R(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 R(E())?x(t)?a("identifier",8204,t):x(n)?a("identifier",8205,n):null:(e=v(),a("identifier",e.charCodeAt(0),e,1))}function B(){var e,t=Y;return(e=S(/^\[\^/))?(e=U(),b("]"),m(e,!0,t,Y)):x("[")?(e=U(),b("]"),m(e,!1,t,Y)):null}function U(){var e;if(_("]"))return[];if(e=V(),!e)throw SyntaxError("nonEmptyClassRanges");return e}function $(e){var t,n,r;if(_("-")&&!w("]")){if(b("-"),r=H(),!r)throw SyntaxError("classAtom");n=Y;var l=U();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 V(){var e=H();if(!e)throw SyntaxError("classAtom");return _("]")?[e]:$(e)}function q(){var e=H();if(!e)throw SyntaxError("classAtom");return _("]")?e:$(e)}function H(){return x("-")?s("-"):G()}function G(){var e;if(e=S(/^[^\\\]-]/))return s(e[0]);if(x("\\")){if(e=L(),!e)throw SyntaxError("classEscape");return O(e)}}var W=[],z=0,X=!0,J=-1!==(t||"").indexOf("u"),Y=0;e=String(e),""===e&&(e="(?:)");var K=I();if(K.range[1]!==e.length)throw SyntaxError("Could not parse entire input - got stuck: "+e);for(var Q=0;Q<W.length;Q++)if(W[Q]<=z)return Y=0,X=!1,I();return K}var n={parse:e};"undefined"!=typeof t&&t.exports?t.exports=n:window.regjsparser=n}()},{}],436:[function(e,t,n){function r(e){return w?_?m.UNICODE_IGNORE_CASE[e]:m.UNICODE[e]:m.REGULAR[e]}function l(e,t){return y.call(e,t)}function i(e,t){for(var n in t)e[n]=t[n]}function a(e,t){if(t){var n=d(t,"");switch(n.type){case"characterClass":case"group":case"value":break;default:n=s(n,t)}i(e,n)}}function s(e,t){return{type:"group",behavior:"ignore",body:[e],raw:"(?:"+t+")"}}function o(e){return l(h,e)?h[e]:!1}function u(e){{var t=f();e.body.forEach(function(e){switch(e.type){case"value":if(t.add(e.codePoint),_&&w){var n=o(e.codePoint);n&&t.add(n)}break;case"characterClassRange":var l=e.min.codePoint,i=e.max.codePoint;t.addRange(l,i),_&&w&&t.iuAddRange(l,i);break;case"characterClassEscape":t.add(r(e.value));break;default:throw Error("Unknown term type: "+e.type)}})}return e.negative&&(t=(w?v:b).clone().remove(t)),a(e,t.toString()),e}function c(e){switch(e.type){case"dot":a(e,(w?x:E).toString());break;case"characterClass":e=u(e);break;case"characterClassEscape":a(e,r(e.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":e.body=e.body.map(c);break;case"value":var t=e.codePoint,n=f(t);if(_&&w){var l=o(t);l&&n.add(l)}a(e,n.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,d=e("regjsparser").parse,f=e("regenerate"),h=e("./data/iu-mappings.json"),m=e("./data/character-class-escape-sets.js"),g={},y=g.hasOwnProperty,v=f().addRange(0,1114111),b=f().addRange(0,65535),x=v.clone().remove(10,13,8232,8233),E=x.clone().intersection(b);f.prototype.iuAddRange=function(e,t){var n=this;do{var r=o(e);r&&n.add(r)}while(++e<=t);return n};var _=!1,w=!1;t.exports=function(e,t){var n=d(e,t);return _=t?t.indexOf("i")>-1:!1,w=t?t.indexOf("u")>-1:!1,i(n,c(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,n){"use strict";var r=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||!r(t))throw new TypeError("Expected a finite positive number");var n="";do 1&t&&(n+=e),e+=e;while(t>>=1);return n}},{"is-finite":438}],438:[function(e,t,n){arguments[4][304][0].apply(n,arguments)},{dup:304}],439:[function(e,t,n){"use strict";t.exports=/^#!.*/},{}],440:[function(e,t,n){"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,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(){this._array=[],this._set={}}var l=e("./util");r.fromArray=function(e,t){for(var n=new r,l=0,i=e.length;i>l;l++)n.add(e[l],t);return n},r.prototype.add=function(e,t){var n=this.has(e),r=this._array.length;(!n||t)&&this._array.push(e),n||(this._set[l.toSetString(e)]=r)},r.prototype.has=function(e){return Object.prototype.hasOwnProperty.call(this._set,l.toSetString(e))},r.prototype.indexOf=function(e){if(this.has(e))return this._set[l.toSetString(e)];throw new Error('"'+e+'" is not in the set.')},r.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)},r.prototype.toArray=function(){return this._array.slice()},t.ArraySet=r})},{"./util":450,amdefine:451}],443:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(e){return 0>e?(-e<<1)+1:(e<<1)+0}function l(e){var t=1===(1&e),n=e>>1;return t?-n:n}var i=e("./base64"),a=5,s=1<<a,o=s-1,u=s;t.encode=function(e){var t,n="",l=r(e);do t=l&o,l>>>=a,l>0&&(t|=u),n+=i.encode(t);while(l>0);return n},t.decode=function(e,t,n){var r,s,c=e.length,p=0,d=0;do{if(t>=c)throw new Error("Expected more digits in base 64 VLQ value.");s=i.decode(e.charAt(t++)),r=!!(s&u),s&=o,p+=s<<d,d+=a}while(r);n.value=l(p),n.rest=t}})},{"./base64":444,amdefine:451}],444:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){var r={},l={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(e,t){r[e]=t,l[t]=e}),t.encode=function(e){if(e in l)return l[e];throw new TypeError("Must be between 0 and 63: "+e)},t.decode=function(e){if(e in r)return r[e];throw new TypeError("Not a valid base 64 digit: "+e)}})},{amdefine:451}],445:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(e,n,l,i,a,s){var o=Math.floor((n-e)/2)+e,u=a(l,i[o],!0);return 0===u?o:u>0?n-o>1?r(o,n,l,i,a,s):s==t.LEAST_UPPER_BOUND?n<i.length?n:-1:o:o-e>1?r(e,o,l,i,a,s):s==t.LEAST_UPPER_BOUND?o:0>e?-1:e; }t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2,t.search=function(e,n,l,i){if(0===n.length)return-1;var a=r(-1,n.length,e,n,l,i||t.GREATEST_LOWER_BOUND);if(0>a)return-1;for(;a-1>=0&&0===l(n[a],n[a-1],!0);)--a;return a}})},{amdefine:451}],446:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(e,t){var n=e.generatedLine,r=t.generatedLine,l=e.generatedColumn,a=t.generatedColumn;return r>n||r==n&&a>=l||i.compareByGeneratedPositions(e,t)<=0}function l(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");l.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},l.prototype.add=function(e){r(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},l.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositions),this._sorted=!0),this._array},t.MappingList=l})},{"./util":450,amdefine:451}],447:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(e){var t=e;return"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=t.sections?new i(t):new l(t)}function l(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var n=a.getArg(t,"version"),r=a.getArg(t,"sources"),l=a.getArg(t,"names",[]),i=a.getArg(t,"sourceRoot",null),s=a.getArg(t,"sourcesContent",null),u=a.getArg(t,"mappings"),c=a.getArg(t,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);r=r.map(a.normalize),this._names=o.fromArray(l,!0),this._sources=o.fromArray(r,!0),this.sourceRoot=i,this.sourcesContent=s,this._mappings=u,this.file=c}function i(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var n=a.getArg(t,"version"),l=a.getArg(t,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);var i={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=a.getArg(e,"offset"),n=a.getArg(t,"line"),l=a.getArg(t,"column");if(n<i.line||n===i.line&&l<i.column)throw new Error("Section offsets must be ordered and non-overlapping.");return i=t,{generatedOffset:{generatedLine:n+1,generatedColumn:l+1},consumer:new r(a.getArg(e,"map"))}})}var a=e("./util"),s=e("./binary-search"),o=e("./array-set").ArraySet,u=e("./base64-vlq");r.fromSourceMap=function(e){return l.fromSourceMap(e)},r.prototype._version=3,r.prototype.__generatedMappings=null,Object.defineProperty(r.prototype,"_generatedMappings",{get:function(){return this.__generatedMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__generatedMappings}}),r.prototype.__originalMappings=null,Object.defineProperty(r.prototype,"_originalMappings",{get:function(){return this.__originalMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot)),this.__originalMappings}}),r.prototype._nextCharIsMappingSeparator=function(e,t){var n=e.charAt(t);return";"===n||","===n},r.prototype._parseMappings=function(e,t){throw new Error("Subclasses must implement _parseMappings")},r.GENERATED_ORDER=1,r.ORIGINAL_ORDER=2,r.GREATEST_LOWER_BOUND=1,r.LEAST_UPPER_BOUND=2,r.prototype.eachMapping=function(e,t,n){var l,i=t||null,s=n||r.GENERATED_ORDER;switch(s){case r.GENERATED_ORDER:l=this._generatedMappings;break;case r.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=a.join(o,t)),{source:t,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name}}).forEach(e,i)},r.prototype.allGeneratedPositionsFor=function(e){var t={source:a.getArg(e,"source"),originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column",0)};null!=this.sourceRoot&&(t.source=a.relative(this.sourceRoot,t.source));var n=[],r=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,s.LEAST_UPPER_BOUND);if(r>=0)for(var l=this._originalMappings[r],i=l.originalLine,o=l.originalColumn;l&&l.originalLine===i&&(void 0===e.column||l.originalColumn===o);)n.push({line:a.getArg(l,"generatedLine",null),column:a.getArg(l,"generatedColumn",null),lastColumn:a.getArg(l,"lastGeneratedColumn",null)}),l=this._originalMappings[++r];return n},t.SourceMapConsumer=r,l.prototype=Object.create(r.prototype),l.prototype.consumer=r,l.fromSourceMap=function(e){var t=Object.create(l.prototype);return t._names=o.fromArray(e._names.toArray(),!0),t._sources=o.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(a.compareByOriginalPositions),t},l.prototype._version=3,Object.defineProperty(l.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?a.join(this.sourceRoot,e):e},this)}}),l.prototype._parseMappings=function(e,t){for(var n,r,l,i,s,o=1,c=0,p=0,d=0,f=0,h=0,m=e.length,g=0,y={},v={};m>g;)if(";"===e.charAt(g))o++,++g,c=0;else if(","===e.charAt(g))++g;else{for(n={},n.generatedLine=o,i=g;m>i&&!this._nextCharIsMappingSeparator(e,i);++i);if(r=e.slice(g,i),l=y[r])g+=r.length;else{for(l=[];i>g;)u.decode(e,g,v),s=v.value,g=v.rest,l.push(s);y[r]=l}if(n.generatedColumn=c+l[0],c=n.generatedColumn,l.length>1){if(n.source=this._sources.at(f+l[1]),f+=l[1],2===l.length)throw new Error("Found a source, but no line and column");if(n.originalLine=p+l[2],p=n.originalLine,n.originalLine+=1,3===l.length)throw new Error("Found a source and line, but no column");n.originalColumn=d+l[3],d=n.originalColumn,l.length>4&&(n.name=this._names.at(h+l[4]),h+=l[4])}this.__generatedMappings.push(n),"number"==typeof n.originalLine&&this.__originalMappings.push(n)}this.__generatedMappings.sort(a.compareByGeneratedPositions),this.__originalMappings.sort(a.compareByOriginalPositions)},l.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)},l.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}},l.prototype.originalPositionFor=function(e){var t={generatedLine:a.getArg(e,"line"),generatedColumn:a.getArg(e,"column")},n=this._findMapping(t,this._generatedMappings,"generatedLine","generatedColumn",a.compareByGeneratedPositions,a.getArg(e,"bias",r.GREATEST_LOWER_BOUND));if(n>=0){var l=this._generatedMappings[n];if(l.generatedLine===t.generatedLine){var i=a.getArg(l,"source",null);return null!=i&&null!=this.sourceRoot&&(i=a.join(this.sourceRoot,i)),{source:i,line:a.getArg(l,"originalLine",null),column:a.getArg(l,"originalColumn",null),name:a.getArg(l,"name",null)}}}return{source:null,line:null,column:null,name:null}},l.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var n;if(null!=this.sourceRoot&&(n=a.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.')},l.prototype.generatedPositionFor=function(e){var t={source:a.getArg(e,"source"),originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")};null!=this.sourceRoot&&(t.source=a.relative(this.sourceRoot,t.source));var n=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",r.GREATEST_LOWER_BOUND));if(n>=0){var l=this._originalMappings[n];if(l.source===t.source)return{line:a.getArg(l,"generatedLine",null),column:a.getArg(l,"generatedColumn",null),lastColumn:a.getArg(l,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},t.BasicSourceMapConsumer=l,i.prototype=Object.create(r.prototype),i.prototype.constructor=r,i.prototype._version=3,Object.defineProperty(i.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}}),i.prototype.originalPositionFor=function(e){var t={generatedLine:a.getArg(e,"line"),generatedColumn:a.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}},i.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.')},i.prototype.generatedPositionFor=function(e){for(var t=0;t<this._sections.length;t++){var n=this._sections[t];if(-1!==n.consumer.sources.indexOf(a.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}},i.prototype._parseMappings=function(e,t){this.__generatedMappings=[],this.__originalMappings=[];for(var n=0;n<this._sections.length;n++)for(var r=this._sections[n],l=r.consumer._generatedMappings,i=0;i<l.length;i++){var s=l[n],o=s.source,u=r.consumer.sourceRoot;null!=o&&null!=u&&(o=a.join(u,o));var c={source:o,generatedLine:s.generatedLine+(r.generatedOffset.generatedLine-1),generatedColumn:s.column+(r.generatedOffset.generatedLine===s.generatedLine)?r.generatedOffset.generatedColumn-1:0,originalLine:s.originalLine,originalColumn:s.originalColumn,name:s.name};this.__generatedMappings.push(c),"number"==typeof c.originalLine&&this.__originalMappings.push(c)}this.__generatedMappings.sort(a.compareByGeneratedPositions),this.__originalMappings.sort(a.compareByOriginalPositions)},t.IndexedSourceMapConsumer=i})},{"./array-set":442,"./base64-vlq":443,"./binary-search":445,"./util":450,amdefine:451}],448:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new a,this._names=new a,this._mappings=new s,this._sourcesContents=null}var l=e("./base64-vlq"),i=e("./util"),a=e("./array-set").ArraySet,s=e("./mapping-list").MappingList;r.prototype._version=3,r.fromSourceMap=function(e){var t=e.sourceRoot,n=new r({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var r={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(r.source=e.source,null!=t&&(r.source=i.relative(t,r.source)),r.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(r.name=e.name)),n.addMapping(r)}),e.sources.forEach(function(t){var r=e.sourceContentFor(t);null!=r&&n.setSourceContent(t,r)}),n},r.prototype.addMapping=function(e){var t=i.getArg(e,"generated"),n=i.getArg(e,"original",null),r=i.getArg(e,"source",null),l=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,r,l),null==r||this._sources.has(r)||this._sources.add(r),null==l||this._names.has(l)||this._names.add(l),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:r,name:l})},r.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=i.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents={}),this._sourcesContents[i.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},r.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 l=this._sourceRoot;null!=l&&(r=i.relative(l,r));var s=new a,o=new a;this._mappings.unsortedForEach(function(t){if(t.source===r&&null!=t.originalLine){var a=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=a.source&&(t.source=a.source,null!=n&&(t.source=i.join(n,t.source)),null!=l&&(t.source=i.relative(l,t.source)),t.originalLine=a.line,t.originalColumn=a.column,null!=a.name&&(t.name=a.name))}var u=t.source;null==u||s.has(u)||s.add(u);var c=t.name;null==c||o.has(c)||o.add(c)},this),this._sources=s,this._names=o,e.sources.forEach(function(t){var r=e.sourceContentFor(t);null!=r&&(null!=n&&(t=i.join(n,t)),null!=l&&(t=i.relative(l,t)),this.setSourceContent(t,r))},this)},r.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}))},r.prototype._serializeMappings=function(){for(var e,t=0,n=1,r=0,a=0,s=0,o=0,u="",c=this._mappings.toArray(),p=0,d=c.length;d>p;p++){if(e=c[p],e.generatedLine!==n)for(t=0;e.generatedLine!==n;)u+=";",n++;else if(p>0){if(!i.compareByGeneratedPositions(e,c[p-1]))continue;u+=","}u+=l.encode(e.generatedColumn-t),t=e.generatedColumn,null!=e.source&&(u+=l.encode(this._sources.indexOf(e.source)-o),o=this._sources.indexOf(e.source),u+=l.encode(e.originalLine-1-a),a=e.originalLine-1,u+=l.encode(e.originalColumn-r),r=e.originalColumn,null!=e.name&&(u+=l.encode(this._names.indexOf(e.name)-s),s=this._names.indexOf(e.name)))}return u},r.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=i.relative(t,e));var n=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},r.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},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=r})},{"./array-set":442,"./base64-vlq":443,"./mapping-list":446,"./util":450,amdefine:451}],449:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(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[o]=!0,null!=r&&this.add(r)}var l=e("./source-map-generator").SourceMapGenerator,i=e("./util"),a=/(\r?\n)/,s=10,o="$$$isSourceNode$$$";r.fromStringWithSourceMap=function(e,t,n){function l(e,t){if(null===e||void 0===e.source)s.add(t);else{var l=n?i.join(n,e.source):e.source;s.add(new r(e.originalLine,e.originalColumn,l,t,e.name))}}var s=new r,o=e.split(a),u=function(){var e=o.shift(),t=o.shift()||"";return e+t},c=1,p=0,d=null;return t.eachMapping(function(e){if(null!==d){if(!(c<e.generatedLine)){var t=o[0],n=t.substr(0,e.generatedColumn-p);return o[0]=t.substr(e.generatedColumn-p),p=e.generatedColumn,l(d,n),void(d=e)}var n="";l(d,u()),c++,p=0}for(;c<e.generatedLine;)s.add(u()),c++;if(p<e.generatedColumn){var t=o[0];s.add(t.substr(0,e.generatedColumn)),o[0]=t.substr(e.generatedColumn),p=e.generatedColumn}d=e},this),o.length>0&&(d&&l(d,u()),s.add(o.join(""))),t.sources.forEach(function(e){var r=t.sourceContentFor(e);null!=r&&(null!=n&&(e=i.join(n,e)),s.setSourceContent(e,r))}),s},r.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[o]&&"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},r.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else{if(!e[o]&&"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},r.prototype.walk=function(e){for(var t,n=0,r=this.children.length;r>n;n++)t=this.children[n],t[o]?t.walk(e):""!==t&&e(t,{source:this.source,line:this.line,column:this.column,name:this.name})},r.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},r.prototype.replaceRight=function(e,t){var n=this.children[this.children.length-1];return n[o]?n.replaceRight(e,t):"string"==typeof n?this.children[this.children.length-1]=n.replace(e,t):this.children.push("".replace(e,t)),this},r.prototype.setSourceContent=function(e,t){this.sourceContents[i.toSetString(e)]=t},r.prototype.walkSourceContents=function(e){for(var t=0,n=this.children.length;n>t;t++)this.children[t][o]&&this.children[t].walkSourceContents(e);for(var r=Object.keys(this.sourceContents),t=0,n=r.length;n>t;t++)e(i.fromSetString(r[t]),this.sourceContents[r[t]])},r.prototype.toString=function(){var e="";return this.walk(function(t){e+=t}),e},r.prototype.toStringWithSourceMap=function(e){var t={code:"",line:1,column:0},n=new l(e),r=!1,i=null,a=null,o=null,u=null;return this.walk(function(e,l){t.code+=e,null!==l.source&&null!==l.line&&null!==l.column?((i!==l.source||a!==l.line||o!==l.column||u!==l.name)&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:t.line,column:t.column},name:l.name}),i=l.source,a=l.line,o=l.column,u=l.name,r=!0):r&&(n.addMapping({generated:{line:t.line,column:t.column}}),i=null,r=!1);for(var c=0,p=e.length;p>c;c++)e.charCodeAt(c)===s?(t.line++,t.column=0,c+1===p?(i=null,r=!1):r&&n.addMapping({source:l.source,original:{line:l.line,column:l.column},generated:{line:t.line,column:t.column},name:l.name})):t.column++}),this.walkSourceContents(function(e,t){n.setSourceContent(e,t)}),{code:t.code,map:n}},t.SourceNode=r})},{"./source-map-generator":448,"./util":450,amdefine:451}],450:[function(e,t,n){if("function"!=typeof r)var r=e("amdefine")(t,e);r(function(e,t,n){function r(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 l(e){var t=e.match(h);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function i(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 a(e){var t=e,n=l(e);if(n){if(!n.path)return e;t=n.path}for(var r,a="/"===t.charAt(0),s=t.split(/\/+/),o=0,u=s.length-1;u>=0;u--)r=s[u],"."===r?s.splice(u,1):".."===r?o++:o>0&&(""===r?(s.splice(u+1,o),o=0):(s.splice(u,2),o--));return t=s.join("/"),""===t&&(t=a?"/":"."),n?(n.path=t,i(n)):t}function s(e,t){""===e&&(e="."),""===t&&(t=".");var n=l(t),r=l(e);if(r&&(e=r.path||"/"),n&&!n.scheme)return r&&(n.scheme=r.scheme),i(n);if(n||t.match(m))return t;if(r&&!r.host&&!r.path)return r.host=t,i(r);var s="/"===t.charAt(0)?t:a(e.replace(/\/+$/,"")+"/"+t);return r?(r.path=s,i(r)):s}function o(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");var n=l(e);return"/"==t.charAt(0)&&n&&"/"==n.path?t.slice(1):0===t.indexOf(e+"/")?t.substr(e.length+1):t}function u(e){return"$"+e}function c(e){return e.substr(1)}function p(e,t){var n=e||"",r=t||"";return(n>r)-(r>n)}function d(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 f(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=r;var h=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,m=/^data:.+\,.+$/;t.urlParse=l,t.urlGenerate=i,t.normalize=a,t.join=s,t.relative=o,t.toSetString=u,t.fromSetString=c,t.compareByOriginalPositions=d,t.compareByGeneratedPositions=f})},{amdefine:451}],451:[function(e,t,n){(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 a(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 s(e){return function(t){return a(t,e)}}function o(e){function t(t){h[e]=t}return t.fromText=function(e,t){throw new Error("amdefine does not implement load.fromText")},t}function u(e,n,i){var a,s,o,u;if(e)s=h[e]={},o={id:e,uri:r,exports:s},a=p(l,s,o,e);else{if(m)throw new Error("amdefine with no module ID cannot be called more than once per file.");m=!0,s=t.exports,o=t,a=p(l,s,o,t.id)}n&&(n=n.map(function(e){return a(e)})),u="function"==typeof i?i.apply(o.exports,n):i,void 0!==u&&(o.exports=u,e&&(h[e]=o.exports))}function c(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 p,d,f={},h={},m=!1,g=e("path");return p=function(e,t,r,l){function i(i,a){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(){a.apply(null,i)}))}return i.toUrl=function(e){return 0===e.indexOf(".")?a(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,c,m=r.indexOf("!"),g=r;if(-1===m){if(r=a(r,l),"require"===r)return p(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),c=d(e,t,n,i,l),r=c.normalize?c.normalize(r,s(l)):a(r,l),h[r]?h[r]:(c.load(r,p(e,t,n,l),o(r),{}),h[r])},c.require=function(e){return h[e]?h[e]:f[e]?(u.apply(null,f[e]),h[e]):void 0},c.amd={},c}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){!function(){"use strict";function e(e){for(var t,n,r=!1,l=!1,i="",a=0;a<e.length;a++)if(t=e[a],n=e[a+1],l||"\\"===e[a-1]||'"'!==t||(r=!r),r)i+=t;else{if(l||t+n!=="//"){if("single"===l&&t+n==="\r\n"){l=!1,a++,i+=t,i+=n;continue}if("single"===l&&"\n"===t)l=!1;else{if(!l&&t+n==="/*"){l="multi",a++;continue}if("multi"===l&&t+n==="*/"){l=!1,a++;continue}}}else l="single",a++;l||(i+=t)}return i}"undefined"!=typeof t&&t.exports?t.exports=e:window.stripJsonComments=e}()},{}],453:[function(e,t,n){"use strict";t.exports=function r(e){function t(){}t.prototype=e,new t}},{}],454:[function(e,t,n){"use strict";t.exports=function(e){return e.replace(/[\s\uFEFF\xA0]+$/g,"")}},{}],455:[function(e,t,n){t.exports={name:"babel-core",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"5.0.12",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","strip-json-comments":"^1.0.2","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"}}},{}],456:[function(e,t,n){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)}),function(){"use strict";function e(t){this.map={};var n=this;t instanceof e?t.forEach(function(e,t){t.forEach(function(t){n.append(e,t)})}):t&&Object.getOwnPropertyNames(t).forEach(function(e){n.append(e,t[e])})}function t(e){return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function n(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function r(e){var t=new FileReader;return t.readAsArrayBuffer(e),n(t)}function l(e){var t=new FileReader;return t.readAsText(e),n(t)}function i(){return this.bodyUsed=!1,p.blob?(this._initBody=function(e){if(this._bodyInit=e,"string"==typeof e)this._bodyText=e;else if(p.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(p.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else{if(e)throw new Error("unsupported BodyInit type");this._bodyText=""}},this.blob=function(){var e=t(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this.blob().then(r)},this.text=function(){var e=t(this);if(e)return e;if(this._bodyBlob)return l(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)}):(this._initBody=function(e){if(this._bodyInit=e,"string"==typeof e)this._bodyText=e;else if(p.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else{if(e)throw new Error("unsupported BodyInit type");this._bodyText=""}},this.text=function(){var e=t(this);return e?e:Promise.resolve(this._bodyText)}),p.formData&&(this.formData=function(){return this.text().then(o)}),this.json=function(){return this.text().then(JSON.parse)},this}function a(e){var t=e.toUpperCase();return d.indexOf(t)>-1?t:e}function s(t,n){if(n=n||{},this.url=t,this.credentials=n.credentials||"omit",this.headers=new e(n.headers),this.method=a(n.method||"GET"),this.mode=n.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n.body)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n.body)}function o(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),l=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(l))}}),t}function u(t){var n=new e,r=t.getAllResponseHeaders().trim().split("\n");return r.forEach(function(e){var t=e.trim().split(":"),r=t.shift().trim(),l=t.join(":").trim();n.append(r,l)}),n}function c(e,t){t||(t={}),this._initBody(e),this.type="default",this.url=null,this.status=t.status,this.statusText=t.statusText,this.headers=t.headers,this.url=t.url||""}if(!self.fetch){e.prototype.append=function(e,t){e=e.toLowerCase();var n=this.map[e];n||(n=[],this.map[e]=n),n.push(t)},e.prototype["delete"]=function(e){delete this.map[e.toLowerCase()]},e.prototype.get=function(e){var t=this.map[e.toLowerCase()];return t?t[0]:null},e.prototype.getAll=function(e){return this.map[e.toLowerCase()]||[]},e.prototype.has=function(e){return this.map.hasOwnProperty(e.toLowerCase())},e.prototype.set=function(e,t){this.map[e.toLowerCase()]=[t]},e.prototype.forEach=function(e){var t=this;Object.getOwnPropertyNames(this.map).forEach(function(n){e(n,t.map[n])})};var p={blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in self},d=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];s.prototype.fetch=function(){var e=this;return new Promise(function(t,n){function r(){return"responseURL"in l?l.responseURL:/^X-Request-URL:/m.test(l.getAllResponseHeaders())?l.getResponseHeader("X-Request-URL"):void 0}var l=new XMLHttpRequest;"cors"===e.credentials&&(l.withCredentials=!0),l.onload=function(){var e=1223===l.status?204:l.status;if(100>e||e>599)return void n(new TypeError("Network request failed"));var i={status:e,statusText:l.statusText,headers:u(l),url:r()},a="response"in l?l.response:l.responseText;t(new c(a,i))},l.onerror=function(){n(new TypeError("Network request failed"))},l.open(e.method,e.url,!0),"responseType"in l&&p.blob&&(l.responseType="blob"),e.headers.forEach(function(e,t){t.forEach(function(t){l.setRequestHeader(e,t)})}),l.send("undefined"==typeof e._bodyInit?null:e._bodyInit)})},i.call(s.prototype),i.call(c.prototype),self.Headers=e,self.Request=s,self.Response=c,self.fetch=function(e,t){return new s(e,t).fetch()},self.fetch.polyfill=!0}}(),window.WebComponents=window.WebComponents||{},function(e){var t=e.flags||{},n="webcomponents.js",r=document.querySelector('script[src*="'+n+'"]');if(!t.noOpts){if(location.search.slice(1).split("&").forEach(function(e){e=e.split("="),e[0]&&(t[e[0]]=e[1]||!0)}),r)for(var l,i=0;l=r.attributes[i];i++)"src"!==l.name&&(t[l.name]=l.value||!0);if(t.log&&t.log.split){var a=t.log.split(",");t.log={},a.forEach(function(e){t.log[e]=!0})}else t.log={}}t.shadow=t.shadow||t.shadowdom||t.polyfill,t.shadow="native"===t.shadow?!1:t.shadow||!HTMLElement.prototype.createShadowRoot,t.register&&(window.CustomElements=window.CustomElements||{flags:{}},window.CustomElements.flags.register=t.register),e.flags=t}(WebComponents),WebComponents.flags.shadow&&("undefined"==typeof WeakMap&&!function(){var e=Object.defineProperty,t=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+(t++ +"__")};n.prototype={set:function(t,n){var r=t[this.name];return r&&r[0]===t?r[1]=n:e(t,this.name,{value:[t,n],writable:!0}),this},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){var t=e[this.name];return t&&t[0]===e?(t[0]=t[1]=void 0,!0):!1},has:function(e){var t=e[this.name];return t?t[0]===e:!1}},window.WeakMap=n}(),window.ShadowDOMPolyfill={},function(e){"use strict";function t(){if("undefined"!=typeof chrome&&chrome.app&&chrome.app.runtime)return!1;if(navigator.getDeviceStorage)return!1;try{var e=new Function("return true;");return e()}catch(t){return!1}}function n(e){if(!e)throw new Error("Assertion failed")}function r(e,t){for(var n=B(t),r=0;r<n.length;r++){var l=n[r];F(e,l,U(t,l))}return e}function l(e,t){for(var n=B(t),r=0;r<n.length;r++){var l=n[r];switch(l){case"arguments":case"caller":case"length":case"name":case"prototype":case"toString":continue}F(e,l,U(t,l))}return e}function i(e,t){for(var n=0;n<t.length;n++)if(t[n]in e)return t[n]}function a(e,t,n){$.value=n,F(e,t,$)}function s(e){var t=e.__proto__||Object.getPrototypeOf(e);if(V)try{B(t)}catch(n){t=t.__proto__}var r=P.get(t);if(r)return r;var l=s(t),i=E(l);return v(t,i,e),i}function o(e,t){g(e,t,!0)}function u(e,t){g(t,e,!1)}function c(e){return/^on[a-z]+$/.test(e)}function p(e){return/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e)}function d(e){return R&&p(e)?new Function("return this.__impl4cf1e782hg__."+e):function(){return this.__impl4cf1e782hg__[e]}}function f(e){return R&&p(e)?new Function("v","this.__impl4cf1e782hg__."+e+" = v"):function(t){this.__impl4cf1e782hg__[e]=t}}function h(e){return R&&p(e)?new Function("return this.__impl4cf1e782hg__."+e+".apply(this.__impl4cf1e782hg__, arguments)"):function(){return this.__impl4cf1e782hg__[e].apply(this.__impl4cf1e782hg__,arguments)}}function m(e,t){try{return Object.getOwnPropertyDescriptor(e,t)}catch(n){return q}}function g(t,n,r,l){for(var i=B(t),a=0;a<i.length;a++){var s=i[a];if("polymerBlackList_"!==s&&!(s in n||t.polymerBlackList_&&t.polymerBlackList_[s])){V&&t.__lookupGetter__(s);var o,u,p=m(t,s);if(r&&"function"==typeof p.value)n[s]=h(s);else{var g=c(s);o=g?e.getEventHandlerGetter(s):d(s),(p.writable||p.set||H)&&(u=g?e.getEventHandlerSetter(s):f(s));var y=H||p.configurable;F(n,s,{get:o,set:u,configurable:y,enumerable:p.enumerable})}}}}function y(e,t,n){var r=e.prototype;v(r,t,n),l(t,e)}function v(e,t,r){var l=t.prototype;n(void 0===P.get(e)),P.set(e,t),N.set(l,e),o(e,l),r&&u(l,r),a(l,"constructor",t),t.prototype=l}function b(e,t){return P.get(t.prototype)===e}function x(e){var t=Object.getPrototypeOf(e),n=s(t),r=E(n);return v(t,r,e),r}function E(e){function t(t){e.call(this,t)}var n=Object.create(e.prototype);return n.constructor=t,t.prototype=n,t}function _(e){return e&&e.__impl4cf1e782hg__}function w(e){return!_(e)}function S(e){return null===e?null:(n(w(e)),e.__wrapper8e3dd93a60__||(e.__wrapper8e3dd93a60__=new(s(e))(e)))}function I(e){return null===e?null:(n(_(e)),e.__impl4cf1e782hg__)}function k(e){return e.__impl4cf1e782hg__}function T(e,t){t.__impl4cf1e782hg__=e,e.__wrapper8e3dd93a60__=t}function C(e){return e&&_(e)?I(e):e}function j(e){return e&&!_(e)?S(e):e}function M(e,t){null!==t&&(n(w(e)),n(void 0===t||_(t)),e.__wrapper8e3dd93a60__=t)}function A(e,t,n){G.get=n,F(e.prototype,t,G)}function O(e,t){A(e,t,function(){return S(this.__impl4cf1e782hg__[t])})}function L(e,t){e.forEach(function(e){t.forEach(function(t){e.prototype[t]=function(){var e=j(this);return e[t].apply(e,arguments)}})})}var P=new WeakMap,N=new WeakMap,D=Object.create(null),R=t(),F=Object.defineProperty,B=Object.getOwnPropertyNames,U=Object.getOwnPropertyDescriptor,$={value:void 0,configurable:!0,enumerable:!1,writable:!0};B(window);var V=/Firefox/.test(navigator.userAgent),q={get:function(){},set:function(e){},configurable:!0,enumerable:!0},H=function(){var e=Object.getOwnPropertyDescriptor(Node.prototype,"nodeType");return e&&!e.get&&!e.set}(),G={get:void 0,configurable:!0,enumerable:!0};e.assert=n,e.constructorTable=P,e.defineGetter=A,e.defineWrapGetter=O,e.forwardMethodsToWrapper=L,e.isIdentifierName=p,e.isWrapper=_,e.isWrapperFor=b,e.mixin=r,e.nativePrototypeTable=N,e.oneOf=i,e.registerObject=x,e.registerWrapper=y,e.rewrap=M,e.setWrapper=T,e.unsafeUnwrap=k,e.unwrap=I,e.unwrapIfNeeded=C,e.wrap=S,e.wrapIfNeeded=j,e.wrappers=D}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t,n){return{index:e,removed:t,addedCount:n}}function n(){}var r=0,l=1,i=2,a=3;n.prototype={calcEditDistances:function(e,t,n,r,l,i){for(var a=i-l+1,s=n-t+1,o=new Array(a),u=0;a>u;u++)o[u]=new Array(s),o[u][0]=u;for(var c=0;s>c;c++)o[0][c]=c;for(var u=1;a>u;u++)for(var c=1;s>c;c++)if(this.equals(e[t+c-1],r[l+u-1]))o[u][c]=o[u-1][c-1];else{var p=o[u-1][c]+1,d=o[u][c-1]+1;o[u][c]=d>p?p:d}return o},spliceOperationsFromEditDistances:function(e){for(var t=e.length-1,n=e[0].length-1,s=e[t][n],o=[];t>0||n>0;)if(0!=t)if(0!=n){var u,c=e[t-1][n-1],p=e[t-1][n],d=e[t][n-1];u=d>p?c>p?p:c:c>d?d:c,u==c?(c==s?o.push(r):(o.push(l),s=c),t--,n--):u==p?(o.push(a),t--,s=p):(o.push(i),n--,s=d)}else o.push(a),t--;else o.push(i),n--;return o.reverse(),o},calcSplices:function(e,n,s,o,u,c){var p=0,d=0,f=Math.min(s-n,c-u);if(0==n&&0==u&&(p=this.sharedPrefix(e,o,f)),s==e.length&&c==o.length&&(d=this.sharedSuffix(e,o,f-p)),n+=p,u+=p,s-=d,c-=d,s-n==0&&c-u==0)return[];if(n==s){for(var h=t(n,[],0);c>u;)h.removed.push(o[u++]);return[h]}if(u==c)return[t(n,[],s-n)];for(var m=this.spliceOperationsFromEditDistances(this.calcEditDistances(e,n,s,o,u,c)),h=void 0,g=[],y=n,v=u,b=0;b<m.length;b++)switch(m[b]){case r:h&&(g.push(h),h=void 0),y++,v++;break;case l:h||(h=t(y,[],0)),h.addedCount++,y++,h.removed.push(o[v]),v++;break;case i:h||(h=t(y,[],0)),h.addedCount++,y++;break;case a:h||(h=t(y,[],0)),h.removed.push(o[v]),v++}return h&&g.push(h),g},sharedPrefix:function(e,t,n){for(var r=0;n>r;r++)if(!this.equals(e[r],t[r]))return r;return n},sharedSuffix:function(e,t,n){for(var r=e.length,l=t.length,i=0;n>i&&this.equals(e[--r],t[--l]);)i++;return i},calculateSplices:function(e,t){return this.calcSplices(e,0,e.length,t,0,t.length)},equals:function(e,t){return e===t}},e.ArraySplice=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(){a=!1;var e=i.slice(0);i=[];for(var t=0;t<e.length;t++)e[t]()}function n(e){i.push(e),a||(a=!0,r(t,0))}var r,l=window.MutationObserver,i=[],a=!1;if(l){var s=1,o=new l(t),u=document.createTextNode(s);o.observe(u,{characterData:!0}),r=function(){s=(s+1)%2,u.data=s}}else r=window.setTimeout;e.setEndOfMicrotask=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.scheduled_||(e.scheduled_=!0,h.push(e),m||(c(n),m=!0))}function n(){for(m=!1;h.length;){var e=h;h=[],e.sort(function(e,t){return e.uid_-t.uid_});for(var t=0;t<e.length;t++){var n=e[t];n.scheduled_=!1;var r=n.takeRecords();i(n),r.length&&n.callback_(r,n)}}}function r(e,t){this.type=e,this.target=t,this.addedNodes=new d.NodeList,this.removedNodes=new d.NodeList,this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function l(e,t){for(;e;e=e.parentNode){var n=f.get(e);if(n)for(var r=0;r<n.length;r++){var l=n[r];l.options.subtree&&l.addTransientObserver(t)}}}function i(e){for(var t=0;t<e.nodes_.length;t++){var n=e.nodes_[t],r=f.get(n);if(!r)return;for(var l=0;l<r.length;l++){var i=r[l];i.observer===e&&i.removeTransientObservers()}}}function a(e,n,l){for(var i=Object.create(null),a=Object.create(null),s=e;s;s=s.parentNode){var o=f.get(s);if(o)for(var u=0;u<o.length;u++){var c=o[u],p=c.options;if((s===e||p.subtree)&&!("attributes"===n&&!p.attributes||"attributes"===n&&p.attributeFilter&&(null!==l.namespace||-1===p.attributeFilter.indexOf(l.name))||"characterData"===n&&!p.characterData||"childList"===n&&!p.childList)){var d=c.observer;i[d.uid_]=d,("attributes"===n&&p.attributeOldValue||"characterData"===n&&p.characterDataOldValue)&&(a[d.uid_]=l.oldValue)}}}for(var h in i){var d=i[h],m=new r(n,e);"name"in l&&"namespace"in l&&(m.attributeName=l.name,m.attributeNamespace=l.namespace),l.addedNodes&&(m.addedNodes=l.addedNodes),l.removedNodes&&(m.removedNodes=l.removedNodes),l.previousSibling&&(m.previousSibling=l.previousSibling),l.nextSibling&&(m.nextSibling=l.nextSibling),void 0!==a[h]&&(m.oldValue=a[h]),t(d),d.records_.push(m)}}function s(e){if(this.childList=!!e.childList,this.subtree=!!e.subtree,this.attributes="attributes"in e||!("attributeOldValue"in e||"attributeFilter"in e)?!!e.attributes:!0,this.characterData="characterDataOldValue"in e&&!("characterData"in e)?!0:!!e.characterData,!this.attributes&&(e.attributeOldValue||"attributeFilter"in e)||!this.characterData&&e.characterDataOldValue)throw new TypeError;if(this.characterData=!!e.characterData,this.attributeOldValue=!!e.attributeOldValue,this.characterDataOldValue=!!e.characterDataOldValue,"attributeFilter"in e){if(null==e.attributeFilter||"object"!=typeof e.attributeFilter)throw new TypeError;this.attributeFilter=g.call(e.attributeFilter)}else this.attributeFilter=null}function o(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++y,this.scheduled_=!1}function u(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}var c=e.setEndOfMicrotask,p=e.wrapIfNeeded,d=e.wrappers,f=new WeakMap,h=[],m=!1,g=Array.prototype.slice,y=0;o.prototype={constructor:o,observe:function(e,t){e=p(e);var n,r=new s(t),l=f.get(e);l||f.set(e,l=[]);for(var i=0;i<l.length;i++)l[i].observer===this&&(n=l[i],n.removeTransientObservers(),n.options=r);n||(n=new u(this,e,r),l.push(n),this.nodes_.push(e))},disconnect:function(){this.nodes_.forEach(function(e){for(var t=f.get(e),n=0;n<t.length;n++){var r=t[n];if(r.observer===this){t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}},u.prototype={addTransientObserver:function(e){if(e!==this.target){t(this.observer),this.transientObservedNodes.push(e);var n=f.get(e);n||f.set(e,n=[]),n.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[];for(var t=0;t<e.length;t++)for(var n=e[t],r=f.get(n),l=0;l<r.length;l++)if(r[l]===this){r.splice(l,1);break}}},e.enqueueMutation=a,e.registerTransientObservers=l,e.wrappers.MutationObserver=o,e.wrappers.MutationRecord=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){this.root=e,this.parent=t}function n(e,t){if(e.treeScope_!==t){e.treeScope_=t;for(var r=e.shadowRoot;r;r=r.olderShadowRoot)r.treeScope_.parent=t;for(var l=e.firstChild;l;l=l.nextSibling)n(l,t)}}function r(n){if(n instanceof e.wrappers.Window,n.treeScope_)return n.treeScope_;var l,i=n.parentNode;return l=i?r(i):new t(n,null),n.treeScope_=l}t.prototype={get renderer(){return this.root instanceof e.wrappers.ShadowRoot?e.getRendererForHost(this.root.host):null},contains:function(e){for(;e;e=e.parent)if(e===this)return!0;return!1}},e.TreeScope=t,e.getTreeScope=r,e.setTreeScope=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e instanceof G.ShadowRoot}function n(e){return F(e).root}function r(e,r){var s=[],o=e;for(s.push(o);o;){var u=a(o);if(u&&u.length>0){for(var c=0;c<u.length;c++){var d=u[c];if(i(d)){var f=n(d),h=f.olderShadowRoot;h&&s.push(h)}s.push(d)}o=u[u.length-1]}else if(t(o)){if(p(e,o)&&l(r))break;o=o.host,s.push(o)}else o=o.parentNode,o&&s.push(o)}return s}function l(e){if(!e)return!1;switch(e.type){case"abort":case"error":case"select":case"change":case"load":case"reset":case"resize":case"scroll":case"selectstart":return!0}return!1}function i(e){return e instanceof HTMLShadowElement}function a(t){return e.getDestinationInsertionPoints(t)}function s(e,t){if(0===e.length)return t;t instanceof G.Window&&(t=t.document);for(var n=F(t),r=e[0],l=F(r),i=u(n,l),a=0;a<e.length;a++){var s=e[a];if(F(s)===i)return s}return e[e.length-1]}function o(e){for(var t=[];e;e=e.parent)t.push(e);return t}function u(e,t){for(var n=o(e),r=o(t),l=null;n.length>0&&r.length>0;){var i=n.pop(),a=r.pop();if(i!==a)break;l=i}return l}function c(e,t,n){t instanceof G.Window&&(t=t.document);var l,i=F(t),a=F(n),s=r(n,e),l=u(i,a);l||(l=a.root);for(var o=l;o;o=o.parent)for(var c=0;c<s.length;c++){var p=s[c];if(F(p)===o)return p}return null}function p(e,t){return F(e)===F(t)}function d(e){if(!z.get(e)&&(z.set(e,!0),h(H(e),H(e.target)),D)){var t=D;throw D=null,t}}function f(e){switch(e.type){case"load":case"beforeunload":case"unload":return!0}return!1}function h(t,n){if(X.get(t))throw new Error("InvalidStateError");X.set(t,!0),e.renderAllPending();var l,i,a;if(f(t)&&!t.bubbles){var s=n;s instanceof G.Document&&(a=s.defaultView)&&(i=s,l=[])}if(!l)if(n instanceof G.Window)a=n,l=[];else if(l=r(n,t),!f(t)){var s=l[l.length-1];s instanceof G.Document&&(a=s.defaultView)}return ne.set(t,l),m(t,l,a,i)&&g(t,l,a,i)&&y(t,l,a,i),Q.set(t,re),Y["delete"](t,null),X["delete"](t),t.defaultPrevented}function m(e,t,n,r){var l=le;if(n&&!v(n,e,l,t,r))return!1;for(var i=t.length-1;i>0;i--)if(!v(t[i],e,l,t,r))return!1;return!0}function g(e,t,n,r){var l=ie,i=t[0]||n;return v(i,e,l,t,r)}function y(e,t,n,r){for(var l=ae,i=1;i<t.length;i++)if(!v(t[i],e,l,t,r))return;n&&t.length>0&&v(n,e,l,t,r)}function v(e,t,n,r,l){var i=W.get(e);if(!i)return!0;var a=l||s(r,e);if(a===e){if(n===le)return!0;n===ae&&(n=ie)}else if(n===ae&&!t.bubbles)return!0;if("relatedTarget"in t){var o=q(t),u=o.relatedTarget;if(u){if(u instanceof Object&&u.addEventListener){var p=H(u),d=c(t,e,p);if(d===a)return!0}else d=null;K.set(t,d)}}Q.set(t,n);var f=t.type,h=!1;J.set(t,a),Y.set(t,e),i.depth++;for(var m=0,g=i.length;g>m;m++){var y=i[m];if(y.removed)h=!0;else if(!(y.type!==f||!y.capture&&n===le||y.capture&&n===ae))try{if("function"==typeof y.handler?y.handler.call(e,t):y.handler.handleEvent(t),ee.get(t))return!1}catch(v){D||(D=v)}}if(i.depth--,h&&0===i.depth){var b=i.slice();i.length=0;for(var m=0;m<b.length;m++)b[m].removed||i.push(b[m])}return!Z.get(t)}function b(e,t,n){this.type=e,this.handler=t,this.capture=Boolean(n)}function x(e,t){if(!(e instanceof se))return H(S(se,"Event",e,t));var n=e;return ve||"beforeunload"!==n.type||this instanceof I?void $(n,this):new I(n)}function E(e){return e&&e.relatedTarget?Object.create(e,{relatedTarget:{value:q(e.relatedTarget)}}):e}function _(e,t,n){var r=window[e],l=function(t,n){return t instanceof r?void $(t,this):H(S(r,e,t,n))};if(l.prototype=Object.create(t.prototype),n&&B(l.prototype,n),r)try{U(r,l,new r("temp"))}catch(i){U(r,l,document.createEvent(e))}return l}function w(e,t){return function(){arguments[t]=q(arguments[t]);var n=q(this);n[e].apply(n,arguments)}}function S(e,t,n,r){if(ge)return new e(n,E(r));var l=q(document.createEvent(t)),i=me[t],a=[n];return Object.keys(i).forEach(function(e){var t=null!=r&&e in r?r[e]:i[e];"relatedTarget"===e&&(t=q(t)),a.push(t)}),l["init"+t].apply(l,a),l}function I(e){x.call(this,e)}function k(e){return"function"==typeof e?!0:e&&e.handleEvent}function T(e){switch(e){case"DOMAttrModified":case"DOMAttributeNameChanged":case"DOMCharacterDataModified":case"DOMElementNameChanged":case"DOMNodeInserted":case"DOMNodeInsertedIntoDocument":case"DOMNodeRemoved":case"DOMNodeRemovedFromDocument":case"DOMSubtreeModified":return!0}return!1}function C(e){$(e,this)}function j(e){return e instanceof G.ShadowRoot&&(e=e.host),q(e)}function M(e,t){var n=W.get(e);if(n)for(var r=0;r<n.length;r++)if(!n[r].removed&&n[r].type===t)return!0;return!1}function A(e,t){for(var n=q(e);n;n=n.parentNode)if(M(H(n),t))return!0;return!1}function O(e){R(e,xe)}function L(t,n,l,i){e.renderAllPending();var a=H(Ee.call(V(n),l,i));if(!a)return null;var o=r(a,null),u=o.lastIndexOf(t);return-1==u?null:(o=o.slice(0,u),s(o,t))}function P(e){return function(){var t=te.get(this);return t&&t[e]&&t[e].value||null}}function N(e){var t=e.slice(2);return function(n){var r=te.get(this);r||(r=Object.create(null),te.set(this,r));var l=r[e];if(l&&this.removeEventListener(t,l.wrapped,!1),"function"==typeof n){var i=function(t){var r=n.call(this,t);r===!1?t.preventDefault():"onbeforeunload"===e&&"string"==typeof r&&(t.returnValue=r)};this.addEventListener(t,i,!1),r[e]={value:n,wrapped:i}}}}var D,R=e.forwardMethodsToWrapper,F=e.getTreeScope,B=e.mixin,U=e.registerWrapper,$=e.setWrapper,V=e.unsafeUnwrap,q=e.unwrap,H=e.wrap,G=e.wrappers,W=(new WeakMap,new WeakMap),z=new WeakMap,X=new WeakMap,J=new WeakMap,Y=new WeakMap,K=new WeakMap,Q=new WeakMap,Z=new WeakMap,ee=new WeakMap,te=new WeakMap,ne=new WeakMap,re=0,le=1,ie=2,ae=3;b.prototype={equals:function(e){return this.handler===e.handler&&this.type===e.type&&this.capture===e.capture},get removed(){return null===this.handler},remove:function(){this.handler=null}};var se=window.Event;se.prototype.polymerBlackList_={returnValue:!0,keyLocation:!0},x.prototype={get target(){return J.get(this)},get currentTarget(){return Y.get(this)},get eventPhase(){return Q.get(this)},get path(){var e=ne.get(this);return e?e.slice():[]},stopPropagation:function(){Z.set(this,!0)},stopImmediatePropagation:function(){Z.set(this,!0),ee.set(this,!0)}},U(se,x,document.createEvent("Event"));var oe=_("UIEvent",x),ue=_("CustomEvent",x),ce={get relatedTarget(){var e=K.get(this);return void 0!==e?e:H(q(this).relatedTarget)}},pe=B({initMouseEvent:w("initMouseEvent",14)},ce),de=B({initFocusEvent:w("initFocusEvent",5)},ce),fe=_("MouseEvent",oe,pe),he=_("FocusEvent",oe,de),me=Object.create(null),ge=function(){try{new window.FocusEvent("focus")}catch(e){return!1}return!0}();if(!ge){var ye=function(e,t,n){if(n){var r=me[n];t=B(B({},r),t)}me[e]=t};ye("Event",{bubbles:!1,cancelable:!1}),ye("CustomEvent",{detail:null},"Event"),ye("UIEvent",{view:null,detail:0},"Event"),ye("MouseEvent",{screenX:0,screenY:0,clientX:0,clientY:0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null},"UIEvent"),ye("FocusEvent",{relatedTarget:null},"UIEvent")}var ve=window.BeforeUnloadEvent;I.prototype=Object.create(x.prototype),B(I.prototype,{get returnValue(){return V(this).returnValue},set returnValue(e){V(this).returnValue=e}}),ve&&U(ve,I);var be=window.EventTarget,xe=["addEventListener","removeEventListener","dispatchEvent"];[Node,Window].forEach(function(e){var t=e.prototype;xe.forEach(function(e){Object.defineProperty(t,e+"_",{value:t[e]})})}),C.prototype={addEventListener:function(e,t,n){if(k(t)&&!T(e)){var r=new b(e,t,n),l=W.get(this);if(l){for(var i=0;i<l.length;i++)if(r.equals(l[i]))return}else l=[],l.depth=0,W.set(this,l);l.push(r);var a=j(this);a.addEventListener_(e,d,!0)}},removeEventListener:function(e,t,n){n=Boolean(n);var r=W.get(this);if(r){for(var l=0,i=!1,a=0;a<r.length;a++)r[a].type===e&&r[a].capture===n&&(l++,r[a].handler===t&&(i=!0,r[a].remove()));if(i&&1===l){var s=j(this);s.removeEventListener_(e,d,!0)}}},dispatchEvent:function(t){var n=q(t),r=n.type;z.set(n,!1),e.renderAllPending();var l;A(this,r)||(l=function(){},this.addEventListener(r,l,!0));try{return q(this).dispatchEvent_(n)}finally{l&&this.removeEventListener(r,l,!0)}}},be&&U(be,C);var Ee=document.elementFromPoint;e.elementFromPoint=L,e.getEventHandlerGetter=P,e.getEventHandlerSetter=N,e.wrapEventTargetMethods=O,e.wrappers.BeforeUnloadEvent=I,e.wrappers.CustomEvent=ue,e.wrappers.Event=x,e.wrappers.EventTarget=C,e.wrappers.FocusEvent=he,e.wrappers.MouseEvent=fe,e.wrappers.UIEvent=oe}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){Object.defineProperty(e,t,m)}function n(e){u(e,this)}function r(){this.length=0,t(this,"length")}function l(e){for(var t=new r,l=0;l<e.length;l++)t[l]=new n(e[l]);return t.length=l,t}function i(e){a.call(this,e)}var a=e.wrappers.UIEvent,s=e.mixin,o=e.registerWrapper,u=e.setWrapper,c=e.unsafeUnwrap,p=e.wrap,d=window.TouchEvent;if(d){var f;try{f=document.createEvent("TouchEvent")}catch(h){return}var m={enumerable:!1};n.prototype={get target(){return p(c(this).target)}};var g={configurable:!0,enumerable:!0,get:null};["clientX","clientY","screenX","screenY","pageX","pageY","identifier","webkitRadiusX","webkitRadiusY","webkitRotationAngle","webkitForce"].forEach(function(e){g.get=function(){return c(this)[e]},Object.defineProperty(n.prototype,e,g)}),r.prototype={item:function(e){return this[e]}},i.prototype=Object.create(a.prototype),s(i.prototype,{get touches(){return l(c(this).touches)},get targetTouches(){return l(c(this).targetTouches)},get changedTouches(){return l(c(this).changedTouches)},initTouchEvent:function(){throw new Error("Not implemented")}}),o(d,i,f),e.wrappers.Touch=n,e.wrappers.TouchEvent=i,e.wrappers.TouchList=r}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e,t){Object.defineProperty(e,t,s)}function n(){this.length=0,t(this,"length")}function r(e){if(null==e)return e;for(var t=new n,r=0,l=e.length;l>r;r++)t[r]=a(e[r]);return t.length=l,t}function l(e,t){e.prototype[t]=function(){return r(i(this)[t].apply(i(this),arguments))}}var i=e.unsafeUnwrap,a=e.wrap,s={enumerable:!1};n.prototype={item:function(e){return this[e]}},t(n.prototype,"item"),e.wrappers.NodeList=n,e.addWrapNodeListMethod=l,e.wrapNodeList=r}(window.ShadowDOMPolyfill),function(e){"use strict";e.wrapHTMLCollection=e.wrapNodeList,e.wrappers.HTMLCollection=e.wrappers.NodeList}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){k(e instanceof _)}function n(e){var t=new S;return t[0]=e,t.length=1,t}function r(e,t,n){C(t,"childList",{removedNodes:n,previousSibling:e.previousSibling,nextSibling:e.nextSibling})}function l(e,t){C(e,"childList",{removedNodes:t})}function i(e,t,r,l){if(e instanceof DocumentFragment){var i=s(e);$=!0;for(var a=i.length-1;a>=0;a--)e.removeChild(i[a]),i[a].parentNode_=t;$=!1;for(var a=0;a<i.length;a++)i[a].previousSibling_=i[a-1]||r,i[a].nextSibling_=i[a+1]||l;return r&&(r.nextSibling_=i[0]),l&&(l.previousSibling_=i[i.length-1]),i}var i=n(e),o=e.parentNode;return o&&o.removeChild(e),e.parentNode_=t,e.previousSibling_=r,e.nextSibling_=l,r&&(r.nextSibling_=e),l&&(l.previousSibling_=e),i}function a(e){if(e instanceof DocumentFragment)return s(e);var t=n(e),l=e.parentNode;return l&&r(e,l,t),t}function s(e){for(var t=new S,n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t.length=n,l(e,t),t}function o(e){return e}function u(e,t){P(e,t),e.nodeIsInserted_()}function c(e,t){for(var n=j(t),r=0;r<e.length;r++)u(e[r],n)}function p(e){P(e,new I(e,null))}function d(e){for(var t=0;t<e.length;t++)p(e[t])}function f(e,t){var n=e.nodeType===_.DOCUMENT_NODE?e:e.ownerDocument;n!==t.ownerDocument&&n.adoptNode(t)}function h(t,n){if(n.length){var r=t.ownerDocument;if(r!==n[0].ownerDocument)for(var l=0;l<n.length;l++)e.adoptNodeNoRemove(n[l],r)}}function m(e,t){h(e,t);var n=t.length;if(1===n)return D(t[0]);for(var r=D(e.ownerDocument.createDocumentFragment()),l=0;n>l;l++)r.appendChild(D(t[l]));return r}function g(e){if(void 0!==e.firstChild_)for(var t=e.firstChild_;t;){var n=t;t=t.nextSibling_,n.parentNode_=n.previousSibling_=n.nextSibling_=void 0}e.firstChild_=e.lastChild_=void 0}function y(e){if(e.invalidateShadowRenderer()){for(var t=e.firstChild;t;){k(t.parentNode===e);var n=t.nextSibling,r=D(t),l=r.parentNode; l&&J.call(l,r),t.previousSibling_=t.nextSibling_=t.parentNode_=null,t=n}e.firstChild_=e.lastChild_=null}else for(var n,i=D(e),a=i.firstChild;a;)n=a.nextSibling,J.call(i,a),a=n}function v(e){var t=e.parentNode;return t&&t.invalidateShadowRenderer()}function b(e){for(var t,n=0;n<e.length;n++)t=e[n],t.parentNode.removeChild(t)}function x(e,t,n){var r;if(r=F(n?V.call(n,N(e),!1):q.call(N(e),!1)),t){for(var l=e.firstChild;l;l=l.nextSibling)r.appendChild(x(l,!0,n));if(e instanceof U.HTMLTemplateElement)for(var i=r.content,l=e.content.firstChild;l;l=l.nextSibling)i.appendChild(x(l,!0,n))}return r}function E(e,t){if(!t||j(e)!==j(t))return!1;for(var n=t;n;n=n.parentNode)if(n===e)return!0;return!1}function _(e){k(e instanceof H),w.call(this,e),this.parentNode_=void 0,this.firstChild_=void 0,this.lastChild_=void 0,this.nextSibling_=void 0,this.previousSibling_=void 0,this.treeScope_=void 0}var w=e.wrappers.EventTarget,S=e.wrappers.NodeList,I=e.TreeScope,k=e.assert,T=e.defineWrapGetter,C=e.enqueueMutation,j=e.getTreeScope,M=e.isWrapper,A=e.mixin,O=e.registerTransientObservers,L=e.registerWrapper,P=e.setTreeScope,N=e.unsafeUnwrap,D=e.unwrap,R=e.unwrapIfNeeded,F=e.wrap,B=e.wrapIfNeeded,U=e.wrappers,$=!1,V=document.importNode,q=window.Node.prototype.cloneNode,H=window.Node,G=window.DocumentFragment,W=(H.prototype.appendChild,H.prototype.compareDocumentPosition),z=H.prototype.isEqualNode,X=H.prototype.insertBefore,J=H.prototype.removeChild,Y=H.prototype.replaceChild,K=/Trident|Edge/.test(navigator.userAgent),Q=K?function(e,t){try{J.call(e,t)}catch(n){if(!(e instanceof G))throw n}}:function(e,t){J.call(e,t)};_.prototype=Object.create(w.prototype),A(_.prototype,{appendChild:function(e){return this.insertBefore(e,null)},insertBefore:function(e,n){t(e);var r;n?M(n)?r=D(n):(r=n,n=F(r)):(n=null,r=null),n&&k(n.parentNode===this);var l,s=n?n.previousSibling:this.lastChild,o=!this.invalidateShadowRenderer()&&!v(e);if(l=o?a(e):i(e,this,s,n),o)f(this,e),g(this),X.call(N(this),D(e),r);else{s||(this.firstChild_=l[0]),n||(this.lastChild_=l[l.length-1],void 0===this.firstChild_&&(this.firstChild_=this.firstChild));var u=r?r.parentNode:N(this);u?X.call(u,m(this,l),r):h(this,l)}return C(this,"childList",{addedNodes:l,nextSibling:n,previousSibling:s}),c(l,this),e},removeChild:function(e){if(t(e),e.parentNode!==this){for(var r=!1,l=(this.childNodes,this.firstChild);l;l=l.nextSibling)if(l===e){r=!0;break}if(!r)throw new Error("NotFoundError")}var i=D(e),a=e.nextSibling,s=e.previousSibling;if(this.invalidateShadowRenderer()){var o=this.firstChild,u=this.lastChild,c=i.parentNode;c&&Q(c,i),o===e&&(this.firstChild_=a),u===e&&(this.lastChild_=s),s&&(s.nextSibling_=a),a&&(a.previousSibling_=s),e.previousSibling_=e.nextSibling_=e.parentNode_=void 0}else g(this),Q(N(this),i);return $||C(this,"childList",{removedNodes:n(e),nextSibling:a,previousSibling:s}),O(this,e),e},replaceChild:function(e,r){t(e);var l;if(M(r)?l=D(r):(l=r,r=F(l)),r.parentNode!==this)throw new Error("NotFoundError");var s,o=r.nextSibling,u=r.previousSibling,d=!this.invalidateShadowRenderer()&&!v(e);return d?s=a(e):(o===e&&(o=e.nextSibling),s=i(e,this,u,o)),d?(f(this,e),g(this),Y.call(N(this),D(e),l)):(this.firstChild===r&&(this.firstChild_=s[0]),this.lastChild===r&&(this.lastChild_=s[s.length-1]),r.previousSibling_=r.nextSibling_=r.parentNode_=void 0,l.parentNode&&Y.call(l.parentNode,m(this,s),l)),C(this,"childList",{addedNodes:s,removedNodes:n(r),nextSibling:o,previousSibling:u}),p(r),c(s,this),r},nodeIsInserted_:function(){for(var e=this.firstChild;e;e=e.nextSibling)e.nodeIsInserted_()},hasChildNodes:function(){return null!==this.firstChild},get parentNode(){return void 0!==this.parentNode_?this.parentNode_:F(N(this).parentNode)},get firstChild(){return void 0!==this.firstChild_?this.firstChild_:F(N(this).firstChild)},get lastChild(){return void 0!==this.lastChild_?this.lastChild_:F(N(this).lastChild)},get nextSibling(){return void 0!==this.nextSibling_?this.nextSibling_:F(N(this).nextSibling)},get previousSibling(){return void 0!==this.previousSibling_?this.previousSibling_:F(N(this).previousSibling)},get parentElement(){for(var e=this.parentNode;e&&e.nodeType!==_.ELEMENT_NODE;)e=e.parentNode;return e},get textContent(){for(var e="",t=this.firstChild;t;t=t.nextSibling)t.nodeType!=_.COMMENT_NODE&&(e+=t.textContent);return e},set textContent(e){null==e&&(e="");var t=o(this.childNodes);if(this.invalidateShadowRenderer()){if(y(this),""!==e){var n=N(this).ownerDocument.createTextNode(e);this.appendChild(n)}}else g(this),N(this).textContent=e;var r=o(this.childNodes);C(this,"childList",{addedNodes:r,removedNodes:t}),d(t),c(r,this)},get childNodes(){for(var e=new S,t=0,n=this.firstChild;n;n=n.nextSibling)e[t++]=n;return e.length=t,e},cloneNode:function(e){return x(this,e)},contains:function(e){return E(this,B(e))},compareDocumentPosition:function(e){return W.call(N(this),R(e))},isEqualNode:function(e){return z.call(N(this),R(e))},normalize:function(){for(var e,t,n=o(this.childNodes),r=[],l="",i=0;i<n.length;i++)t=n[i],t.nodeType===_.TEXT_NODE?e||t.data.length?e?(l+=t.data,r.push(t)):e=t:this.removeChild(t):(e&&r.length&&(e.data+=l,b(r)),r=[],l="",e=null,t.childNodes.length&&t.normalize());e&&r.length&&(e.data+=l,b(r))}}),T(_,"ownerDocument"),L(H,_,document.createDocumentFragment()),delete _.prototype.querySelector,delete _.prototype.querySelectorAll,_.prototype=A(Object.create(w.prototype),_.prototype),e.cloneNode=x,e.nodeWasAdded=u,e.nodeWasRemoved=p,e.nodesWereAdded=c,e.nodesWereRemoved=d,e.originalInsertBefore=X,e.originalRemoveChild=J,e.snapshotNodeList=o,e.wrappers.Node=_}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n,r,l){for(var i=null,a=null,s=0,o=t.length;o>s;s++)i=b(t[s]),!l&&(a=y(i).root)&&a instanceof e.wrappers.ShadowRoot||(r[n++]=i);return n}function n(e){return String(e).replace(/\/deep\/|::shadow|>>>/g," ")}function r(e){return String(e).replace(/:host\(([^\s]+)\)/g,"$1").replace(/([^\s]):host/g,"$1").replace(":host","*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g," ")}function l(e,t){for(var n,r=e.firstElementChild;r;){if(r.matches(t))return r;if(n=l(r,t))return n;r=r.nextElementSibling}return null}function i(e,t){return e.matches(t)}function a(e,t,n){var r=e.localName;return r===t||r===n&&e.namespaceURI===M}function s(){return!0}function o(e,t,n){return e.localName===n}function u(e,t){return e.namespaceURI===t}function c(e,t,n){return e.namespaceURI===t&&e.localName===n}function p(e,t,n,r,l,i){for(var a=e.firstElementChild;a;)r(a,l,i)&&(n[t++]=a),t=p(a,t,n,r,l,i),a=a.nextElementSibling;return t}function d(n,r,l,i,a){var s,o=v(this),u=y(this).root;if(u instanceof e.wrappers.ShadowRoot)return p(this,r,l,n,i,null);if(o instanceof C)s=w.call(o,i);else{if(!(o instanceof j))return p(this,r,l,n,i,null);s=_.call(o,i)}return t(s,r,l,a)}function f(n,r,l,i,a){var s,o=v(this),u=y(this).root;if(u instanceof e.wrappers.ShadowRoot)return p(this,r,l,n,i,a);if(o instanceof C)s=I.call(o,i,a);else{if(!(o instanceof j))return p(this,r,l,n,i,a);s=S.call(o,i,a)}return t(s,r,l,!1)}function h(n,r,l,i,a){var s,o=v(this),u=y(this).root;if(u instanceof e.wrappers.ShadowRoot)return p(this,r,l,n,i,a);if(o instanceof C)s=T.call(o,i,a);else{if(!(o instanceof j))return p(this,r,l,n,i,a);s=k.call(o,i,a)}return t(s,r,l,!1)}var m=e.wrappers.HTMLCollection,g=e.wrappers.NodeList,y=e.getTreeScope,v=e.unsafeUnwrap,b=e.wrap,x=document.querySelector,E=document.documentElement.querySelector,_=document.querySelectorAll,w=document.documentElement.querySelectorAll,S=document.getElementsByTagName,I=document.documentElement.getElementsByTagName,k=document.getElementsByTagNameNS,T=document.documentElement.getElementsByTagNameNS,C=window.Element,j=window.HTMLDocument||window.Document,M="http://www.w3.org/1999/xhtml",A={querySelector:function(t){var r=n(t),i=r!==t;t=r;var a,s=v(this),o=y(this).root;if(o instanceof e.wrappers.ShadowRoot)return l(this,t);if(s instanceof C)a=b(E.call(s,t));else{if(!(s instanceof j))return l(this,t);a=b(x.call(s,t))}return a&&!i&&(o=y(a).root)&&o instanceof e.wrappers.ShadowRoot?l(this,t):a},querySelectorAll:function(e){var t=n(e),r=t!==e;e=t;var l=new g;return l.length=d.call(this,i,0,l,e,r),l}},O={matches:function(t){return t=r(t),e.originalMatches.call(v(this),t)}},L={getElementsByTagName:function(e){var t=new m,n="*"===e?s:a;return t.length=f.call(this,n,0,t,e,e.toLowerCase()),t},getElementsByClassName:function(e){return this.querySelectorAll("."+e)},getElementsByTagNameNS:function(e,t){var n=new m,r=null;return r="*"===e?"*"===t?s:o:"*"===t?u:c,n.length=h.call(this,r,0,n,e||null,t),n}};e.GetElementsByInterface=L,e.SelectorsInterface=A,e.MatchesInterface=O}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;return e}function n(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.previousSibling;return e}var r=e.wrappers.NodeList,l={get firstElementChild(){return t(this.firstChild)},get lastElementChild(){return n(this.lastChild)},get childElementCount(){for(var e=0,t=this.firstElementChild;t;t=t.nextElementSibling)e++;return e},get children(){for(var e=new r,t=0,n=this.firstElementChild;n;n=n.nextElementSibling)e[t++]=n;return e.length=t,e},remove:function(){var e=this.parentNode;e&&e.removeChild(this)}},i={get nextElementSibling(){return t(this.nextSibling)},get previousElementSibling(){return n(this.previousSibling)}};e.ChildNodeInterface=i,e.ParentNodeInterface=l}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}var n=e.ChildNodeInterface,r=e.wrappers.Node,l=e.enqueueMutation,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,o=window.CharacterData;t.prototype=Object.create(r.prototype),i(t.prototype,{get nodeValue(){return this.data},set nodeValue(e){this.data=e},get textContent(){return this.data},set textContent(e){this.data=e},get data(){return s(this).data},set data(e){var t=s(this).data;l(this,"characterData",{oldValue:t}),s(this).data=e}}),i(t.prototype,n),a(o,t,document.createTextNode("")),e.wrappers.CharacterData=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e>>>0}function n(e){r.call(this,e)}var r=e.wrappers.CharacterData,l=(e.enqueueMutation,e.mixin),i=e.registerWrapper,a=window.Text;n.prototype=Object.create(r.prototype),l(n.prototype,{splitText:function(e){e=t(e);var n=this.data;if(e>n.length)throw new Error("IndexSizeError");var r=n.slice(0,e),l=n.slice(e);this.data=r;var i=this.ownerDocument.createTextNode(l);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}}),i(a,n,document.createTextNode("")),e.wrappers.Text=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return i(e).getAttribute("class")}function n(e,t){a(e,"attributes",{name:"class",namespace:null,oldValue:t})}function r(t){e.invalidateRendererBasedOnAttribute(t,"class")}function l(e,l,i){var a=e.ownerElement_;if(null==a)return l.apply(e,i);var s=t(a),o=l.apply(e,i);return t(a)!==s&&(n(a,s),r(a)),o}if(!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH.");var i=e.unsafeUnwrap,a=e.enqueueMutation,s=DOMTokenList.prototype.add;DOMTokenList.prototype.add=function(){l(this,s,arguments)};var o=DOMTokenList.prototype.remove;DOMTokenList.prototype.remove=function(){l(this,o,arguments)};var u=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(){return l(this,u,arguments)}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n){var r=t.parentNode;if(r&&r.shadowRoot){var l=e.getRendererForHost(r);l.dependsOnAttribute(n)&&l.invalidate()}}function n(e,t,n){c(e,"attributes",{name:t,namespace:null,oldValue:n})}function r(e){a.call(this,e)}var l=e.ChildNodeInterface,i=e.GetElementsByInterface,a=e.wrappers.Node,s=e.ParentNodeInterface,o=e.SelectorsInterface,u=e.MatchesInterface,c=(e.addWrapNodeListMethod,e.enqueueMutation),p=e.mixin,d=(e.oneOf,e.registerWrapper),f=e.unsafeUnwrap,h=e.wrappers,m=window.Element,g=["matches","mozMatchesSelector","msMatchesSelector","webkitMatchesSelector"].filter(function(e){return m.prototype[e]}),y=g[0],v=m.prototype[y],b=new WeakMap;r.prototype=Object.create(a.prototype),p(r.prototype,{createShadowRoot:function(){var t=new h.ShadowRoot(this);f(this).polymerShadowRoot_=t;var n=e.getRendererForHost(this);return n.invalidate(),t},get shadowRoot(){return f(this).polymerShadowRoot_||null},setAttribute:function(e,r){var l=f(this).getAttribute(e);f(this).setAttribute(e,r),n(this,e,l),t(this,e)},removeAttribute:function(e){var r=f(this).getAttribute(e);f(this).removeAttribute(e),n(this,e,r),t(this,e)},get classList(){var e=b.get(this);if(!e){if(e=f(this).classList,!e)return;e.ownerElement_=this,b.set(this,e)}return e},get className(){return f(this).className},set className(e){this.setAttribute("class",e)},get id(){return f(this).id},set id(e){this.setAttribute("id",e)}}),g.forEach(function(e){"matches"!==e&&(r.prototype[e]=function(e){return this.matches(e)})}),m.prototype.webkitCreateShadowRoot&&(r.prototype.webkitCreateShadowRoot=r.prototype.createShadowRoot),p(r.prototype,l),p(r.prototype,i),p(r.prototype,s),p(r.prototype,o),p(r.prototype,u),d(m,r,document.createElementNS(null,"x")),e.invalidateRendererBasedOnAttribute=t,e.matchesNames=g,e.originalMatches=v,e.wrappers.Element=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case" ":return"&nbsp;"}}function n(e){return e.replace(k,t)}function r(e){return e.replace(T,t)}function l(e){for(var t={},n=0;n<e.length;n++)t[e[n]]=!0;return t}function i(e,t){switch(e.nodeType){case Node.ELEMENT_NODE:for(var l,i=e.tagName.toLowerCase(),s="<"+i,o=e.attributes,u=0;l=o[u];u++)s+=" "+l.name+'="'+n(l.value)+'"';return s+=">",C[i]?s:s+a(e)+"</"+i+">";case Node.TEXT_NODE:var c=e.data;return t&&j[t.localName]?c:r(c);case Node.COMMENT_NODE:return"<!--"+e.data+"-->";default:throw console.error(e),new Error("not implemented")}}function a(e){e instanceof I.HTMLTemplateElement&&(e=e.content);for(var t="",n=e.firstChild;n;n=n.nextSibling)t+=i(n,e);return t}function s(e,t,n){var r=n||"div";e.textContent="";var l=w(e.ownerDocument.createElement(r));l.innerHTML=t;for(var i;i=l.firstChild;)e.appendChild(S(i))}function o(e){h.call(this,e)}function u(e,t){var n=w(e.cloneNode(!1));n.innerHTML=t;for(var r,l=w(document.createDocumentFragment());r=n.firstChild;)l.appendChild(r);return S(l)}function c(t){return function(){return e.renderAllPending(),_(this)[t]}}function p(e){m(o,e,c(e))}function d(t){Object.defineProperty(o.prototype,t,{get:c(t),set:function(n){e.renderAllPending(),_(this)[t]=n},configurable:!0,enumerable:!0})}function f(t){Object.defineProperty(o.prototype,t,{value:function(){return e.renderAllPending(),_(this)[t].apply(_(this),arguments)},configurable:!0,enumerable:!0})}var h=e.wrappers.Element,m=e.defineGetter,g=e.enqueueMutation,y=e.mixin,v=e.nodesWereAdded,b=e.nodesWereRemoved,x=e.registerWrapper,E=e.snapshotNodeList,_=e.unsafeUnwrap,w=e.unwrap,S=e.wrap,I=e.wrappers,k=/[&\u00A0"]/g,T=/[&\u00A0<>]/g,C=l(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),j=l(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]),M=/MSIE/.test(navigator.userAgent),A=window.HTMLElement,O=window.HTMLTemplateElement;o.prototype=Object.create(h.prototype),y(o.prototype,{get innerHTML(){return a(this)},set innerHTML(e){if(M&&j[this.localName])return void(this.textContent=e);var t=E(this.childNodes);this.invalidateShadowRenderer()?this instanceof I.HTMLTemplateElement?s(this.content,e):s(this,e,this.tagName):!O&&this instanceof I.HTMLTemplateElement?s(this.content,e):_(this).innerHTML=e;var n=E(this.childNodes);g(this,"childList",{addedNodes:n,removedNodes:t}),b(t),v(n,this)},get outerHTML(){return i(this,this.parentNode)},set outerHTML(e){var t=this.parentNode;if(t){t.invalidateShadowRenderer();var n=u(t,e);t.replaceChild(n,this)}},insertAdjacentHTML:function(e,t){var n,r;switch(String(e).toLowerCase()){case"beforebegin":n=this.parentNode,r=this;break;case"afterend":n=this.parentNode,r=this.nextSibling;break;case"afterbegin":n=this,r=this.firstChild;break;case"beforeend":n=this,r=null;break;default:return}var l=u(n,t);n.insertBefore(l,r)},get hidden(){return this.hasAttribute("hidden")},set hidden(e){e?this.setAttribute("hidden",""):this.removeAttribute("hidden")}}),["clientHeight","clientLeft","clientTop","clientWidth","offsetHeight","offsetLeft","offsetTop","offsetWidth","scrollHeight","scrollWidth"].forEach(p),["scrollLeft","scrollTop"].forEach(d),["getBoundingClientRect","getClientRects","scrollIntoView"].forEach(f),x(A,o,document.createElement("b")),e.wrappers.HTMLElement=o,e.getInnerHTML=a,e.setInnerHTML=s}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.HTMLCanvasElement;t.prototype=Object.create(n.prototype),r(t.prototype,{getContext:function(){var e=i(this).getContext.apply(i(this),arguments);return e&&a(e)}}),l(s,t,document.createElement("canvas")),e.wrappers.HTMLCanvasElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=window.HTMLContentElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get select(){return this.getAttribute("select")},set select(e){this.setAttribute("select",e)},setAttribute:function(e,t){n.prototype.setAttribute.call(this,e,t),"select"===String(e).toLowerCase()&&this.invalidateShadowRenderer(!0)}}),i&&l(i,t),e.wrappers.HTMLContentElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=window.HTMLFormElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get elements(){return i(a(this).elements)}}),l(s,t,document.createElement("form")),e.wrappers.HTMLFormElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e,t){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var l=i(document.createElement("img"));r.call(this,l),a(l,this),void 0!==e&&(l.width=e),void 0!==t&&(l.height=t)}var r=e.wrappers.HTMLElement,l=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLImageElement;t.prototype=Object.create(r.prototype),l(s,t,document.createElement("img")),n.prototype=t.prototype,e.wrappers.HTMLImageElement=t,e.wrappers.Image=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=(e.mixin,e.wrappers.NodeList,e.registerWrapper),l=window.HTMLShadowElement;t.prototype=Object.create(n.prototype),t.prototype.constructor=t,l&&r(l,t),e.wrappers.HTMLShadowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){if(!e.defaultView)return e;var t=p.get(e);if(!t){for(t=e.implementation.createHTMLDocument("");t.lastChild;)t.removeChild(t.lastChild);p.set(e,t)}return t}function n(e){for(var n,r=t(e.ownerDocument),l=o(r.createDocumentFragment());n=e.firstChild;)l.appendChild(n);return l}function r(e){if(l.call(this,e),!d){var t=n(e);c.set(this,u(t))}}var l=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,o=e.unwrap,u=e.wrap,c=new WeakMap,p=new WeakMap,d=window.HTMLTemplateElement;r.prototype=Object.create(l.prototype),i(r.prototype,{constructor:r,get content(){return d?u(s(this).content):c.get(this)}}),d&&a(d,r),e.wrappers.HTMLTemplateElement=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.registerWrapper,l=window.HTMLMediaElement;l&&(t.prototype=Object.create(n.prototype),r(l,t,document.createElement("audio")),e.wrappers.HTMLMediaElement=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var t=i(document.createElement("audio"));r.call(this,t),a(t,this),t.setAttribute("preload","auto"),void 0!==e&&t.setAttribute("src",e)}var r=e.wrappers.HTMLMediaElement,l=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLAudioElement;s&&(t.prototype=Object.create(r.prototype),l(s,t,document.createElement("audio")),n.prototype=t.prototype,e.wrappers.HTMLAudioElement=t,e.wrappers.Audio=n)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e.replace(/\s+/g," ").trim()}function n(e){l.call(this,e)}function r(e,t,n,i){if(!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function.");var a=o(document.createElement("option"));l.call(this,a),s(a,this),void 0!==e&&(a.text=e),void 0!==t&&a.setAttribute("value",t),n===!0&&a.setAttribute("selected",""),a.selected=i===!0}var l=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.rewrap,o=e.unwrap,u=e.wrap,c=window.HTMLOptionElement;n.prototype=Object.create(l.prototype),i(n.prototype,{get text(){return t(this.textContent)},set text(e){this.textContent=t(String(e))},get form(){return u(o(this).form)}}),a(c,n,document.createElement("option")),r.prototype=n.prototype,e.wrappers.HTMLOptionElement=n,e.wrappers.Option=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.unwrap,a=e.wrap,s=window.HTMLSelectElement;t.prototype=Object.create(n.prototype),r(t.prototype,{add:function(e,t){"object"==typeof t&&(t=i(t)),i(this).add(i(e),t)},remove:function(e){return void 0===e?void n.prototype.remove.call(this):("object"==typeof e&&(e=i(e)),void i(this).remove(e))},get form(){return a(i(this).form)}}),l(s,t,document.createElement("select")),e.wrappers.HTMLSelectElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.unwrap,a=e.wrap,s=e.wrapHTMLCollection,o=window.HTMLTableElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get caption(){return a(i(this).caption)},createCaption:function(){return a(i(this).createCaption())},get tHead(){return a(i(this).tHead)},createTHead:function(){return a(i(this).createTHead())},createTFoot:function(){return a(i(this).createTFoot())},get tFoot(){return a(i(this).tFoot)},get tBodies(){return s(i(this).tBodies)},createTBody:function(){return a(i(this).createTBody())},get rows(){return s(i(this).rows)},insertRow:function(e){return a(i(this).insertRow(e))}}),l(o,t,document.createElement("table")),e.wrappers.HTMLTableElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,o=window.HTMLTableSectionElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get rows(){return i(a(this).rows)},insertRow:function(e){return s(a(this).insertRow(e))}}),l(o,t,document.createElement("thead")),e.wrappers.HTMLTableSectionElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,l=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,o=window.HTMLTableRowElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get cells(){return i(a(this).cells)},insertCell:function(e){return s(a(this).insertCell(e))}}),l(o,t,document.createElement("tr")),e.wrappers.HTMLTableRowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e.localName){case"content":return new n(e);case"shadow":return new l(e);case"template":return new i(e)}r.call(this,e)}var n=e.wrappers.HTMLContentElement,r=e.wrappers.HTMLElement,l=e.wrappers.HTMLShadowElement,i=e.wrappers.HTMLTemplateElement,a=(e.mixin,e.registerWrapper),s=window.HTMLUnknownElement;t.prototype=Object.create(r.prototype),a(s,t),e.wrappers.HTMLUnknownElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.wrappers.Element,n=e.wrappers.HTMLElement,r=e.registerObject,l=e.defineWrapGetter,i="http://www.w3.org/2000/svg",a=document.createElementNS(i,"title"),s=r(a),o=Object.getPrototypeOf(s.prototype).constructor;if(!("classList"in a)){var u=Object.getOwnPropertyDescriptor(t.prototype,"classList");Object.defineProperty(n.prototype,"classList",u),delete t.prototype.classList}l(o,"ownerSVGElement"),e.wrappers.SVGElement=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){d.call(this,e)}var n=e.mixin,r=e.registerWrapper,l=e.unwrap,i=e.wrap,a=window.SVGUseElement,s="http://www.w3.org/2000/svg",o=i(document.createElementNS(s,"g")),u=document.createElementNS(s,"use"),c=o.constructor,p=Object.getPrototypeOf(c.prototype),d=p.constructor;t.prototype=Object.create(p),"instanceRoot"in u&&n(t.prototype,{get instanceRoot(){return i(l(this).instanceRoot)},get animatedInstanceRoot(){return i(l(this).animatedInstanceRoot)}}),r(a,t,u),e.wrappers.SVGUseElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.mixin,l=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.SVGElementInstance;s&&(t.prototype=Object.create(n.prototype),r(t.prototype,{get correspondingElement(){return a(i(this).correspondingElement)},get correspondingUseElement(){return a(i(this).correspondingUseElement)},get parentNode(){return a(i(this).parentNode)},get childNodes(){throw new Error("Not implemented")},get firstChild(){return a(i(this).firstChild)},get lastChild(){return a(i(this).lastChild)},get previousSibling(){return a(i(this).previousSibling)},get nextSibling(){return a(i(this).nextSibling)}}),l(s,t),e.wrappers.SVGElementInstance=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){l(e,this)}var n=e.mixin,r=e.registerWrapper,l=e.setWrapper,i=e.unsafeUnwrap,a=e.unwrap,s=e.unwrapIfNeeded,o=e.wrap,u=window.CanvasRenderingContext2D;n(t.prototype,{get canvas(){return o(i(this).canvas)},drawImage:function(){arguments[0]=s(arguments[0]),i(this).drawImage.apply(i(this),arguments)},createPattern:function(){return arguments[0]=a(arguments[0]),i(this).createPattern.apply(i(this),arguments)}}),r(u,t,document.createElement("canvas").getContext("2d")),e.wrappers.CanvasRenderingContext2D=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){l(e,this)}var n=e.mixin,r=e.registerWrapper,l=e.setWrapper,i=e.unsafeUnwrap,a=e.unwrapIfNeeded,s=e.wrap,o=window.WebGLRenderingContext;if(o){n(t.prototype,{get canvas(){return s(i(this).canvas)},texImage2D:function(){arguments[5]=a(arguments[5]),i(this).texImage2D.apply(i(this),arguments)},texSubImage2D:function(){arguments[6]=a(arguments[6]),i(this).texSubImage2D.apply(i(this),arguments)}});var u=/WebKit/.test(navigator.userAgent)?{drawingBufferHeight:null,drawingBufferWidth:null}:{};r(o,t,u),e.wrappers.WebGLRenderingContext=t}}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.GetElementsByInterface,n=e.ParentNodeInterface,r=e.SelectorsInterface,l=e.mixin,i=e.registerObject,a=i(document.createDocumentFragment());l(a.prototype,n),l(a.prototype,r),l(a.prototype,t);var s=i(document.createComment(""));e.wrappers.Comment=s,e.wrappers.DocumentFragment=a}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=p(c(e).ownerDocument.createDocumentFragment());n.call(this,t),o(t,this);var l=e.shadowRoot;f.set(this,l),this.treeScope_=new r(this,a(l||e)),d.set(this,e)}var n=e.wrappers.DocumentFragment,r=e.TreeScope,l=e.elementFromPoint,i=e.getInnerHTML,a=e.getTreeScope,s=e.mixin,o=e.rewrap,u=e.setInnerHTML,c=e.unsafeUnwrap,p=e.unwrap,d=new WeakMap,f=new WeakMap,h=/[ \t\n\r\f]/;t.prototype=Object.create(n.prototype),s(t.prototype,{constructor:t,get innerHTML(){return i(this)},set innerHTML(e){u(this,e),this.invalidateShadowRenderer()},get olderShadowRoot(){return f.get(this)||null},get host(){return d.get(this)||null},invalidateShadowRenderer:function(){return d.get(this).invalidateShadowRenderer()},elementFromPoint:function(e,t){return l(this,this.ownerDocument,e,t)},getElementById:function(e){return h.test(e)?null:this.querySelector('[id="'+e+'"]')}}),e.wrappers.ShadowRoot=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=p(e).root;return t instanceof f?t.host:null}function n(t,n){if(t.shadowRoot){n=Math.min(t.childNodes.length-1,n);var r=t.childNodes[n];if(r){var l=e.getDestinationInsertionPoints(r);if(l.length>0){var i=l[0].parentNode;i.nodeType==Node.ELEMENT_NODE&&(t=i)}}}return t}function r(e){return e=c(e),t(e)||e}function l(e){a(e,this)}var i=e.registerWrapper,a=e.setWrapper,s=e.unsafeUnwrap,o=e.unwrap,u=e.unwrapIfNeeded,c=e.wrap,p=e.getTreeScope,d=window.Range,f=e.wrappers.ShadowRoot;l.prototype={get startContainer(){return r(s(this).startContainer)},get endContainer(){return r(s(this).endContainer)},get commonAncestorContainer(){return r(s(this).commonAncestorContainer)},setStart:function(e,t){e=n(e,t),s(this).setStart(u(e),t)},setEnd:function(e,t){e=n(e,t),s(this).setEnd(u(e),t)},setStartBefore:function(e){s(this).setStartBefore(u(e))},setStartAfter:function(e){s(this).setStartAfter(u(e))},setEndBefore:function(e){s(this).setEndBefore(u(e))},setEndAfter:function(e){s(this).setEndAfter(u(e))},selectNode:function(e){s(this).selectNode(u(e))},selectNodeContents:function(e){s(this).selectNodeContents(u(e))},compareBoundaryPoints:function(e,t){return s(this).compareBoundaryPoints(e,o(t))},extractContents:function(){return c(s(this).extractContents())},cloneContents:function(){return c(s(this).cloneContents())},insertNode:function(e){s(this).insertNode(u(e))},surroundContents:function(e){s(this).surroundContents(u(e))},cloneRange:function(){return c(s(this).cloneRange())},isPointInRange:function(e,t){return s(this).isPointInRange(u(e),t)},comparePoint:function(e,t){return s(this).comparePoint(u(e),t)},intersectsNode:function(e){return s(this).intersectsNode(u(e))},toString:function(){return s(this).toString()}},d.prototype.createContextualFragment&&(l.prototype.createContextualFragment=function(e){return c(s(this).createContextualFragment(e))}),i(window.Range,l,document.createRange()),e.wrappers.Range=l}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.previousSibling_=e.previousSibling,e.nextSibling_=e.nextSibling,e.parentNode_=e.parentNode}function n(n,l,i){var a=L(n),s=L(l),o=i?L(i):null;if(r(l),t(l),i)n.firstChild===i&&(n.firstChild_=i),i.previousSibling_=i.previousSibling;else{n.lastChild_=n.lastChild,n.lastChild===n.firstChild&&(n.firstChild_=n.firstChild);var u=P(a.lastChild);u&&(u.nextSibling_=u.nextSibling)}e.originalInsertBefore.call(a,s,o)}function r(n){var r=L(n),l=r.parentNode;if(l){var i=P(l);t(n),n.previousSibling&&(n.previousSibling.nextSibling_=n),n.nextSibling&&(n.nextSibling.previousSibling_=n),i.lastChild===n&&(i.lastChild_=n),i.firstChild===n&&(i.firstChild_=n),e.originalRemoveChild.call(l,r)}}function l(e){D.set(e,[])}function i(e){var t=D.get(e);return t||D.set(e,t=[]),t}function a(e){for(var t=[],n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t}function s(){for(var e=0;e<U.length;e++){var t=U[e],n=t.parentRenderer;n&&n.dirty||t.render()}U=[]}function o(){S=null,s()}function u(e){var t=F.get(e);return t||(t=new f(e),F.set(e,t)),t}function c(e){var t=M(e).root;return t instanceof j?t:null}function p(e){return u(e.host)}function d(e){this.skip=!1,this.node=e,this.childNodes=[]}function f(e){this.host=e,this.dirty=!1,this.invalidateAttributes(),this.associateNode(e)}function h(e){for(var t=[],n=e.firstChild;n;n=n.nextSibling)E(n)?t.push.apply(t,i(n)):t.push(n);return t}function m(e){if(e instanceof T)return e;if(e instanceof k)return null;for(var t=e.firstChild;t;t=t.nextSibling){var n=m(t);if(n)return n}return null}function g(e,t){i(t).push(e);var n=R.get(e);n?n.push(t):R.set(e,[t]); }function y(e){return R.get(e)}function v(e){R.set(e,void 0)}function b(e,t){var n=t.getAttribute("select");if(!n)return!0;if(n=n.trim(),!n)return!0;if(!(e instanceof I))return!1;if(!V.test(n))return!1;try{return e.matches(n)}catch(r){return!1}}function x(e,t){var n=y(t);return n&&n[n.length-1]===e}function E(e){return e instanceof k||e instanceof T}function _(e){return e.shadowRoot}function w(e){for(var t=[],n=e.shadowRoot;n;n=n.olderShadowRoot)t.push(n);return t}var S,I=e.wrappers.Element,k=e.wrappers.HTMLContentElement,T=e.wrappers.HTMLShadowElement,C=e.wrappers.Node,j=e.wrappers.ShadowRoot,M=(e.assert,e.getTreeScope),A=(e.mixin,e.oneOf),O=e.unsafeUnwrap,L=e.unwrap,P=e.wrap,N=e.ArraySplice,D=new WeakMap,R=new WeakMap,F=new WeakMap,B=A(window,["requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","setTimeout"]),U=[],$=new N;$.equals=function(e,t){return L(e.node)===t},d.prototype={append:function(e){var t=new d(e);return this.childNodes.push(t),t},sync:function(e){if(!this.skip){for(var t=this.node,l=this.childNodes,i=a(L(t)),s=e||new WeakMap,o=$.calculateSplices(l,i),u=0,c=0,p=0,d=0;d<o.length;d++){for(var f=o[d];p<f.index;p++)c++,l[u++].sync(s);for(var h=f.removed.length,m=0;h>m;m++){var g=P(i[c++]);s.get(g)||r(g)}for(var y=f.addedCount,v=i[c]&&P(i[c]),m=0;y>m;m++){var b=l[u++],x=b.node;n(t,x,v),s.set(x,!0),b.sync(s)}p+=y}for(var d=p;d<l.length;d++)l[d].sync(s)}}},f.prototype={render:function(e){if(this.dirty){this.invalidateAttributes();var t=this.host;this.distribution(t);var n=e||new d(t);this.buildRenderTree(n,t);var r=!e;r&&n.sync(),this.dirty=!1}},get parentRenderer(){return M(this.host).renderer},invalidate:function(){if(!this.dirty){this.dirty=!0;var e=this.parentRenderer;if(e&&e.invalidate(),U.push(this),S)return;S=window[B](o,0)}},distribution:function(e){this.resetAllSubtrees(e),this.distributionResolution(e)},resetAll:function(e){E(e)?l(e):v(e),this.resetAllSubtrees(e)},resetAllSubtrees:function(e){for(var t=e.firstChild;t;t=t.nextSibling)this.resetAll(t);e.shadowRoot&&this.resetAll(e.shadowRoot),e.olderShadowRoot&&this.resetAll(e.olderShadowRoot)},distributionResolution:function(e){if(_(e)){for(var t=e,n=h(t),r=w(t),l=0;l<r.length;l++)this.poolDistribution(r[l],n);for(var l=r.length-1;l>=0;l--){var i=r[l],a=m(i);if(a){var s=i.olderShadowRoot;s&&(n=h(s));for(var o=0;o<n.length;o++)g(n[o],a)}this.distributionResolution(i)}}for(var u=e.firstChild;u;u=u.nextSibling)this.distributionResolution(u)},poolDistribution:function(e,t){if(!(e instanceof T))if(e instanceof k){var n=e;this.updateDependentAttributes(n.getAttribute("select"));for(var r=!1,l=0;l<t.length;l++){var e=t[l];e&&b(e,n)&&(g(e,n),t[l]=void 0,r=!0)}if(!r)for(var i=n.firstChild;i;i=i.nextSibling)g(i,n)}else for(var i=e.firstChild;i;i=i.nextSibling)this.poolDistribution(i,t)},buildRenderTree:function(e,t){for(var n=this.compose(t),r=0;r<n.length;r++){var l=n[r],i=e.append(l);this.buildRenderTree(i,l)}if(_(t)){var a=u(t);a.dirty=!1}},compose:function(e){for(var t=[],n=e.shadowRoot||e,r=n.firstChild;r;r=r.nextSibling)if(E(r)){this.associateNode(n);for(var l=i(r),a=0;a<l.length;a++){var s=l[a];x(r,s)&&t.push(s)}}else t.push(r);return t},invalidateAttributes:function(){this.attributes=Object.create(null)},updateDependentAttributes:function(e){if(e){var t=this.attributes;/\.\w+/.test(e)&&(t["class"]=!0),/#\w+/.test(e)&&(t.id=!0),e.replace(/\[\s*([^\s=\|~\]]+)/g,function(e,n){t[n]=!0})}},dependsOnAttribute:function(e){return this.attributes[e]},associateNode:function(e){O(e).polymerShadowRenderer_=this}};var V=/^(:not\()?[*.#[a-zA-Z_|]/;C.prototype.invalidateShadowRenderer=function(e){var t=O(this).polymerShadowRenderer_;return t?(t.invalidate(),!0):!1},k.prototype.getDistributedNodes=T.prototype.getDistributedNodes=function(){return s(),i(this)},I.prototype.getDestinationInsertionPoints=function(){return s(),y(this)||[]},k.prototype.nodeIsInserted_=T.prototype.nodeIsInserted_=function(){this.invalidateShadowRenderer();var e,t=c(this);t&&(e=p(t)),O(this).polymerShadowRenderer_=e,e&&e.invalidate()},e.getRendererForHost=u,e.getShadowTrees=w,e.renderAllPending=s,e.getDestinationInsertionPoints=y,e.visual={insertBefore:n,remove:r}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t){if(window[t]){r(!e.wrappers[t]);var o=function(e){n.call(this,e)};o.prototype=Object.create(n.prototype),l(o.prototype,{get form(){return s(a(this).form)}}),i(window[t],o,document.createElement(t.slice(4,-7))),e.wrappers[t]=o}}var n=e.wrappers.HTMLElement,r=e.assert,l=e.mixin,i=e.registerWrapper,a=e.unwrap,s=e.wrap,o=["HTMLButtonElement","HTMLFieldSetElement","HTMLInputElement","HTMLKeygenElement","HTMLLabelElement","HTMLLegendElement","HTMLObjectElement","HTMLOutputElement","HTMLTextAreaElement"];o.forEach(t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r(e,this)}var n=e.registerWrapper,r=e.setWrapper,l=e.unsafeUnwrap,i=e.unwrap,a=e.unwrapIfNeeded,s=e.wrap,o=window.Selection;t.prototype={get anchorNode(){return s(l(this).anchorNode)},get focusNode(){return s(l(this).focusNode)},addRange:function(e){l(this).addRange(a(e))},collapse:function(e,t){l(this).collapse(a(e),t)},containsNode:function(e,t){return l(this).containsNode(a(e),t)},getRangeAt:function(e){return s(l(this).getRangeAt(e))},removeRange:function(e){l(this).removeRange(i(e))},selectAllChildren:function(e){l(this).selectAllChildren(a(e))},toString:function(){return l(this).toString()}},o.prototype.extend&&(t.prototype.extend=function(e,t){l(this).extend(a(e),t)}),n(window.Selection,t,window.getSelection()),e.wrappers.Selection=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r(e,this)}var n=e.registerWrapper,r=e.setWrapper,l=e.unsafeUnwrap,i=e.unwrapIfNeeded,a=e.wrap,s=window.TreeWalker;t.prototype={get root(){return a(l(this).root)},get currentNode(){return a(l(this).currentNode)},set currentNode(e){l(this).currentNode=i(e)},get filter(){return l(this).filter},parentNode:function(){return a(l(this).parentNode())},firstChild:function(){return a(l(this).firstChild())},lastChild:function(){return a(l(this).lastChild())},previousSibling:function(){return a(l(this).previousSibling())},previousNode:function(){return a(l(this).previousNode())},nextNode:function(){return a(l(this).nextNode())}},n(s,t),e.wrappers.TreeWalker=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){c.call(this,e),this.treeScope_=new m(this,null)}function n(e){var n=document[e];t.prototype[e]=function(){return C(n.apply(k(this),arguments))}}function r(e,t){A.call(k(t),T(e)),l(e,t)}function l(e,t){e.shadowRoot&&t.adoptNode(e.shadowRoot),e instanceof h&&i(e,t);for(var n=e.firstChild;n;n=n.nextSibling)l(n,t)}function i(e,t){var n=e.olderShadowRoot;n&&t.adoptNode(n)}function a(e){I(e,this)}function s(e,t){var n=document.implementation[t];e.prototype[t]=function(){return C(n.apply(k(this),arguments))}}function o(e,t){var n=document.implementation[t];e.prototype[t]=function(){return n.apply(k(this),arguments)}}var u=e.GetElementsByInterface,c=e.wrappers.Node,p=e.ParentNodeInterface,d=e.wrappers.Selection,f=e.SelectorsInterface,h=e.wrappers.ShadowRoot,m=e.TreeScope,g=e.cloneNode,y=e.defineWrapGetter,v=e.elementFromPoint,b=e.forwardMethodsToWrapper,x=e.matchesNames,E=e.mixin,_=e.registerWrapper,w=e.renderAllPending,S=e.rewrap,I=e.setWrapper,k=e.unsafeUnwrap,T=e.unwrap,C=e.wrap,j=e.wrapEventTargetMethods,M=(e.wrapNodeList,new WeakMap);t.prototype=Object.create(c.prototype),y(t,"documentElement"),y(t,"body"),y(t,"head"),["createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode","getElementById"].forEach(n);var A=document.adoptNode,O=document.getSelection;E(t.prototype,{adoptNode:function(e){return e.parentNode&&e.parentNode.removeChild(e),r(e,this),e},elementFromPoint:function(e,t){return v(this,this,e,t)},importNode:function(e,t){return g(e,t,k(this))},getSelection:function(){return w(),new d(O.call(T(this)))},getElementsByName:function(e){return f.querySelectorAll.call(this,"[name="+JSON.stringify(String(e))+"]")}});var L=document.createTreeWalker,P=e.wrappers.TreeWalker;if(t.prototype.createTreeWalker=function(e,t,n,r){var l=null;return n&&(n.acceptNode&&"function"==typeof n.acceptNode?l={acceptNode:function(e){return n.acceptNode(C(e))}}:"function"==typeof n&&(l=function(e){return n(C(e))})),new P(L.call(T(this),T(e),t,l,r))},document.registerElement){var N=document.registerElement;t.prototype.registerElement=function(t,n){function r(e){return e?void I(e,this):i?document.createElement(i,t):document.createElement(t)}var l,i;if(void 0!==n&&(l=n.prototype,i=n["extends"]),l||(l=Object.create(HTMLElement.prototype)),e.nativePrototypeTable.get(l))throw new Error("NotSupportedError");for(var a,s=Object.getPrototypeOf(l),o=[];s&&!(a=e.nativePrototypeTable.get(s));)o.push(s),s=Object.getPrototypeOf(s);if(!a)throw new Error("NotSupportedError");for(var u=Object.create(a),c=o.length-1;c>=0;c--)u=Object.create(u);["createdCallback","attachedCallback","detachedCallback","attributeChangedCallback"].forEach(function(e){var t=l[e];t&&(u[e]=function(){C(this)instanceof r||S(this),t.apply(C(this),arguments)})});var p={prototype:u};i&&(p["extends"]=i),r.prototype=l,r.prototype.constructor=r,e.constructorTable.set(u,r),e.nativePrototypeTable.set(l,u);N.call(T(this),t,p);return r},b([window.HTMLDocument||window.Document],["registerElement"])}b([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement,window.HTMLHtmlElement],["appendChild","compareDocumentPosition","contains","getElementsByClassName","getElementsByTagName","getElementsByTagNameNS","insertBefore","querySelector","querySelectorAll","removeChild","replaceChild"]),b([window.HTMLBodyElement,window.HTMLHeadElement,window.HTMLHtmlElement],x),b([window.HTMLDocument||window.Document],["adoptNode","importNode","contains","createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode","createTreeWalker","elementFromPoint","getElementById","getElementsByName","getSelection"]),E(t.prototype,u),E(t.prototype,p),E(t.prototype,f),E(t.prototype,{get implementation(){var e=M.get(this);return e?e:(e=new a(T(this).implementation),M.set(this,e),e)},get defaultView(){return C(T(this).defaultView)}}),_(window.Document,t,document.implementation.createHTMLDocument("")),window.HTMLDocument&&_(window.HTMLDocument,t),j([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement]),s(a,"createDocumentType"),s(a,"createDocument"),s(a,"createHTMLDocument"),o(a,"hasFeature"),_(window.DOMImplementation,a),b([window.DOMImplementation],["createDocumentType","createDocument","createHTMLDocument","hasFeature"]),e.adoptNodeNoRemove=r,e.wrappers.DOMImplementation=a,e.wrappers.Document=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.wrappers.Selection,l=e.mixin,i=e.registerWrapper,a=e.renderAllPending,s=e.unwrap,o=e.unwrapIfNeeded,u=e.wrap,c=window.Window,p=window.getComputedStyle,d=window.getDefaultComputedStyle,f=window.getSelection;t.prototype=Object.create(n.prototype),c.prototype.getComputedStyle=function(e,t){return u(this||window).getComputedStyle(o(e),t)},d&&(c.prototype.getDefaultComputedStyle=function(e,t){return u(this||window).getDefaultComputedStyle(o(e),t)}),c.prototype.getSelection=function(){return u(this||window).getSelection()},delete window.getComputedStyle,delete window.getDefaultComputedStyle,delete window.getSelection,["addEventListener","removeEventListener","dispatchEvent"].forEach(function(e){c.prototype[e]=function(){var t=u(this||window);return t[e].apply(t,arguments)},delete window[e]}),l(t.prototype,{getComputedStyle:function(e,t){return a(),p.call(s(this),o(e),t)},getSelection:function(){return a(),new r(f.call(s(this)))},get document(){return u(s(this).document)}}),d&&(t.prototype.getDefaultComputedStyle=function(e,t){return a(),d.call(s(this),o(e),t)}),i(c,t,window),e.wrappers.Window=t}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrap,n=window.DataTransfer||window.Clipboard,r=n.prototype.setDragImage;r&&(n.prototype.setDragImage=function(e,n,l){r.call(this,t(e),n,l)})}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t;t=e instanceof i?e:new i(e&&l(e)),r(t,this)}var n=e.registerWrapper,r=e.setWrapper,l=e.unwrap,i=window.FormData;i&&(n(i,t,new i),e.wrappers.FormData=t)}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrapIfNeeded,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.send=function(e){return n.call(this,t(e))}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=n[e],r=window[t];if(r){var l=document.createElement(e),i=l.constructor;window[t]=i}}var n=(e.isWrapperFor,{a:"HTMLAnchorElement",area:"HTMLAreaElement",audio:"HTMLAudioElement",base:"HTMLBaseElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",col:"HTMLTableColElement",content:"HTMLContentElement",data:"HTMLDataElement",datalist:"HTMLDataListElement",del:"HTMLModElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",embed:"HTMLEmbedElement",fieldset:"HTMLFieldSetElement",font:"HTMLFontElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",head:"HTMLHeadElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",marquee:"HTMLMarqueeElement",menu:"HTMLMenuElement",menuitem:"HTMLMenuItemElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",script:"HTMLScriptElement",select:"HTMLSelectElement",shadow:"HTMLShadowElement",source:"HTMLSourceElement",span:"HTMLSpanElement",style:"HTMLStyleElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",template:"HTMLTemplateElement",textarea:"HTMLTextAreaElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",ul:"HTMLUListElement",video:"HTMLVideoElement"});Object.keys(n).forEach(t),Object.getOwnPropertyNames(e.wrappers).forEach(function(t){window[t]=e.wrappers[t]})}(window.ShadowDOMPolyfill),function(e){function t(e,t){var n="";return Array.prototype.forEach.call(e,function(e){n+=e.textContent+"\n\n"}),t||(n=n.replace(p,"")),n}function n(e){var t=document.createElement("style");return t.textContent=e,t}function r(e){var t=n(e);document.head.appendChild(t);var r=[];if(t.sheet)try{r=t.sheet.cssRules}catch(l){}else console.warn("sheet not found",t);return t.parentNode.removeChild(t),r}function l(){j.initialized=!0,document.body.appendChild(j);var e=j.contentDocument,t=e.createElement("base");t.href=document.baseURI,e.head.appendChild(t)}function i(e){j.initialized||l(),document.body.appendChild(j),e(j.contentDocument),document.body.removeChild(j)}function a(e,t){if(t){var l;if(e.match("@import")&&A){var a=n(e);i(function(e){e.head.appendChild(a.impl),l=Array.prototype.slice.call(a.sheet.cssRules,0),t(l)})}else l=r(e),t(l)}}function s(e){e&&u().appendChild(document.createTextNode(e))}function o(e,t){var r=n(e);r.setAttribute(t,""),r.setAttribute(L,""),document.head.appendChild(r)}function u(){return M||(M=document.createElement("style"),M.setAttribute(L,""),M[L]=!0),M}var c={strictStyling:!1,registry:{},shimStyling:function(e,n,r){var l=this.prepareRoot(e,n,r),i=this.isTypeExtension(r),a=this.makeScopeSelector(n,i),s=t(l,!0);s=this.scopeCssText(s,a),e&&(e.shimmedStyle=s),this.addCssToDocument(s,n)},shimStyle:function(e,t){return this.shimCssText(e.textContent,t)},shimCssText:function(e,t){return e=this.insertDirectives(e),this.scopeCssText(e,t)},makeScopeSelector:function(e,t){return e?t?"[is="+e+"]":e:""},isTypeExtension:function(e){return e&&e.indexOf("-")<0},prepareRoot:function(e,t,n){var r=this.registerRoot(e,t,n);return this.replaceTextInStyles(r.rootStyles,this.insertDirectives),this.removeStyles(e,r.rootStyles),this.strictStyling&&this.applyScopeToContent(e,t),r.scopeStyles},removeStyles:function(e,t){for(var n,r=0,l=t.length;l>r&&(n=t[r]);r++)n.parentNode.removeChild(n)},registerRoot:function(e,t,n){var r=this.registry[t]={root:e,name:t,extendsName:n},l=this.findStyles(e);r.rootStyles=l,r.scopeStyles=r.rootStyles;var i=this.registry[r.extendsName];return i&&(r.scopeStyles=i.scopeStyles.concat(r.scopeStyles)),r},findStyles:function(e){if(!e)return[];var t=e.querySelectorAll("style");return Array.prototype.filter.call(t,function(e){return!e.hasAttribute(P)})},applyScopeToContent:function(e,t){e&&(Array.prototype.forEach.call(e.querySelectorAll("*"),function(e){e.setAttribute(t,"")}),Array.prototype.forEach.call(e.querySelectorAll("template"),function(e){this.applyScopeToContent(e.content,t)},this))},insertDirectives:function(e){return e=this.insertPolyfillDirectivesInCssText(e),this.insertPolyfillRulesInCssText(e)},insertPolyfillDirectivesInCssText:function(e){return e=e.replace(d,function(e,t){return t.slice(0,-2)+"{"}),e.replace(f,function(e,t){return t+" {"})},insertPolyfillRulesInCssText:function(e){return e=e.replace(h,function(e,t){return t.slice(0,-1)}),e.replace(m,function(e,t,n,r){var l=e.replace(t,"").replace(n,"");return r+l})},scopeCssText:function(e,t){var n=this.extractUnscopedRulesFromCssText(e);if(e=this.insertPolyfillHostInCssText(e),e=this.convertColonHost(e),e=this.convertColonHostContext(e),e=this.convertShadowDOMSelectors(e),t){var e,r=this;a(e,function(n){e=r.scopeRules(n,t)})}return e=e+"\n"+n,e.trim()},extractUnscopedRulesFromCssText:function(e){for(var t,n="";t=g.exec(e);)n+=t[1].slice(0,-1)+"\n\n";for(;t=y.exec(e);)n+=t[0].replace(t[2],"").replace(t[1],t[3])+"\n\n";return n},convertColonHost:function(e){return this.convertColonRule(e,E,this.colonHostPartReplacer)},convertColonHostContext:function(e){return this.convertColonRule(e,_,this.colonHostContextPartReplacer)},convertColonRule:function(e,t,n){return e.replace(t,function(e,t,r,l){if(t=k,r){for(var i,a=r.split(","),s=[],o=0,u=a.length;u>o&&(i=a[o]);o++)i=i.trim(),s.push(n(t,i,l));return s.join(",")}return t+l})},colonHostContextPartReplacer:function(e,t,n){return t.match(v)?this.colonHostPartReplacer(e,t,n):e+t+n+", "+t+" "+e+n},colonHostPartReplacer:function(e,t,n){return e+t.replace(v,"")+n},convertShadowDOMSelectors:function(e){for(var t=0;t<C.length;t++)e=e.replace(C[t]," ");return e},scopeRules:function(e,t){var n="";return e&&Array.prototype.forEach.call(e,function(e){if(e.selectorText&&e.style&&void 0!==e.style.cssText)n+=this.scopeSelector(e.selectorText,t,this.strictStyling)+" {\n ",n+=this.propertiesFromRule(e)+"\n}\n\n";else if(e.type===CSSRule.MEDIA_RULE)n+="@media "+e.media.mediaText+" {\n",n+=this.scopeRules(e.cssRules,t),n+="\n}\n\n";else try{e.cssText&&(n+=e.cssText+"\n\n")}catch(r){e.type===CSSRule.KEYFRAMES_RULE&&e.cssRules&&(n+=this.ieSafeCssTextFromKeyFrameRule(e))}},this),n},ieSafeCssTextFromKeyFrameRule:function(e){var t="@keyframes "+e.name+" {";return Array.prototype.forEach.call(e.cssRules,function(e){t+=" "+e.keyText+" {"+e.style.cssText+"}"}),t+=" }"},scopeSelector:function(e,t,n){var r=[],l=e.split(",");return l.forEach(function(e){e=e.trim(),this.selectorNeedsScoping(e,t)&&(e=n&&!e.match(k)?this.applyStrictSelectorScope(e,t):this.applySelectorScope(e,t)),r.push(e)},this),r.join(", ")},selectorNeedsScoping:function(e,t){if(Array.isArray(t))return!0;var n=this.makeScopeMatcher(t);return!e.match(n)},makeScopeMatcher:function(e){return e=e.replace(/\[/g,"\\[").replace(/\]/g,"\\]"),new RegExp("^("+e+")"+w,"m")},applySelectorScope:function(e,t){return Array.isArray(t)?this.applySelectorScopeList(e,t):this.applySimpleSelectorScope(e,t)},applySelectorScopeList:function(e,t){for(var n,r=[],l=0;n=t[l];l++)r.push(this.applySimpleSelectorScope(e,n));return r.join(", ")},applySimpleSelectorScope:function(e,t){return e.match(T)?(e=e.replace(k,t),e.replace(T,t+" ")):t+" "+e},applyStrictSelectorScope:function(e,t){t=t.replace(/\[is=([^\]]*)\]/g,"$1");var n=[" ",">","+","~"],r=e,l="["+t+"]";return n.forEach(function(e){var t=r.split(e);r=t.map(function(e){var t=e.trim().replace(T,"");return t&&n.indexOf(t)<0&&t.indexOf(l)<0&&(e=t.replace(/([^:]*)(:*)(.*)/,"$1"+l+"$2$3")),e}).join(e)}),r},insertPolyfillHostInCssText:function(e){return e.replace(I,b).replace(S,v)},propertiesFromRule:function(e){var t=e.style.cssText;e.style.content&&!e.style.content.match(/['"]+|attr/)&&(t=t.replace(/content:[^;]*;/g,"content: '"+e.style.content+"';"));var n=e.style;for(var r in n)"initial"===n[r]&&(t+=r+": initial; ");return t},replaceTextInStyles:function(e,t){e&&t&&(e instanceof Array||(e=[e]),Array.prototype.forEach.call(e,function(e){e.textContent=t.call(this,e.textContent)},this))},addCssToDocument:function(e,t){e.match("@import")?o(e,t):s(e)}},p=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim,d=/\/\*\s*@polyfill ([^*]*\*+([^/*][^*]*\*+)*\/)([^{]*?){/gim,f=/polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim,h=/\/\*\s@polyfill-rule([^*]*\*+([^/*][^*]*\*+)*)\//gim,m=/(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,g=/\/\*\s@polyfill-unscoped-rule([^*]*\*+([^/*][^*]*\*+)*)\//gim,y=/(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,v="-shadowcsshost",b="-shadowcsscontext",x=")(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)",E=new RegExp("("+v+x,"gim"),_=new RegExp("("+b+x,"gim"),w="([>\\s~+[.,{:][\\s\\S]*)?$",S=/\:host/gim,I=/\:host-context/gim,k=v+"-no-combinator",T=new RegExp(v,"gim"),C=(new RegExp(b,"gim"),[/>>>/g,/::shadow/g,/::content/g,/\/deep\//g,/\/shadow\//g,/\/shadow-deep\//g,/\^\^/g,/\^/g]),j=document.createElement("iframe");j.style.display="none";var M,A=navigator.userAgent.match("Chrome"),O="shim-shadowdom",L="shim-shadowdom-css",P="no-shim";if(window.ShadowDOMPolyfill){s("style { display: none !important; }\n");var N=ShadowDOMPolyfill.wrap(document),D=N.querySelector("head");D.insertBefore(u(),D.childNodes[0]),document.addEventListener("DOMContentLoaded",function(){e.urlResolver;if(window.HTMLImports&&!HTMLImports.useNative){var t="link[rel=stylesheet]["+O+"]",n="style["+O+"]";HTMLImports.importer.documentPreloadSelectors+=","+t,HTMLImports.importer.importsPreloadSelectors+=","+t,HTMLImports.parser.documentSelectors=[HTMLImports.parser.documentSelectors,t,n].join(",");var r=HTMLImports.parser.parseGeneric;HTMLImports.parser.parseGeneric=function(e){if(!e[L]){var t=e.__importElement||e;if(!t.hasAttribute(O))return void r.call(this,e);e.__resource&&(t=e.ownerDocument.createElement("style"),t.textContent=e.__resource),HTMLImports.path.resolveUrlsInStyle(t,e.href),t.textContent=c.shimStyle(t),t.removeAttribute(O,""),t.setAttribute(L,""),t[L]=!0,t.parentNode!==D&&(e.parentNode===D?D.replaceChild(t,e):this.addElementToDocument(t)),t.__importParsed=!0,this.markParsingComplete(e),this.parseNext()}};var l=HTMLImports.parser.hasResource;HTMLImports.parser.hasResource=function(e){return"link"===e.localName&&"stylesheet"===e.rel&&e.hasAttribute(O)?e.__resource:l.call(this,e)}}})}e.ShadowCSS=c}(window.WebComponents)),function(e){window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}}(window.WebComponents),function(e){"use strict";function t(e){return void 0!==d[e]}function n(){s.call(this),this._isInvalid=!0}function r(e){return""==e&&n.call(this),e.toLowerCase()}function l(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,63,96].indexOf(t)?e:encodeURIComponent(e)}function i(e){var t=e.charCodeAt(0);return t>32&&127>t&&-1==[34,35,60,62,96].indexOf(t)?e:encodeURIComponent(e)}function a(e,a,s){function o(e){b.push(e)}var u=a||"scheme start",c=0,p="",y=!1,v=!1,b=[];e:for(;(e[c-1]!=h||0==c)&&!this._isInvalid;){var x=e[c];switch(u){case"scheme start":if(!x||!m.test(x)){if(a){o("Invalid scheme.");break e}p="",u="no scheme";continue}p+=x.toLowerCase(),u="scheme";break;case"scheme":if(x&&g.test(x))p+=x.toLowerCase();else{if(":"!=x){if(a){if(h==x)break e;o("Code point not allowed in scheme: "+x);break e}p="",c=0,u="no scheme";continue}if(this._scheme=p,p="",a)break e;t(this._scheme)&&(this._isRelative=!0),u="file"==this._scheme?"relative":this._isRelative&&s&&s._scheme==this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"==x?(query="?",u="query"):"#"==x?(this._fragment="#",u="fragment"):h!=x&&" "!=x&&"\n"!=x&&"\r"!=x&&(this._schemeData+=l(x));break;case"no scheme":if(s&&t(s._scheme)){u="relative";continue}o("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!=x||"/"!=e[c+1]){o("Expected /, got: "+x),u="relative";continue}u="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!=this._scheme&&(this._scheme=s._scheme),h==x){this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query;break e}if("/"==x||"\\"==x)"\\"==x&&o("\\ is an invalid code point."),u="relative slash";else if("?"==x)this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query="?",u="query";else{if("#"!=x){var E=e[c+1],_=e[c+2];("file"!=this._scheme||!m.test(x)||":"!=E&&"|"!=E||h!=_&&"/"!=_&&"\\"!=_&&"?"!=_&&"#"!=_)&&(this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._path.pop()),u="relative path";continue}this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._fragment="#",u="fragment"}break;case"relative slash":if("/"!=x&&"\\"!=x){"file"!=this._scheme&&(this._host=s._host,this._port=s._port),u="relative path";continue}"\\"==x&&o("\\ is an invalid code point."),u="file"==this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!=x){o("Expected '/', got: "+x),u="authority ignore slashes";continue}u="authority second slash";break;case"authority second slash":if(u="authority ignore slashes","/"!=x){o("Expected '/', got: "+x);continue}break;case"authority ignore slashes":if("/"!=x&&"\\"!=x){u="authority";continue}o("Expected authority, got: "+x);break;case"authority":if("@"==x){y&&(o("@ already seen."),p+="%40"),y=!0;for(var w=0;w<p.length;w++){var S=p[w];if(" "!=S&&"\n"!=S&&"\r"!=S)if(":"!=S||null!==this._password){var I=l(S);null!==this._password?this._password+=I:this._username+=I}else this._password="";else o("Invalid whitespace in authority.")}p=""}else{if(h==x||"/"==x||"\\"==x||"?"==x||"#"==x){c-=p.length,p="",u="host";continue}p+=x}break;case"file host":if(h==x||"/"==x||"\\"==x||"?"==x||"#"==x){2!=p.length||!m.test(p[0])||":"!=p[1]&&"|"!=p[1]?0==p.length?u="relative path start":(this._host=r.call(this,p),p="",u="relative path start"):u="relative path";continue}" "==x||"\n"==x||"\r"==x?o("Invalid whitespace in file host."):p+=x;break;case"host":case"hostname":if(":"!=x||v){if(h==x||"/"==x||"\\"==x||"?"==x||"#"==x){if(this._host=r.call(this,p),p="",u="relative path start",a)break e;continue}" "!=x&&"\n"!=x&&"\r"!=x?("["==x?v=!0:"]"==x&&(v=!1),p+=x):o("Invalid code point in host/hostname: "+x)}else if(this._host=r.call(this,p),p="",u="port","hostname"==a)break e;break;case"port":if(/[0-9]/.test(x))p+=x;else{if(h==x||"/"==x||"\\"==x||"?"==x||"#"==x||a){if(""!=p){var k=parseInt(p,10);k!=d[this._scheme]&&(this._port=k+""),p=""}if(a)break e;u="relative path start";continue}" "==x||"\n"==x||"\r"==x?o("Invalid code point in port: "+x):n.call(this)}break;case"relative path start":if("\\"==x&&o("'\\' not allowed in path."),u="relative path","/"!=x&&"\\"!=x)continue;break;case"relative path":if(h!=x&&"/"!=x&&"\\"!=x&&(a||"?"!=x&&"#"!=x))" "!=x&&"\n"!=x&&"\r"!=x&&(p+=l(x));else{"\\"==x&&o("\\ not allowed in relative path.");var T;(T=f[p.toLowerCase()])&&(p=T),".."==p?(this._path.pop(),"/"!=x&&"\\"!=x&&this._path.push("")):"."==p&&"/"!=x&&"\\"!=x?this._path.push(""):"."!=p&&("file"==this._scheme&&0==this._path.length&&2==p.length&&m.test(p[0])&&"|"==p[1]&&(p=p[0]+":"),this._path.push(p)),p="","?"==x?(this._query="?",u="query"):"#"==x&&(this._fragment="#",u="fragment")}break;case"query":a||"#"!=x?h!=x&&" "!=x&&"\n"!=x&&"\r"!=x&&(this._query+=i(x)):(this._fragment="#",u="fragment");break;case"fragment":h!=x&&" "!=x&&"\n"!=x&&"\r"!=x&&(this._fragment+=x)}c++}}function s(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function o(e,t){void 0===t||t instanceof o||(t=new o(String(t))),this._url=e,s.call(this);var n=e.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");a.call(this,n,null,t)}var u=!1;if(!e.forceJURL)try{var c=new URL("b","http://a");c.pathname="c%20d",u="http://a/c%20d"===c.href}catch(p){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var f=Object.create(null);f["%2e"]=".",f[".%2e"]="..",f["%2e."]="..",f["%2e%2e"]="..";var h=void 0,m=/[a-zA-Z]/,g=/[a-zA-Z0-9\+\-\.]/;o.prototype={toString:function(){return this.href},get href(){if(this._isInvalid)return this._url;var e="";return(""!=this._username||null!=this._password)&&(e=this._username+(null!=this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+e+this.host:"")+this.pathname+this._query+this._fragment},set href(e){s.call(this),a.call(this,e)},get protocol(){return this._scheme+":"},set protocol(e){this._isInvalid||a.call(this,e+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"host")},get hostname(){return this._host},set hostname(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"hostname")},get port(){return this._port},set port(e){!this._isInvalid&&this._isRelative&&a.call(this,e,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(e){!this._isInvalid&&this._isRelative&&(this._path=[],a.call(this,e,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"==this._query?"":this._query},set search(e){!this._isInvalid&&this._isRelative&&(this._query="?","?"==e[0]&&(e=e.slice(1)),a.call(this,e,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"==this._fragment?"":this._fragment},set hash(e){this._isInvalid||(this._fragment="#","#"==e[0]&&(e=e.slice(1)),a.call(this,e,"fragment"))},get origin(){var e;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null"}return e=this.host,e?this._scheme+"://"+e:""}};var y=e.URL;y&&(o.createObjectURL=function(e){return y.createObjectURL.apply(y,arguments)},o.revokeObjectURL=function(e){y.revokeObjectURL(e)}),e.URL=o}}(this),function(e){function t(e){x.push(e),b||(b=!0,m(r))}function n(e){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(e)||e}function r(){b=!1;var e=x;x=[],e.sort(function(e,t){return e.uid_-t.uid_});var t=!1;e.forEach(function(e){var n=e.takeRecords();l(e),n.length&&(e.callback_(n,e),t=!0)}),t&&r()}function l(e){e.nodes_.forEach(function(t){var n=g.get(t);n&&n.forEach(function(t){t.observer===e&&t.removeTransientObservers()})})}function i(e,t){for(var n=e;n;n=n.parentNode){var r=g.get(n);if(r)for(var l=0;l<r.length;l++){var i=r[l],a=i.options;if(n===e||a.subtree){var s=t(a);s&&i.enqueue(s)}}}}function a(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++E}function s(e,t){this.type=e,this.target=t,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null, this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function o(e){var t=new s(e.type,e.target);return t.addedNodes=e.addedNodes.slice(),t.removedNodes=e.removedNodes.slice(),t.previousSibling=e.previousSibling,t.nextSibling=e.nextSibling,t.attributeName=e.attributeName,t.attributeNamespace=e.attributeNamespace,t.oldValue=e.oldValue,t}function u(e,t){return _=new s(e,t)}function c(e){return w?w:(w=o(_),w.oldValue=e,w)}function p(){_=w=void 0}function d(e){return e===w||e===_}function f(e,t){return e===t?e:w&&d(e)?w:null}function h(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}var m,g=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))m=setTimeout;else if(window.setImmediate)m=window.setImmediate;else{var y=[],v=String(Math.random());window.addEventListener("message",function(e){if(e.data===v){var t=y;y=[],t.forEach(function(e){e()})}}),m=function(e){y.push(e),window.postMessage(v,"*")}}var b=!1,x=[],E=0;a.prototype={observe:function(e,t){if(e=n(e),!t.childList&&!t.attributes&&!t.characterData||t.attributeOldValue&&!t.attributes||t.attributeFilter&&t.attributeFilter.length&&!t.attributes||t.characterDataOldValue&&!t.characterData)throw new SyntaxError;var r=g.get(e);r||g.set(e,r=[]);for(var l,i=0;i<r.length;i++)if(r[i].observer===this){l=r[i],l.removeListeners(),l.options=t;break}l||(l=new h(this,e,t),r.push(l),this.nodes_.push(e)),l.addListeners()},disconnect:function(){this.nodes_.forEach(function(e){for(var t=g.get(e),n=0;n<t.length;n++){var r=t[n];if(r.observer===this){r.removeListeners(),t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}};var _,w;h.prototype={enqueue:function(e){var n=this.observer.records_,r=n.length;if(n.length>0){var l=n[r-1],i=f(l,e);if(i)return void(n[r-1]=i)}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=g.get(e);t||g.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=g.get(e),n=0;n<t.length;n++)if(t[n]===this){t.splice(n,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var t=e.attrName,n=e.relatedNode.namespaceURI,r=e.target,l=new u("attributes",r);l.attributeName=t,l.attributeNamespace=n;var a=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;i(r,function(e){return!e.attributes||e.attributeFilter&&e.attributeFilter.length&&-1===e.attributeFilter.indexOf(t)&&-1===e.attributeFilter.indexOf(n)?void 0:e.attributeOldValue?c(a):l});break;case"DOMCharacterDataModified":var r=e.target,l=u("characterData",r),a=e.prevValue;i(r,function(e){return e.characterData?e.characterDataOldValue?c(a):l:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var s,o,d=e.target;"DOMNodeInserted"===e.type?(s=[d],o=[]):(s=[],o=[d]);var f=d.previousSibling,h=d.nextSibling,l=u("childList",e.target.parentNode);l.addedNodes=s,l.removedNodes=o,l.previousSibling=f,l.nextSibling=h,i(e.relatedNode,function(e){return e.childList?l:void 0})}p()}},e.JsMutationObserver=a,e.MutationObserver||(e.MutationObserver=a)}(this),window.HTMLImports=window.HTMLImports||{flags:{}},function(e){function t(e,t){t=t||h,r(function(){i(e,t)},t)}function n(e){return"complete"===e.readyState||e.readyState===y}function r(e,t){if(n(t))e&&e();else{var l=function(){("complete"===t.readyState||t.readyState===y)&&(t.removeEventListener(v,l),r(e,t))};t.addEventListener(v,l)}}function l(e){e.target.__loaded=!0}function i(e,t){function n(){o==u&&e&&e({allImports:s,loadedImports:c,errorImports:p})}function r(e){l(e),c.push(this),o++,n()}function i(e){p.push(this),o++,n()}var s=t.querySelectorAll("link[rel=import]"),o=0,u=s.length,c=[],p=[];if(u)for(var d,f=0;u>f&&(d=s[f]);f++)a(d)?(o++,n()):(d.addEventListener("load",r),d.addEventListener("error",i));else n()}function a(e){return p?e.__loaded||e["import"]&&"loading"!==e["import"].readyState:e.__importParsed}function s(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)o(t)&&u(t)}function o(e){return"link"===e.localName&&"import"===e.rel}function u(e){var t=e["import"];t?l({target:e}):(e.addEventListener("load",l),e.addEventListener("error",l))}var c="import",p=Boolean(c in document.createElement("link")),d=Boolean(window.ShadowDOMPolyfill),f=function(e){return d?ShadowDOMPolyfill.wrapIfNeeded(e):e},h=f(document),m={get:function(){var e=HTMLImports.currentScript||document.currentScript||("complete"!==document.readyState?document.scripts[document.scripts.length-1]:null);return f(e)},configurable:!0};Object.defineProperty(document,"_currentScript",m),Object.defineProperty(h,"_currentScript",m);var g=/Trident|Edge/.test(navigator.userAgent),y=g?"complete":"interactive",v="readystatechange";p&&(new MutationObserver(function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.addedNodes&&s(t.addedNodes)}).observe(document.head,{childList:!0}),function(){if("loading"===document.readyState)for(var e,t=document.querySelectorAll("link[rel=import]"),n=0,r=t.length;r>n&&(e=t[n]);n++)u(e)}()),t(function(e){HTMLImports.ready=!0,HTMLImports.readyTime=(new Date).getTime();var t=h.createEvent("CustomEvent");t.initCustomEvent("HTMLImportsLoaded",!0,!0,e),h.dispatchEvent(t)}),e.IMPORT_LINK_TYPE=c,e.useNative=p,e.rootDocument=h,e.whenReady=t,e.isIE=g}(HTMLImports),function(e){var t=[],n=function(e){t.push(e)},r=function(){t.forEach(function(t){t(e)})};e.addModule=n,e.initializeModules=r}(HTMLImports),HTMLImports.addModule(function(e){var t=/(url\()([^)]*)(\))/g,n=/(@import[\s]+(?!url\())([^;]*)(;)/g,r={resolveUrlsInStyle:function(e,t){var n=e.ownerDocument,r=n.createElement("a");return e.textContent=this.resolveUrlsInCssText(e.textContent,t,r),e},resolveUrlsInCssText:function(e,r,l){var i=this.replaceUrls(e,l,r,t);return i=this.replaceUrls(i,l,r,n)},replaceUrls:function(e,t,n,r){return e.replace(r,function(e,r,l,i){var a=l.replace(/["']/g,"");return n&&(a=new URL(a,n).href),t.href=a,a=t.href,r+"'"+a+"'"+i})}};e.path=r}),HTMLImports.addModule(function(e){var t={async:!0,ok:function(e){return e.status>=200&&e.status<300||304===e.status||0===e.status},load:function(n,r,l){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=i.getResponseHeader("Location"),a=null;if(n)var a="/"===n.substr(0,1)?location.origin+n:n;r.call(l,!t.ok(i)&&i,i.response||i.responseText,a)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)this.require(t);this.checkDone()},addNode:function(e){this.inflight++,this.require(e),this.checkDone()},require:function(e){var t=e.src||e.href;e.__nodeUrl=t,this.dedupe(t,e)||this.fetch(t,e)},dedupe:function(e,t){if(this.pending[e])return this.pending[e].push(t),!0;return this.cache[e]?(this.onload(e,t,this.cache[e]),this.tail(),!0):(this.pending[e]=[t],!1)},fetch:function(e,r){if(n.load&&console.log("fetch",e,r),e)if(e.match(/^data:/)){var l=e.split(","),i=l[0],a=l[1];a=i.indexOf(";base64")>-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,l){this.receive(e,r,t,n,l)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,l){this.cache[e]=r;for(var i,a=this.pending[e],s=0,o=a.length;o>s&&(i=a[s]);s++)this.onload(e,i,r,n,l),this.tail();this.pending[e]=null},tail:function(){--this.inflight,this.checkDone()},checkDone:function(){this.inflight||this.oncomplete()}},e.Loader=r}),HTMLImports.addModule(function(e){var t=function(e){this.addCallback=e,this.mo=new MutationObserver(this.handler.bind(this))};t.prototype={handler:function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)"childList"===t.type&&t.addedNodes.length&&this.addedNodes(t.addedNodes)},addedNodes:function(e){this.addCallback&&this.addCallback(e);for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.children&&t.children.length&&this.addedNodes(t.children)},observe:function(e){this.mo.observe(e,{childList:!0,subtree:!0})}},e.Observer=t}),HTMLImports.addModule(function(e){function t(e){return"link"===e.localName&&e.rel===c}function n(e){var t=r(e);return"data:text/javascript;charset=utf-8,"+encodeURIComponent(t)}function r(e){return e.textContent+l(e)}function l(e){var t=e.ownerDocument;t.__importedScripts=t.__importedScripts||0;var n=e.ownerDocument.baseURI,r=t.__importedScripts?"-"+t.__importedScripts:"";return t.__importedScripts++,"\n//# sourceURL="+n+r+".js\n"}function i(e){var t=e.ownerDocument.createElement("style");return t.textContent=e.textContent,a.resolveUrlsInStyle(t),t}var a=e.path,s=e.rootDocument,o=e.flags,u=e.isIE,c=e.IMPORT_LINK_TYPE,p="link[rel="+c+"]",d={documentSelectors:p,importsSelectors:[p,"link[rel=stylesheet]","style","script:not([type])",'script[type="text/javascript"]'].join(","),map:{link:"parseLink",script:"parseScript",style:"parseStyle"},dynamicElements:[],parseNext:function(){var e=this.nextToParse();e&&this.parse(e)},parse:function(e){if(this.isParsed(e))return void(o.parse&&console.log("[%s] is already parsed",e.localName));var t=this[this.map[e.localName]];t&&(this.markParsing(e),t.call(this,e))},parseDynamic:function(e,t){this.dynamicElements.push(e),t||this.parseNext()},markParsing:function(e){o.parse&&console.log("parsing",e),this.parsingElement=e},markParsingComplete:function(e){e.__importParsed=!0,this.markDynamicParsingComplete(e),e.__importElement&&(e.__importElement.__importParsed=!0,this.markDynamicParsingComplete(e.__importElement)),this.parsingElement=null,o.parse&&console.log("completed",e)},markDynamicParsingComplete:function(e){var t=this.dynamicElements.indexOf(e);t>=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(HTMLImports.__importsParsingHook&&HTMLImports.__importsParsingHook(e),e["import"]&&(e["import"].__importParsed=!0),this.markParsingComplete(e),e.dispatchEvent(e.__resource&&!e.__error?new CustomEvent("load",{bubbles:!1}):new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(r){t&&t(r),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),u&&"style"===e.localName){var l=!1;if(-1==e.textContent.indexOf("@import"))l=!0;else if(e.sheet){l=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,o=0;s>o&&(i=a[o]);o++)i.type===CSSRule.IMPORT_RULE&&(l=l&&Boolean(i.styleSheet))}l&&e.dispatchEvent(new CustomEvent("load",{bubbles:!1}))}},parseScript:function(t){var r=document.createElement("script");r.__importElement=t,r.src=t.src?t.src:n(t),e.currentScript=t,this.trackElement(r,function(t){r.parentNode.removeChild(r),e.currentScript=null}),this.addElementToDocument(r)},nextToParse:function(){return this._mayParse=[],!this.parsingElement&&(this.nextToParseInDoc(s)||this.nextToParseDynamic())},nextToParseInDoc:function(e,n){if(e&&this._mayParse.indexOf(e)<0){this._mayParse.push(e);for(var r,l=e.querySelectorAll(this.parseSelectorsForNode(e)),i=0,a=l.length;a>i&&(r=l[i]);i++)if(!this.isParsed(r))return this.hasResource(r)?t(r)?this.nextToParseInDoc(r["import"],r):r:void 0}return n},nextToParseDynamic:function(){return this.dynamicElements[0]},parseSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===s?this.documentSelectors:this.importsSelectors},isParsed:function(e){return e.__importParsed},needsDynamicParsing:function(e){return this.dynamicElements.indexOf(e)>=0},hasResource:function(e){return t(e)&&void 0===e["import"]?!1:!0}};e.parser=d,e.IMPORT_SELECTOR=p}),HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function l(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var l=n.createElement("base");l.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(l),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,o=e.rootDocument,u=e.Loader,c=e.Observer,p=e.parser,d={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){f.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);f.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===o?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var o=this.documents[e];void 0===o&&(o=a?null:l(r,s||e),o&&(o.__importLink=n,this.bootDocument(o)),this.documents[e]=o),n["import"]=o}p.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),p.parseNext()},loadedAll:function(){p.parseNext()}},f=new u(d.loaded.bind(d),d.loadedAll.bind(d));if(d.observer=new c,!document.baseURI){var h={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",h),Object.defineProperty(o,"baseURI",h)}e.importer=d,e.importLoader=f}),HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,l,i,a,s=0,o=e.length;o>s&&(a=e[s]);s++)r||(r=a.ownerDocument,l=t.isParsed(r)),i=this.shouldLoadNode(a),i&&n.loadNode(a),this.shouldParseNode(a)&&l&&t.parseDynamic(a,i)},shouldLoadNode:function(e){return 1===e.nodeType&&l.call(e,n.loadSelectorsForNode(e))},shouldParseNode:function(e){return 1===e.nodeType&&l.call(e,t.parseSelectorsForNode(e))}};n.observer.addCallback=r.added.bind(r);var l=HTMLElement.prototype.matches||HTMLElement.prototype.matchesSelector||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector}),function(e){function t(){HTMLImports.importer.bootDocument(l)}var n=e.initializeModules,r=e.isIE;if(!e.useNative){r&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(e,t){t=t||{};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,Boolean(t.bubbles),Boolean(t.cancelable),t.detail),n},window.CustomEvent.prototype=window.Event.prototype),n();var l=e.rootDocument;"complete"===document.readyState||"interactive"===document.readyState&&!window.attachEvent?t():document.addEventListener("DOMContentLoaded",t)}}(HTMLImports),window.CustomElements=window.CustomElements||{flags:{}},function(e){var t=e.flags,n=[],r=function(e){n.push(e)},l=function(){n.forEach(function(t){t(e)})};e.addModule=r,e.initializeModules=l,e.hasNative=Boolean(document.registerElement),e.useNative=!t.register&&e.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(CustomElements),CustomElements.addModule(function(e){function t(e,t){n(e,function(e){return t(e)?!0:void r(e,t)}),r(e,t)}function n(e,t,r){var l=e.firstElementChild;if(!l)for(l=e.firstChild;l&&l.nodeType!==Node.ELEMENT_NODE;)l=l.nextSibling;for(;l;)t(l,r)!==!0&&n(l,t,r),l=l.nextElementSibling;return null}function r(e,n){for(var r=e.shadowRoot;r;)t(r,n),r=r.olderShadowRoot}function l(e,t){i(e,t,[])}function i(e,t,n){if(e=wrap(e),!(n.indexOf(e)>=0)){n.push(e);for(var r,l=e.querySelectorAll("link[rel="+a+"]"),s=0,o=l.length;o>s&&(r=l[s]);s++)r["import"]&&i(r["import"],t,n);t(e)}}var a=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";e.forDocumentTree=l,e.forSubtree=t}),CustomElements.addModule(function(e){function t(e){return n(e)||r(e)}function n(t){return e.upgrade(t)?!0:void s(t)}function r(e){x(e,function(e){return n(e)?!0:void 0})}function l(e){s(e),d(e)&&x(e,function(e){s(e)})}function i(e){S.push(e),w||(w=!0,setTimeout(a))}function a(){w=!1;for(var e,t=S,n=0,r=t.length;r>n&&(e=t[n]);n++)e();S=[]}function s(e){_?i(function(){o(e)}):o(e)}function o(e){e.__upgraded__&&(e.attachedCallback||e.detachedCallback)&&!e.__attached&&d(e)&&(e.__attached=!0,e.attachedCallback&&e.attachedCallback())}function u(e){c(e),x(e,function(e){c(e)})}function c(e){_?i(function(){p(e)}):p(e)}function p(e){e.__upgraded__&&(e.attachedCallback||e.detachedCallback)&&e.__attached&&!d(e)&&(e.__attached=!1,e.detachedCallback&&e.detachedCallback())}function d(e){for(var t=e,n=wrap(document);t;){if(t==n)return!0;t=t.parentNode||t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host}}function f(e){if(e.shadowRoot&&!e.shadowRoot.__watched){b.dom&&console.log("watching shadow-root for: ",e.localName);for(var t=e.shadowRoot;t;)g(t),t=t.olderShadowRoot}}function h(e){if(b.dom){var n=e[0];if(n&&"childList"===n.type&&n.addedNodes&&n.addedNodes){for(var r=n.addedNodes[0];r&&r!==document&&!r.host;)r=r.parentNode;var l=r&&(r.URL||r._URL||r.host&&r.host.localName)||"";l=l.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",e.length,l||"")}e.forEach(function(e){"childList"===e.type&&(I(e.addedNodes,function(e){e.localName&&t(e)}),I(e.removedNodes,function(e){e.localName&&u(e)}))}),b.dom&&console.groupEnd()}function m(e){for(e=wrap(e),e||(e=wrap(document));e.parentNode;)e=e.parentNode;var t=e.__observer;t&&(h(t.takeRecords()),a())}function g(e){if(!e.__observer){var t=new MutationObserver(h);t.observe(e,{childList:!0,subtree:!0}),e.__observer=t}}function y(e){e=wrap(e),b.dom&&console.group("upgradeDocument: ",e.baseURI.split("/").pop()),t(e),g(e),b.dom&&console.groupEnd()}function v(e){E(e,y)}var b=e.flags,x=e.forSubtree,E=e.forDocumentTree,_=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;e.hasPolyfillMutations=_;var w=!1,S=[],I=Array.prototype.forEach.call.bind(Array.prototype.forEach),k=Element.prototype.createShadowRoot;k&&(Element.prototype.createShadowRoot=function(){var e=k.call(this);return CustomElements.watchShadow(this),e}),e.watchShadow=f,e.upgradeDocumentTree=v,e.upgradeSubtree=r,e.upgradeAll=t,e.attachedNode=l,e.takeRecords=m}),CustomElements.addModule(function(e){function t(t){if(!t.__upgraded__&&t.nodeType===Node.ELEMENT_NODE){var r=t.getAttribute("is"),l=e.getRegisteredDefinition(r||t.localName);if(l){if(r&&l.tag==t.localName)return n(t,l);if(!r&&!l["extends"])return n(t,l)}}}function n(t,n){return a.upgrade&&console.group("upgrade:",t.localName),n.is&&t.setAttribute("is",n.is),r(t,n),t.__upgraded__=!0,i(t),e.attachedNode(t),e.upgradeSubtree(t),a.upgrade&&console.groupEnd(),t}function r(e,t){Object.__proto__?e.__proto__=t.prototype:(l(e,t.prototype,t["native"]),e.__proto__=t.prototype)}function l(e,t,n){for(var r={},l=t;l!==n&&l!==HTMLElement.prototype;){for(var i,a=Object.getOwnPropertyNames(l),s=0;i=a[s];s++)r[i]||(Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(l,i)),r[i]=1);l=Object.getPrototypeOf(l)}}function i(e){e.createdCallback&&e.createdCallback()}var a=e.flags;e.upgrade=t,e.upgradeWithDefinition=n,e.implementPrototype=r}),CustomElements.addModule(function(e){function t(t,r){var o=r||{};if(!t)throw new Error("document.registerElement: first argument `name` must not be empty");if(t.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(t)+"'.");if(l(t))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(t)+"'. The type name is invalid.");if(u(t))throw new Error("DuplicateDefinitionError: a type with name '"+String(t)+"' is already registered");return o.prototype||(o.prototype=Object.create(HTMLElement.prototype)),o.__name=t.toLowerCase(),o.lifecycle=o.lifecycle||{},o.ancestry=i(o["extends"]),a(o),s(o),n(o.prototype),c(o.__name,o),o.ctor=p(o),o.ctor.prototype=o.prototype,o.prototype.constructor=o.ctor,e.ready&&y(document),o.ctor}function n(e){if(!e.setAttribute._polyfilled){var t=e.setAttribute;e.setAttribute=function(e,n){r.call(this,e,n,t)};var n=e.removeAttribute;e.removeAttribute=function(e){r.call(this,e,null,n)},e.setAttribute._polyfilled=!0}}function r(e,t,n){e=e.toLowerCase();var r=this.getAttribute(e);n.apply(this,arguments);var l=this.getAttribute(e);this.attributeChangedCallback&&l!==r&&this.attributeChangedCallback(e,r,l)}function l(e){for(var t=0;t<_.length;t++)if(e===_[t])return!0}function i(e){var t=u(e);return t?i(t["extends"]).concat([t]):[]}function a(e){for(var t,n=e["extends"],r=0;t=e.ancestry[r];r++)n=t.is&&t.tag;e.tag=n||e.__name,n&&(e.is=e.__name)}function s(e){if(!Object.__proto__){var t=HTMLElement.prototype;if(e.is){var n=document.createElement(e.tag),r=Object.getPrototypeOf(n);r===e.prototype&&(t=r)}for(var l,i=e.prototype;i&&i!==t;)l=Object.getPrototypeOf(i),i.__proto__=l,i=l;e["native"]=t}}function o(e){return b(I(e.tag),e)}function u(e){return e?w[e.toLowerCase()]:void 0}function c(e,t){w[e]=t}function p(e){return function(){return o(e)}}function d(e,t,n){return e===S?f(t,n):k(e,t)}function f(e,t){var n=u(t||e);if(n){if(e==n.tag&&t==n.is)return new n.ctor;if(!t&&!n.is)return new n.ctor}var r;return t?(r=f(e),r.setAttribute("is",t),r):(r=I(e),e.indexOf("-")>=0&&x(r,HTMLElement),r)}function h(e,t){var n=e[t];e[t]=function(){var e=n.apply(this,arguments);return v(e),e}}var m,g=e.isIE11OrOlder,y=e.upgradeDocumentTree,v=e.upgradeAll,b=e.upgradeWithDefinition,x=e.implementPrototype,E=e.useNative,_=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],w={},S="http://www.w3.org/1999/xhtml",I=document.createElement.bind(document),k=document.createElementNS.bind(document);m=Object.__proto__||E?function(e,t){return e instanceof t}:function(e,t){for(var n=e;n;){if(n===t.prototype)return!0;n=n.__proto__}return!1},h(Node.prototype,"cloneNode"),h(document,"importNode"),g&&!function(){var e=document.importNode;document.importNode=function(){var t=e.apply(document,arguments);if(t.nodeType==t.DOCUMENT_FRAGMENT_NODE){var n=document.createDocumentFragment();return n.appendChild(t),n}return t}}(),document.registerElement=t,document.createElement=f,document.createElementNS=d,e.registry=w,e["instanceof"]=m,e.reservedTagList=_,e.getRegisteredDefinition=u,document.register=document.registerElement}),function(e){function t(){a(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(e){a(wrap(e["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var n=e.useNative,r=e.initializeModules,l=/Trident/.test(navigator.userAgent);if(n){var i=function(){};e.watchShadow=i,e.upgrade=i,e.upgradeAll=i,e.upgradeDocumentTree=i,e.upgradeSubtree=i,e.takeRecords=i,e["instanceof"]=function(e,t){return e instanceof t}}else r();var a=e.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}),l&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(e,t){t=t||{};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,Boolean(t.bubbles),Boolean(t.cancelable),t.detail),n},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||e.flags.eager)t();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var s=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(s,t)}else t();e.isIE11OrOlder=l}(window.CustomElements),function(e){Function.prototype.bind||(Function.prototype.bind=function(e){var t=this,n=Array.prototype.slice.call(arguments,1);return function(){var r=n.slice();return r.push.apply(r,arguments),t.apply(e,r)}})}(window.WebComponents),function(e){"use strict";function t(){window.Polymer===l&&(window.Polymer=function(){throw new Error('You tried to use polymer without loading it first. To load polymer, <link rel="import" href="components/polymer/polymer.html">')})}if(!window.performance){var n=Date.now();window.performance={now:function(){return Date.now()-n}}}window.requestAnimationFrame||(window.requestAnimationFrame=function(){var e=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;return e?function(t){return e(function(){t(performance.now())})}:function(e){return window.setTimeout(e,1e3/60)}}()),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(){return window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(e){clearTimeout(e)}}());var r=[],l=function(e,t){"string"!=typeof e&&1===arguments.length&&Array.prototype.push.call(arguments,document._currentScript),r.push(arguments)};window.Polymer=l,e.consumeDeclarations=function(t){e.consumeDeclarations=function(){throw"Possible attempt to load Polymer twice"},t&&t(r),r=null},HTMLImports.useNative?t():addEventListener("DOMContentLoaded",t)}(window.WebComponents),function(e){var t=document.createElement("style");t.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var n=document.querySelector("head");n.insertBefore(t,n.firstChild)}(window.WebComponents),function(e){window.Platform=e}(window.WebComponents),!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var e;return function t(e,n,r){function l(a,s){if(!n[a]){if(!e[a]){var o="function"==typeof require&&require;if(!s&&o)return o(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var u=n[a]={exports:{}};e[a][0].call(u.exports,function(t){var n=e[a][1][t];return l(n?n:t)},u,u.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)l(r[a]);return l}({1:[function(e,t){var n=e("../lib/decorators/unhandledRejection"),r=n(e("../lib/Promise"));t.exports="undefined"!=typeof global?global.Promise=r:"undefined"!=typeof self?self.Promise=r:r},{"../lib/Promise":2,"../lib/decorators/unhandledRejection":4}],2:[function(t,n){!function(e){"use strict";e(function(e){var t=e("./makePromise"),n=e("./Scheduler"),r=e("./env").asap;return t({scheduler:new n(r)})})}("function"==typeof e&&e.amd?e:function(e){n.exports=e(t)})},{"./Scheduler":3,"./env":5,"./makePromise":7}],3:[function(t,n){!function(e){"use strict";e(function(){function e(e){this._async=e,this._running=!1,this._queue=this,this._queueLen=0,this._afterQueue={},this._afterQueueLen=0;var t=this;this.drain=function(){t._drain()}}return e.prototype.enqueue=function(e){this._queue[this._queueLen++]=e,this.run()},e.prototype.afterQueue=function(e){this._afterQueue[this._afterQueueLen++]=e,this.run()},e.prototype.run=function(){this._running||(this._running=!0,this._async(this.drain))},e.prototype._drain=function(){for(var e=0;e<this._queueLen;++e)this._queue[e].run(),this._queue[e]=void 0;for(this._queueLen=0,this._running=!1,e=0;e<this._afterQueueLen;++e)this._afterQueue[e].run(),this._afterQueue[e]=void 0;this._afterQueueLen=0},e})}("function"==typeof e&&e.amd?e:function(e){n.exports=e()})},{}],4:[function(t,n){!function(e){"use strict";e(function(e){function t(e){throw e}function n(){}var r=e("../env").setTimer,l=e("../format");return function(e){function i(e){e.handled||(f.push(e),c("Potentially unhandled rejection ["+e.id+"] "+l.formatError(e.value)))}function a(e){var t=f.indexOf(e);t>=0&&(f.splice(t,1),p("Handled previous rejection ["+e.id+"] "+l.formatObject(e.value)))}function s(e,t){d.push(e,t),null===h&&(h=r(o,0))}function o(){for(h=null;d.length>0;)d.shift()(d.shift())}var u,c=n,p=n;"undefined"!=typeof console&&(u=console,c="undefined"!=typeof u.error?function(e){u.error(e)}:function(e){u.log(e)},p="undefined"!=typeof u.info?function(e){u.info(e)}:function(e){u.log(e)}),e.onPotentiallyUnhandledRejection=function(e){s(i,e)},e.onPotentiallyUnhandledRejectionHandled=function(e){s(a,e)},e.onFatalRejection=function(e){s(t,e.value)};var d=[],f=[],h=null;return e}})}("function"==typeof e&&e.amd?e:function(e){n.exports=e(t)})},{"../env":5,"../format":6}],5:[function(t,n){!function(e){"use strict";e(function(e){function t(){return"undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick}function n(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function r(e){function t(){var e=n;n=void 0,e()}var n,r=document.createTextNode(""),l=new e(t);l.observe(r,{characterData:!0});var i=0;return function(e){n=e,r.data=i^=1}}var l,i="undefined"!=typeof setTimeout&&setTimeout,a=function(e,t){return setTimeout(e,t)},s=function(e){return clearTimeout(e)},o=function(e){return i(e,0)};if(t())o=function(e){return process.nextTick(e)};else if(l=n())o=r(l);else if(!i){var u=e,c=u("vertx");a=function(e,t){return c.setTimer(t,e)},s=c.cancelTimer,o=c.runOnLoop||c.runOnContext}return{setTimer:a,clearTimer:s,asap:o}})}("function"==typeof e&&e.amd?e:function(e){n.exports=e(t)})},{}],6:[function(t,n){!function(e){"use strict";e(function(){function e(e){var n="object"==typeof e&&null!==e&&e.stack?e.stack:t(e);return e instanceof Error?n:n+" (WARNING: non-Error used)"}function t(e){var t=String(e);return"[object Object]"===t&&"undefined"!=typeof JSON&&(t=n(e,t)),t}function n(e,t){try{return JSON.stringify(e)}catch(n){return t}}return{formatError:e,formatObject:t,tryStringify:n}})}("function"==typeof e&&e.amd?e:function(e){n.exports=e()})},{}],7:[function(t,n){!function(e){"use strict";e(function(){return function(e){function t(e,t){this._handler=e===b?t:n(e)}function n(e){function t(e){l.resolve(e)}function n(e){l.reject(e)}function r(e){l.notify(e)}var l=new E;try{e(t,n,r)}catch(i){n(i)}return l}function r(e){return P(e)?e:new t(b,new _(g(e)))}function l(e){return new t(b,new _(new I(e)))}function i(){return Z}function a(){return new t(b,new E); }function s(e,t){var n=new E(e.receiver,e.join().context);return new t(b,n)}function o(e){return c(H,null,e)}function u(e,t){return c(B,e,t)}function c(e,n,r){function l(t,l,a){a.resolved||p(r,i,t,e(n,l,t),a)}function i(e,t,n){c[e]=t,0===--u&&n.become(new S(c))}for(var a,s="function"==typeof n?l:i,o=new E,u=r.length>>>0,c=new Array(u),d=0;d<r.length&&!o.resolved;++d)a=r[d],void 0!==a||d in r?p(r,s,d,a,o):--u;return 0===u&&o.become(new S(c)),new t(b,o)}function p(e,t,n,r,l){if(N(r)){var i=y(r),a=i.state();0===a?i.fold(t,n,void 0,l):a>0?t(n,i.value,l):(l.become(i),d(e,n+1,i))}else t(n,r,l)}function d(e,t,n){for(var r=t;r<e.length;++r)f(g(e[r]),n)}function f(e,t){if(e!==t){var n=e.state();0===n?e.visit(e,void 0,e._unreport):0>n&&e._unreport()}}function h(e){return"object"!=typeof e||null===e?l(new TypeError("non-iterable passed to race()")):0===e.length?i():1===e.length?r(e[0]):m(e)}function m(e){var n,r,l,i=new E;for(n=0;n<e.length;++n)if(r=e[n],void 0!==r||n in e){if(l=g(r),0!==l.state()){i.become(l),d(e,n+1,l);break}l.visit(i,i.resolve,i.reject)}return new t(b,i)}function g(e){return P(e)?e._handler.join():N(e)?v(e):new S(e)}function y(e){return P(e)?e._handler.join():v(e)}function v(e){try{var t=e.then;return"function"==typeof t?new w(t,e):new S(e)}catch(n){return new I(n)}}function b(){}function x(){}function E(e,n){t.createContext(this,n),this.consumers=void 0,this.receiver=e,this.handler=void 0,this.resolved=!1}function _(e){this.handler=e}function w(e,t){E.call(this),z.enqueue(new A(e,t,this))}function S(e){t.createContext(this),this.value=e}function I(e){t.createContext(this),this.id=++K,this.value=e,this.handled=!1,this.reported=!1,this._report()}function k(e,t){this.rejection=e,this.context=t}function T(e){this.rejection=e}function C(){return new I(new TypeError("Promise cycle"))}function j(e,t){this.continuation=e,this.handler=t}function M(e,t){this.handler=t,this.value=e}function A(e,t,n){this._then=e,this.thenable=t,this.resolver=n}function O(e,t,n,r,l){try{e.call(t,n,r,l)}catch(i){r(i)}}function L(e,t,n,r){this.f=e,this.z=t,this.c=n,this.to=r,this.resolver=Y,this.receiver=this}function P(e){return e instanceof t}function N(e){return("object"==typeof e||"function"==typeof e)&&null!==e}function D(e,n,r,l){return"function"!=typeof e?l.become(n):(t.enterContext(n),U(e,n.value,r,l),void t.exitContext())}function R(e,n,r,l,i){return"function"!=typeof e?i.become(r):(t.enterContext(r),$(e,n,r.value,l,i),void t.exitContext())}function F(e,n,r,l,i){return"function"!=typeof e?i.notify(n):(t.enterContext(r),V(e,n,l,i),void t.exitContext())}function B(e,t,n){try{return e(t,n)}catch(r){return l(r)}}function U(e,t,n,r){try{r.become(g(e.call(n,t)))}catch(l){r.become(new I(l))}}function $(e,t,n,r,l){try{e.call(r,t,n,l)}catch(i){l.become(new I(i))}}function V(e,t,n,r){try{r.notify(e.call(n,t))}catch(l){r.notify(l)}}function q(e,t){t.prototype=J(e.prototype),t.prototype.constructor=t}function H(e,t){return t}function G(){}function W(){return"undefined"!=typeof process&&null!==process&&"function"==typeof process.emit?function(e,t){return"unhandledRejection"===e?process.emit(e,t.value,t):process.emit(e,t)}:"undefined"!=typeof self&&"function"==typeof CustomEvent?function(e,t,n){var r=!1;try{var l=new n("unhandledRejection");r=l instanceof n}catch(i){}return r?function(e,r){var l=new n(e,{detail:{reason:r.value,key:r},bubbles:!1,cancelable:!0});return!t.dispatchEvent(l)}:e}(G,self,CustomEvent):G}var z=e.scheduler,X=W(),J=Object.create||function(e){function t(){}return t.prototype=e,new t};t.resolve=r,t.reject=l,t.never=i,t._defer=a,t._handler=g,t.prototype.then=function(e,t,n){var r=this._handler,l=r.join().state();if("function"!=typeof e&&l>0||"function"!=typeof t&&0>l)return new this.constructor(b,r);var i=this._beget(),a=i._handler;return r.chain(a,r.receiver,e,t,n),i},t.prototype["catch"]=function(e){return this.then(void 0,e)},t.prototype._beget=function(){return s(this._handler,this.constructor)},t.all=o,t.race=h,t._traverse=u,t._visitRemaining=d,b.prototype.when=b.prototype.become=b.prototype.notify=b.prototype.fail=b.prototype._unreport=b.prototype._report=G,b.prototype._state=0,b.prototype.state=function(){return this._state},b.prototype.join=function(){for(var e=this;void 0!==e.handler;)e=e.handler;return e},b.prototype.chain=function(e,t,n,r,l){this.when({resolver:e,receiver:t,fulfilled:n,rejected:r,progress:l})},b.prototype.visit=function(e,t,n,r){this.chain(Y,e,t,n,r)},b.prototype.fold=function(e,t,n,r){this.when(new L(e,t,n,r))},q(b,x),x.prototype.become=function(e){e.fail()};var Y=new x;q(b,E),E.prototype._state=0,E.prototype.resolve=function(e){this.become(g(e))},E.prototype.reject=function(e){this.resolved||this.become(new I(e))},E.prototype.join=function(){if(!this.resolved)return this;for(var e=this;void 0!==e.handler;)if(e=e.handler,e===this)return this.handler=C();return e},E.prototype.run=function(){var e=this.consumers,t=this.handler;this.handler=this.handler.join(),this.consumers=void 0;for(var n=0;n<e.length;++n)t.when(e[n])},E.prototype.become=function(e){this.resolved||(this.resolved=!0,this.handler=e,void 0!==this.consumers&&z.enqueue(this),void 0!==this.context&&e._report(this.context))},E.prototype.when=function(e){this.resolved?z.enqueue(new j(e,this.handler)):void 0===this.consumers?this.consumers=[e]:this.consumers.push(e)},E.prototype.notify=function(e){this.resolved||z.enqueue(new M(e,this))},E.prototype.fail=function(e){var t="undefined"==typeof e?this.context:e;this.resolved&&this.handler.join().fail(t)},E.prototype._report=function(e){this.resolved&&this.handler.join()._report(e)},E.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},q(b,_),_.prototype.when=function(e){z.enqueue(new j(e,this))},_.prototype._report=function(e){this.join()._report(e)},_.prototype._unreport=function(){this.join()._unreport()},q(E,w),q(b,S),S.prototype._state=1,S.prototype.fold=function(e,t,n,r){R(e,t,this,n,r)},S.prototype.when=function(e){D(e.fulfilled,this,e.receiver,e.resolver)};var K=0;q(b,I),I.prototype._state=-1,I.prototype.fold=function(e,t,n,r){r.become(this)},I.prototype.when=function(e){"function"==typeof e.rejected&&this._unreport(),D(e.rejected,this,e.receiver,e.resolver)},I.prototype._report=function(e){z.afterQueue(new k(this,e))},I.prototype._unreport=function(){this.handled||(this.handled=!0,z.afterQueue(new T(this)))},I.prototype.fail=function(e){this.reported=!0,X("unhandledRejection",this),t.onFatalRejection(this,void 0===e?this.context:e)},k.prototype.run=function(){this.rejection.handled||this.rejection.reported||(this.rejection.reported=!0,X("unhandledRejection",this.rejection)||t.onPotentiallyUnhandledRejection(this.rejection,this.context))},T.prototype.run=function(){this.rejection.reported&&(X("rejectionHandled",this.rejection)||t.onPotentiallyUnhandledRejectionHandled(this.rejection))},t.createContext=t.enterContext=t.exitContext=t.onPotentiallyUnhandledRejection=t.onPotentiallyUnhandledRejectionHandled=t.onFatalRejection=G;var Q=new b,Z=new t(b,Q);return j.prototype.run=function(){this.handler.join().when(this.continuation)},M.prototype.run=function(){var e=this.handler.consumers;if(void 0!==e)for(var t,n=0;n<e.length;++n)t=e[n],F(t.progress,this.value,this.handler,t.receiver,t.resolver)},A.prototype.run=function(){function e(e){r.resolve(e)}function t(e){r.reject(e)}function n(e){r.notify(e)}var r=this.resolver;O(this._then,this.thenable,e,t,n)},L.prototype.fulfilled=function(e){this.f.call(this.c,this.z,e,this.to)},L.prototype.rejected=function(e){this.to.reject(e)},L.prototype.progress=function(e){this.to.notify(e)},t}})}("function"==typeof e&&e.amd?e:function(e){n.exports=e()})},{}]},{},[1])(1)}),function(__global){function __eval(__source,__global,__load){try{eval('(function() { var __moduleName = "'+(__load.name||"").replace('"','"')+'"; '+__source+" \n }).call(__global);")}catch(e){throw("SyntaxError"==e.name||"TypeError"==e.name)&&(e.message="Evaluating "+(__load.name||load.address)+"\n "+e.message),e}}$__Object$getPrototypeOf=Object.getPrototypeOf||function(e){return e.__proto__};var $__Object$defineProperty;!function(){try{Object.defineProperty({},"a",{})&&($__Object$defineProperty=Object.defineProperty)}catch(e){$__Object$defineProperty=function(e,t,n){try{e[t]=n.value||n.get.call(e)}catch(r){}}}}(),$__Object$create=Object.create||function(e,t){function n(){}if(n.prototype=e,"object"==typeof t)for(prop in t)t.hasOwnProperty(prop)&&(n[prop]=t[prop]);return new n},function(){function e(e){return{status:"loading",name:e,linkSets:[],dependencies:[],metadata:{}}}function t(e,t,n){return new k(a({step:n.address?"fetch":"locate",loader:e,moduleName:t,moduleMetadata:n&&n.metadata||{},moduleSource:n.source,moduleAddress:n.address}))}function n(t,n,l,i){return new k(function(e){e(t.loaderObj.normalize(n,l,i))}).then(function(n){var l;if(t.modules[n])return l=e(n),l.status="linked",l.module=t.modules[n],l;for(var i=0,a=t.loads.length;a>i;i++)if(l=t.loads[i],l.name==n)return l;return l=e(n),t.loads.push(l),r(t,l),l})}function r(e,t){l(e,t,k.resolve().then(function(){return e.loaderObj.locate({name:t.name,metadata:t.metadata})}))}function l(e,t,n){i(e,t,n.then(function(n){return"loading"==t.status?(t.address=n,e.loaderObj.fetch({name:t.name,metadata:t.metadata,address:n})):void 0}))}function i(e,t,r){r.then(function(r){return"loading"==t.status?k.resolve(e.loaderObj.translate({name:t.name,metadata:t.metadata,address:t.address,source:r})).then(function(n){return t.source=n,e.loaderObj.instantiate({name:t.name,metadata:t.metadata,address:t.address,source:n})}).then(function(n){if(void 0===n)return t.address=t.address||"<Anonymous Module "+ ++j+">",t.isDeclarative=!0,e.loaderObj.transpile(t).then(function(e){var n=__global.System,r=n.register;n.register=function(e,n,r){"string"!=typeof e&&(r=n,n=e),t.declare=r,t.depsList=n},__eval(e,__global,t),n.register=r});if("object"!=typeof n)throw TypeError("Invalid instantiate return value");t.depsList=n.deps||[],t.execute=n.execute,t.isDeclarative=!1}).then(function(){t.dependencies=[];for(var r=t.depsList,l=[],i=0,a=r.length;a>i;i++)(function(r,i){l.push(n(e,r,t.name,t.address).then(function(e){if(t.dependencies[i]={key:r,value:e.name},"linked"!=e.status)for(var n=t.linkSets.concat([]),l=0,a=n.length;a>l;l++)o(n[l],e)}))})(r[i],i);return k.all(l)}).then(function(){t.status="loaded";for(var e=t.linkSets.concat([]),n=0,r=e.length;r>n;n++)c(e[n],t)}):void 0})["catch"](function(e){t.status="failed",t.exception=e;for(var n=t.linkSets.concat([]),r=0,l=n.length;l>r;r++)p(n[r],t,e)})}function a(t){return function(n){var a=t.loader,o=t.moduleName,u=t.step;if(a.modules[o])throw new TypeError('"'+o+'" already exists in the module table');for(var c,p=0,d=a.loads.length;d>p;p++)if(a.loads[p].name==o)return c=a.loads[p],"translate"!=u||c.source||(c.address=t.moduleAddress,i(a,c,k.resolve(t.moduleSource))),c.linkSets[0].done.then(function(){n(c)});var f=e(o);f.metadata=t.moduleMetadata;var h=s(a,f);a.loads.push(f),n(h.done),"locate"==u?r(a,f):"fetch"==u?l(a,f,k.resolve(t.moduleAddress)):(f.address=t.moduleAddress,i(a,f,k.resolve(t.moduleSource)))}}function s(e,t){var n={loader:e,loads:[],startingLoad:t,loadingCount:0};return n.done=new k(function(e,t){n.resolve=e,n.reject=t}),o(n,t),n}function o(e,t){for(var n=0,r=e.loads.length;r>n;n++)if(e.loads[n]==t)return;e.loads.push(t),t.linkSets.push(e),"loaded"!=t.status&&e.loadingCount++;for(var l=e.loader,n=0,r=t.dependencies.length;r>n;n++){var i=t.dependencies[n].value;if(!l.modules[i])for(var a=0,s=l.loads.length;s>a;a++)if(l.loads[a].name==i){o(e,l.loads[a]);break}}}function u(e){var t=!1;try{m(e,function(n,r){p(e,n,r),t=!0})}catch(n){p(e,null,n),t=!0}return t}function c(e,t){if(e.loadingCount--,!(e.loadingCount>0)){var n=e.startingLoad;if(e.loader.loaderObj.execute===!1){for(var r=[].concat(e.loads),l=0,i=r.length;i>l;l++){var t=r[l];t.module=t.isDeclarative?{name:t.name,module:M({}),evaluated:!0}:{module:M({})},t.status="linked",d(e.loader,t)}return e.resolve(n)}var a=u(e);a||e.resolve(n)}}function p(e,t,n){var r=e.loader;t&&e.loads[0].name!=t.name&&(n=_(n,'Error loading "'+t.name+'" from "'+e.loads[0].name+'" at '+(e.loads[0].address||"<unknown>")+"\n")),t&&(n=_(n,'Error loading "'+t.name+'" at '+(t.address||"<unknown>")+"\n"));for(var l=e.loads.concat([]),i=0,a=l.length;a>i;i++){var t=l[i];r.loaderObj.failed=r.loaderObj.failed||[],-1==T.call(r.loaderObj.failed,t)&&r.loaderObj.failed.push(t);var s=T.call(t.linkSets,e);if(t.linkSets.splice(s,1),0==t.linkSets.length){var o=T.call(e.loader.loads,t);-1!=o&&e.loader.loads.splice(o,1)}}e.reject(n)}function d(e,t){if(e.loaderObj.trace){e.loaderObj.loads||(e.loaderObj.loads={});var n={};t.dependencies.forEach(function(e){n[e.key]=e.value}),e.loaderObj.loads[t.name]={name:t.name,deps:t.dependencies.map(function(e){return e.key}),depMap:n,address:t.address,metadata:t.metadata,source:t.source,kind:t.isDeclarative?"declarative":"dynamic"}}t.name&&(e.modules[t.name]=t.module);var r=T.call(e.loads,t);-1!=r&&e.loads.splice(r,1);for(var l=0,i=t.linkSets.length;i>l;l++)r=T.call(t.linkSets[l].loads,t),-1!=r&&t.linkSets[l].loads.splice(r,1);t.linkSets.splice(0,t.linkSets.length)}function f(e,t,n){if(n[e.groupIndex]=n[e.groupIndex]||[],-1==T.call(n[e.groupIndex],e)){n[e.groupIndex].push(e);for(var r=0,l=t.length;l>r;r++)for(var i=t[r],a=0;a<e.dependencies.length;a++)if(i.name==e.dependencies[a].value){var s=e.groupIndex+(i.isDeclarative!=e.isDeclarative);if(void 0===i.groupIndex||i.groupIndex<s){if(void 0!==i.groupIndex&&(n[i.groupIndex].splice(T.call(n[i.groupIndex],i),1),0==n[i.groupIndex].length))throw new TypeError("Mixed dependency cycle detected");i.groupIndex=s}f(i,t,n)}}}function h(e,t,n){try{var r=t.execute()}catch(l){return void n(t,l)}return r&&r instanceof S?r:void n(t,new TypeError("Execution must define a Module instance"))}function m(e,t){var n=e.loader;if(e.loads.length){var r=[],l=e.loads[0];l.groupIndex=0,f(l,e.loads,r);for(var i=l.isDeclarative==r.length%2,a=r.length-1;a>=0;a--){for(var s=r[a],o=0;o<s.length;o++){var u=s[o];if(i)y(u,e.loads,n);else{var c=h(e,u,t);if(!c)return;u.module={name:u.name,module:c},u.status="linked"}d(n,u)}i=!i}}}function g(e,t){var n=t.moduleRecords;return n[e]||(n[e]={name:e,dependencies:[],module:new S,importers:[]})}function y(e,t,n){if(!e.module){var r=e.module=g(e.name,n),l=e.module.module,i=e.declare.call(__global,function(e,t){r.locked=!0,l[e]=t;for(var n=0,i=r.importers.length;i>n;n++){var a=r.importers[n];if(!a.locked){var s=T.call(a.dependencies,r);a.setters[s](l)}}return r.locked=!1,t});r.setters=i.setters,r.execute=i.execute;for(var a=0,s=e.dependencies.length;s>a;a++){var o=e.dependencies[a].value,u=n.modules[o];if(!u)for(var c=0;c<t.length;c++)t[c].name==o&&(t[c].module?u=g(o,n):(y(t[c],t,n),u=t[c].module));u.importers?(r.dependencies.push(u),u.importers.push(r)):r.dependencies.push(null),r.setters[a]&&r.setters[a](u.module)}e.status="linked"}}function v(e,t){return x(t.module,[],e),t.module.module}function b(e){try{e.execute.call(__global)}catch(t){return t}}function x(e,t,n){var r=E(e,t,n);if(r)throw r}function E(e,t,n){if(!e.evaluated&&e.dependencies){t.push(e);for(var r,l=e.dependencies,i=0,a=l.length;a>i;i++){var s=l[i];if(s&&-1==T.call(t,s)&&(r=E(s,t,n)))return r=_(r,"Error evaluating "+s.name+"\n")}if(e.failed)return new Error("Module failed execution.");if(!e.evaluated)return e.evaluated=!0,r=b(e),r?e.failed=!0:Object.preventExtensions&&Object.preventExtensions(e.module),e.execute=void 0,r}}function _(e,t){return e instanceof Error?e.message=t+e.message:e=t+e,e}function w(e){if("object"!=typeof e)throw new TypeError("Options must be an object");e.normalize&&(this.normalize=e.normalize),e.locate&&(this.locate=e.locate),e.fetch&&(this.fetch=e.fetch),e.translate&&(this.translate=e.translate),e.instantiate&&(this.instantiate=e.instantiate),this._loader={loaderObj:this,loads:[],modules:{},importPromises:{},moduleRecords:{}},C(this,"global",{get:function(){return __global}})}function S(){}function I(e,t,n){var r=e._loader.importPromises;return r[t]=n.then(function(e){return r[t]=void 0,e},function(e){throw r[t]=void 0,e})}var k=__global.Promise||require("when/es6-shim/Promise");__global.console&&(console.assert=console.assert||function(){});var T=Array.prototype.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},C=$__Object$defineProperty,j=0;w.prototype={constructor:w,define:function(e,t,n){if(this._loader.importPromises[e])throw new TypeError("Module is already loading.");return I(this,e,new k(a({step:"translate",loader:this._loader,moduleName:e,moduleMetadata:n&&n.metadata||{},moduleSource:t,moduleAddress:n&&n.address})))},"delete":function(e){var t=this._loader;return delete t.importPromises[e],delete t.moduleRecords[e],t.modules[e]?delete t.modules[e]:!1},get:function(e){return this._loader.modules[e]?(x(this._loader.modules[e],[],this),this._loader.modules[e].module):void 0},has:function(e){return!!this._loader.modules[e]},"import":function(e,n){var r=this;return k.resolve(r.normalize(e,n&&n.name,n&&n.address)).then(function(e){var l=r._loader;return l.modules[e]?(x(l.modules[e],[],l._loader),l.modules[e].module):l.importPromises[e]||I(r,e,t(l,e,n||{}).then(function(t){return delete l.importPromises[e],v(l,t)}))})},load:function(e){return this._loader.modules[e]?(x(this._loader.modules[e],[],this._loader),k.resolve(this._loader.modules[e].module)):this._loader.importPromises[e]||I(this,e,t(this._loader,e,{}))},module:function(t,n){var r=e();r.address=n&&n.address;var l=s(this._loader,r),a=k.resolve(t),o=this._loader,u=l.done.then(function(){return v(o,r)});return i(o,r,a),u},newModule:function(e){if("object"!=typeof e)throw new TypeError("Expected object");var t,n=new S;if(Object.getOwnPropertyNames&&null!=e)t=Object.getOwnPropertyNames(e);else{t=[];for(var r in e)t.push(r)}for(var l=0;l<t.length;l++)(function(t){C(n,t,{configurable:!1,enumerable:!0,get:function(){return e[t]}})})(t[l]);return Object.preventExtensions&&Object.preventExtensions(n),n},set:function(e,t){if(!(t instanceof S))throw new TypeError("Loader.set("+e+", module) must be a module");this._loader.modules[e]={module:t}},normalize:function(e){return e},locate:function(e){return e.name},fetch:function(){throw new TypeError("Fetch not implemented")},translate:function(e){return e.source},instantiate:function(){}};var M=w.prototype.newModule;"object"==typeof exports&&(module.exports=w),__global.Reflect=__global.Reflect||{},__global.Reflect.Loader=__global.Reflect.Loader||w,__global.Reflect.global=__global.Reflect.global||__global,__global.LoaderPolyfill=w}(),function(e){function t(e,t){return e.newModule({"default":i[t],__useDefault:!0})}function n(e,t){var n=this.traceurOptions||{};n.modules="instantiate",n.script=!1,n.sourceMaps="inline",n.filename=e.address,n.inputSourceMap=e.metadata.sourceMap,n.moduleName=!1;var l=new t.Compiler(n),i=r(e.source,l,n.filename);return i+"\n//# sourceURL="+e.address+"!eval"}function r(e,t,n){try{return t.compile(e,n)}catch(r){throw r[0]}}function l(e,t){var n=this.babelOptions||{};n.modules="system",n.sourceMap="inline",n.filename=e.address,n.code=!0,n.ast=!1,n.blacklist||(n.blacklist=["react"]);var r=t.transform(e.source,n).code;return r+"\n//# sourceURL="+e.address+"!eval"}var i=__global;e.prototype.transpiler="traceur",e.prototype.transpile=function(e){var r=this;return r.transpilerHasRun||(i.traceur&&!r.has("traceur")&&r.set("traceur",t(r,"traceur")),i.babel&&!r.has("babel")&&r.set("babel",t(r,"babel")),r.transpilerHasRun=!0),r["import"](r.transpiler).then(function(t){return t.__useDefault&&(t=t["default"]),'var __moduleAddress = "'+e.address+'";'+(t.Compiler?n:l).call(r,e,t)})},e.prototype.instantiate=function(e){var n=this;return Promise.resolve(n.normalize(n.transpiler)).then(function(r){return e.name===r?{deps:[],execute:function(){var r=i.System,l=i.Reflect.Loader;return __eval("(function(require,exports,module){"+e.source+"})();",i,e),i.System=r,i.Reflect.Loader=l,t(n,e.name)}}:void 0})}}(__global.LoaderPolyfill),function(){function e(e){var t=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@\/?#]*(?::[^:@\/?#]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null}function t(e){var t=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?t.pop():t.push(e)}),t.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}function n(n,r){return s&&(r=r.replace(/\\/g,"/")),r=e(r||""),n=e(n||""),r&&n?(r.protocol||n.protocol)+(r.protocol||r.authority?r.authority:n.authority)+t(r.protocol||r.authority||"/"===r.pathname.charAt(0)?r.pathname:r.pathname?(n.authority&&!n.pathname?"/":"")+n.pathname.slice(0,n.pathname.lastIndexOf("/")+1)+r.pathname:n.pathname)+(r.protocol||r.authority||r.pathname?r.search:r.search||n.search)+r.hash:null}function r(){document.removeEventListener("DOMContentLoaded",r,!1),window.removeEventListener("load",r,!1),l()}function l(){for(var e=document.getElementsByTagName("script"),t=0;t<e.length;t++){var n=e[t];if("module"==n.type){var r=n.innerHTML.substr(1);__global.System.module(r)["catch"](function(e){setTimeout(function(){throw e})})}}}var i,a="undefined"!=typeof window&&"undefined"!=typeof document,s="undefined"!=typeof process&&!!process.platform.match(/^win/),o=__global.Promise||require("when/es6-shim/Promise");if("undefined"!=typeof XMLHttpRequest)i=function(e,t,n){function r(){t(i.responseText)}function l(){n(i.statusText+": "+e||"XHR error")}var i=new XMLHttpRequest,a=!0,s=!1;if(!("withCredentials"in i)){var o=/^(\w+:)?\/\/([^\/]+)/.exec(e);o&&(a=o[2]===window.location.host,o[1]&&(a&=o[1]===window.location.protocol))}a||"undefined"==typeof XDomainRequest||(i=new XDomainRequest,i.onload=r,i.onerror=l,i.ontimeout=l,i.onprogress=function(){},i.timeout=0,s=!0),i.onreadystatechange=function(){4===i.readyState&&(200===i.status||0==i.status&&i.responseText?r():l())},i.open("GET",e,!0),s&&setTimeout(function(){i.send()},0),i.send(null)};else{if("undefined"==typeof require)throw new TypeError("No environment fetch API available.");var u;i=function(e,t,n){if("file:"!=e.substr(0,5))throw"Only file URLs of the form file: allowed running in Node.";return u=u||require("fs"),e=e.substr(5),s&&(e=e.replace(/\//g,"\\")),u.readFile(e,function(e,r){return e?n(e):void t(r+"")})}}var c=function(e){function t(t){if(e.call(this,t||{}),"undefined"!=typeof location&&location.href){var n=__global.location.href.split("#")[0].split("?")[0];this.baseURL=n.substring(0,n.lastIndexOf("/")+1)}else{if("undefined"==typeof process||!process.cwd)throw new TypeError("No environment baseURL");this.baseURL="file:"+process.cwd()+"/",s&&(this.baseURL=this.baseURL.replace(/\\/g,"/"))}this.paths={"*":"*.js"}}return t.__proto__=null!==e?e:Function.prototype,t.prototype=$__Object$create(null!==e?e.prototype:null),$__Object$defineProperty(t.prototype,"constructor",{value:t}),$__Object$defineProperty(t.prototype,"global",{get:function(){return __global},enumerable:!1}),$__Object$defineProperty(t.prototype,"strict",{get:function(){return!0},enumerable:!1}),$__Object$defineProperty(t.prototype,"normalize",{value:function(e,t){if("string"!=typeof e)throw new TypeError("Module name must be a string");var n=e.split("/");if(0==n.length)throw new TypeError("No module name provided");var r=0,l=!1,i=0;if("."==n[0]){if(r++,r==n.length)throw new TypeError('Illegal module name "'+e+'"');l=!0}else{for(;".."==n[r];)if(r++,r==n.length)throw new TypeError('Illegal module name "'+e+'"');r&&(l=!0),i=r}for(var a=r;a<n.length;a++){var s=n[a];if(""==s||"."==s||".."==s)throw new TypeError('Illegal module name "'+e+'"')}if(!l)return e;var o=[],u=(t||"").split("/");return u.length-1-i,o=o.concat(u.splice(0,u.length-1-i)),o=o.concat(n.splice(r,n.length-r)),o.join("/")},enumerable:!1,writable:!0}),$__Object$defineProperty(t.prototype,"locate",{value:function(e){var t,r=e.name,l="";for(var i in this.paths){var s=i.split("*");if(s.length>2)throw new TypeError("Only one wildcard in a path is permitted");if(1==s.length){if(r==i&&i.length>l.length){l=i;break}}else r.substr(0,s[0].length)==s[0]&&r.substr(r.length-s[1].length)==s[1]&&(l=i,t=r.substr(s[0].length,r.length-s[1].length-s[0].length))}var o=this.paths[l];return t&&(o=o.replace("*",t)),a&&(o=o.replace(/#/g,"%23")),n(this.baseURL,o)},enumerable:!1,writable:!0}),$__Object$defineProperty(t.prototype,"fetch",{value:function(e){var t=this;return new o(function(r,l){i(n(t.baseURL,e.address),function(e){r(e)},l)})},enumerable:!1,writable:!0}),t}(__global.LoaderPolyfill),p=new c;if("object"==typeof exports&&(module.exports=p),__global.System=p,a&&document.getElementsByTagName){var d=document.getElementsByTagName("script");d=d[d.length-1],"complete"===document.readyState?setTimeout(l):document.addEventListener&&(document.addEventListener("DOMContentLoaded",r,!1),window.addEventListener("load",r,!1)),d.getAttribute("data-init")&&window[d.getAttribute("data-init")]()}}()}("undefined"!=typeof window?window:"undefined"!=typeof global?global:self),function e(t,n,r){function l(a,s){if(!n[a]){if(!t[a]){var o="function"==typeof require&&require;if(!s&&o)return o(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return l(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)l(r[a]);return l}({1:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=e("./models/Module.js"),s=r(a),o=e("./models/Component.js"),u=r(o),c=e("./helpers/Selectors.js"),p=r(c),d=e("./helpers/Utility.js"),f=r(d),h=e("./helpers/Events.js"),m=r(h);!function(e,t){function n(){var e=t.readyState,n=["interactive","complete"];!r&&~n.indexOf(e)&&(r=!0,new a)}"undefined"!=typeof System&&(System.transpiler="babel",System.babelOptions={blacklist:[]});var r=!1,a=function(){function e(){l(this,e),this.findLinks(),this.findTemplates(),m["default"].setupDelegation()}return i(e,[{key:"findLinks",value:function(){p["default"].getImports(t).forEach(function(e){return e["import"]?void new s["default"](e):void e.addEventListener("load",function(){return new s["default"](e)})})}},{key:"findTemplates",value:function(){p["default"].getTemplates(t).forEach(function(e){var t=p["default"].getAllScripts(e.content),n=e.getAttribute("ref"),r=f["default"].resolver(n,null).production;t.forEach(function(t){r.isLocalPath(t.getAttribute("src"))&&new u["default"](r,e,t)})})}}]),e}();n(),t.addEventListener("DOMContentLoaded",n)}(window,document)},{"./helpers/Events.js":3,"./helpers/Selectors.js":5,"./helpers/Utility.js":6,"./models/Component.js":7,"./models/Module.js":9}],2:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t={};return{fetch:function(n){return t[n]?t[n]:(t[n]=new Promise(function(t){e.fetch(n).then(function(e){return e.text()}).then(function(e){t(e)})}),t[n])}}}(window),t.exports=n["default"]},{}],3:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var l=e("./Utility.js"),i=r(l);!function(){var e=Event.prototype.stopPropagation;Event.prototype.stopPropagation=function(){this.isPropagationStopped=!0,e.apply(this,arguments)}}(),n["default"]=function(e){var t=[],n=null;return{findById:function(e){function n(t,l){return t._rootNodeID===e?void function(){r={properties:this._currentElement.props,component:l}}.bind(t)():void(t._renderedComponent&&!function(){var e=t._renderedComponent._renderedChildren;e&&Object.keys(e).forEach(function(t){n(e[t],l)})}())}var r=void 0;return t.forEach(function(e){n(e._reactInternalInstance._renderedComponent,e)}),r},transformKeys:function(e){var t=void 0===arguments[1]?"toLowerCase":arguments[1],n={};return Object.keys(e).forEach(function(r){n[r[t]()]=e[r]}),n},registerComponent:function(e){t.push(e)},setupDelegation:function(){var t=this,r=n||function(){var t=e.createElement("a"),n=/^on/i,r=[];for(var l in t)l.match(n)&&r.push(l.replace(n,""));return r}();r.forEach(function(n){e.addEventListener(n,function(e){var n="on"+e.type,r=[];i["default"].toArray(e.path).forEach(function(l){if(!e.isPropagationStopped&&l.getAttribute&&l.hasAttribute(i["default"].ATTRIBUTE_REACTID)){var a=t.findById(l.getAttribute(i["default"].ATTRIBUTE_REACTID));if(a&&a.properties){var s=t.transformKeys(a.properties);n in s&&r.push(s[n].bind(a.component,e))}}}),r.forEach(function(e){return e()})})})}}}(window.document),t.exports=n["default"]},{"./Utility.js":6}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){return{warn:function(t){e.log("Maple.js: %c"+t+".","color: #5F9EA0")},info:function(t){e.log("Maple.js: %c"+t+".","color: blue")},error:function(t){e.error("%c Maple.js: %c"+t+".","color: black","color: #CD6090")}}}(window.console),t.exports=n["default"]},{}],5:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var l=e("./Utility.js"),i=r(l),a=function(e){return i["default"].toArray(this.querySelectorAll(e))};n["default"]=function(){return{getCSSLinks:function(e){return a.call(e,'link[type="text/css"],link[type="text/scss"]')},getCSSInlines:function(e){return a.call(e,'style[type="text/css"]')},getImports:function(e){return a.call(e,'link[rel="import"]:not([data-ignore])')},getTemplates:function(e){return a.call(e,"template[ref]")},getScripts:function(e){return a.call(e,'script[type="text/javascript"]')},getAllScripts:function(e){var t=a.call(e,'script[type="text/jsx"]');return[].concat(i["default"].toArray(this.getScripts(e)),i["default"].toArray(t))}}}(),t.exports=n["default"]},{"./Utility.js":6}],6:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){return{ATTRIBUTE_REACTID:"data-reactid",resolver:function(t,n){function r(t){var n=void 0===arguments[1]?e:arguments[1],r=n.createElement("a");return r.href=t,r.href}var l=this.getPath(t),i=this.getPath.bind(this),a=this.getName.bind(this);return{production:{getPath:function(t){return this.isLocalPath(t)?""+this.getAbsolutePath()+"/"+a(t):r(t,e)},getSrc:function(e){return a(e)},getAbsolutePath:function(){return r(t)},getRelativePath:function(){return t},isLocalPath:function(e){return!!~e.indexOf(t)}},development:{getPath:function(t){return this.isLocalPath(t)?""+this.getAbsolutePath()+"/"+t:r(t,e)},getSrc:function(e){return e},getAbsolutePath:function(){return r(l)},getRelativePath:function(){return l},isLocalPath:function(e){return e=i(r(e,n)),!!~r(l).indexOf(e)}}}},toArray:function(e){return Array.from?Array.from(e):Array.prototype.slice.apply(e)},flattenArray:function(e){var t=this,n=void 0===arguments[1]?[]:arguments[1];return e.forEach(function(e){Array.isArray(e)&&t.flattenArray(e,n),!Array.isArray(e)&&n.push(e)}),n},toSnakeCase:function(e){var t=void 0===arguments[1]?"-":arguments[1];return e.split(/([A-Z][a-z]{0,})/g).filter(function(e){return e}).join(t).toLowerCase()},getName:function(e){return e.split("/").slice(-1)},getPath:function(e){return e.split("/").slice(0,-1).join("/")},removeExtension:function(e){return e.split(".").slice(0,-1).join(".")}}}(window.document),t.exports=n["default"]},{}],7:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{ "default":e}}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var l=e,i=t,a=n;s=u=o=void 0,r=!1;var s=Object.getOwnPropertyDescriptor(l,i);if(void 0!==s){if("value"in s)return s.value;var o=s.get;return void 0===o?void 0:o.call(a)}var u=Object.getPrototypeOf(l);if(null===u)return void 0;e=u,t=i,n=a,r=!0}},o=e("./Element.js"),u=r(o),c=e("./../helpers/Utility.js"),p=r(c),d=e("./../helpers/Logger.js"),f=r(d),h=e("./StateManager.js"),m=function(e){function t(e,n,r){var i=this;l(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),this.path=e,this.elements={script:r,template:n};var a=r.getAttribute("src");this.setState(h.State.RESOLVING);var o=""+this.path.getRelativePath()+"/"+p["default"].removeExtension(a);return"jsx"===a.split(".").pop().toLowerCase()?void f["default"].error("Use JS extension instead of JSX – JSX compilation will work as expected"):void System["import"](""+o).then(function(t){t["default"]&&Promise.all(i.loadThirdPartyScripts()).then(function(){new u["default"](e,n,r,t["default"]),i.setState(h.State.RESOLVED)})})}return i(t,e),a(t,[{key:"loadThirdPartyScripts",value:function(){var e=this,t=p["default"].toArray(this.elements.template.content.querySelectorAll('script[type="text/javascript"]')),n=t.filter(function(t){return!e.path.isLocalPath(t.getAttribute("src"))});return n.map(function(e){var t=e.getAttribute("src");return e=document.createElement("script"),e.setAttribute("type","text/javascript"),e.setAttribute("src",t),new Promise(function(t){e.addEventListener("load",function(){return t()}),document.head.appendChild(e)})})}}]),t}(h.StateManager);n["default"]=m,t.exports=n["default"]},{"./../helpers/Logger.js":4,"./../helpers/Utility.js":6,"./Element.js":8,"./StateManager.js":10}],8:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var l=e,i=t,a=n;s=u=o=void 0,r=!1;var s=Object.getOwnPropertyDescriptor(l,i);if(void 0!==s){if("value"in s)return s.value;var o=s.get;return void 0===o?void 0:o.call(a)}var u=Object.getPrototypeOf(l);if(null===u)return void 0;e=u,t=i,n=a,r=!0}},o=e("./../helpers/Events.js"),u=r(o),c=e("./../helpers/Utility.js"),p=r(c),d=e("./../helpers/Logger.js"),f=r(d),h=e("./../helpers/CacheFactory.js"),m=r(h),g=e("./../helpers/Selectors.js"),y=r(g),v=e("./StateManager.js"),b=function(e){function t(e,n,r,i){l(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),this.path=e,this.sass="undefined"==typeof Sass?null:new Sass,this.elements={script:r,template:n},this.script=i;var a=this.getDescriptor();if(!a.extend)return void document.registerElement(a.name,{prototype:this.getElementPrototype()});var o="HTML"+a.extend+"Element";document.registerElement(a.name,{prototype:Object.create(window[o].prototype,this.getElementPrototype()),"extends":a.extend.toLowerCase()})}return i(t,e),a(t,[{key:"loadStyles",value:function(e){function t(t){var n=document.createElement("style");n.setAttribute("type","text/css"),n.innerHTML=t,e.appendChild(n)}var n=this;this.setState(v.State.RESOLVING);var r=this.elements.template.content,l=y["default"].getCSSLinks(r),i=y["default"].getCSSInlines(r),a=[].concat(l,i).map(function(e){return new Promise(function(r){return"style"===e.nodeName.toLowerCase()?(t(e.innerHTML),void r(e.innerHTML)):void m["default"].fetch(n.path.getPath(e.getAttribute("href"))).then(function(l){return"text/scss"===e.getAttribute("type")?n.sass?(f["default"].warn("All of your SASS documents should be compiled to CSS for production via your build process"),void n.sass.compile(l,function(e){t(e.text),r(e.text)})):(f["default"].error('You should include "sass.js" for development runtime SASS compilation'),void reject()):(t(l),void r(l))})})});return Promise.all(a).then(function(){return n.setState(v.State.RESOLVED)}),a}},{key:"getDescriptor",value:function(){var e=this.script.name||this.script.toString().match(/(?:function|class)\s*([a-z_]+)/i)[1],t=null;if(~e.indexOf("_")){var n=e.split("_");e=n[0],t=n[1]}return{name:p["default"].toSnakeCase(e),extend:t}}},{key:"getElementPrototype",value:function(){var e=this.loadStyles.bind(this),t=this.script,n=this.path;return Object.create(HTMLElement.prototype,{attachedCallback:{value:function(){function r(e){for(var n=0;n<e.length;n++){var r=e.item(n),l=/^data-/i;if(r.value){if(r.name===p["default"].ATTRIBUTE_REACTID)continue;var i=r.name.replace(l,"");t.defaultProps[i]=r.value}}}function l(){var t=this;Promise.all(e(s)).then(function(){t.removeAttribute("unresolved"),t.setAttribute("resolved","")})}t.defaultProps={path:n,element:this.cloneNode(!0)},r.call(this,this.attributes),this.innerHTML="";var i=React.createElement(t),a=document.createElement("content"),s=this.createShadowRoot();s.appendChild(a);var o=React.render(i,a);u["default"].registerComponent(o),l.apply(this)}}})}}]),t}(v.StateManager);n["default"]=b,t.exports=n["default"]},{"./../helpers/CacheFactory.js":2,"./../helpers/Events.js":3,"./../helpers/Logger.js":4,"./../helpers/Selectors.js":5,"./../helpers/Utility.js":6,"./StateManager.js":10}],9:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var l=e,i=t,a=n;s=u=o=void 0,r=!1;var s=Object.getOwnPropertyDescriptor(l,i);if(void 0!==s){if("value"in s)return s.value;var o=s.get;return void 0===o?void 0:o.call(a)}var u=Object.getPrototypeOf(l);if(null===u)return void 0;e=u,t=i,n=a,r=!0}},o=e("./Component.js"),u=r(o),c=e("./../helpers/Utility.js"),p=r(c),d=e("./../helpers/Logger.js"),f=r(d),h=e("./../helpers/Selectors.js"),m=r(h),g=e("./StateManager.js"),y=function(e){function t(e){var n=this;l(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),this.path=p["default"].resolver(e.getAttribute("href"),e["import"]).development,this.state=g.State.UNRESOLVED,this.elements={link:e},this.components=[],this.loadModule(e).then(function(){var t=n.getTemplates();return t.length>1?void f["default"].error('Component "'+e.getAttribute("href")+'" is attempting to register two components'):([n.getTemplates()[0]].forEach(function(e){var t=m["default"].getAllScripts(e.content);t.map(function(t){var r=t.getAttribute("src");if(n.path.isLocalPath(r)){var l=new u["default"](n.path,e,t);n.components.push(l)}})}),void n.setState(g.State.RESOLVED))})}return i(t,e),a(t,[{key:"setState",value:function(e){this.state=e}},{key:"loadModule",value:function(e){return this.setState(g.State.RESOLVING),new Promise(function(t){return e.hasAttribute("ref")?void t(e):e["import"]?void t(e):void e.addEventListener("load",function(){t(e)})})}},{key:"getTemplates",value:function(){var e=this.elements.link["import"];return p["default"].toArray(e.querySelectorAll("template"))}}]),t}(g.StateManager);n["default"]=y,t.exports=n["default"]},{"./../helpers/Logger.js":4,"./../helpers/Selectors.js":5,"./../helpers/Utility.js":6,"./Component.js":7,"./StateManager.js":10}],10:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i={UNRESOLVED:0,RESOLVING:1,RESOLVED:2};n.State=i;var a=function(){function e(){r(this,e),this.state=i.UNRESOLVED}return l(e,[{key:"setState",value:function(e){this.state=e}}]),e}();n.StateManager=a},{}]},{},[1]);
ajax/libs/raven.js/3.25.2/angular,console,require/raven.js
jonobr1/cdnjs
/*! Raven.js 3.25.2 (30b6d4e) | github.com/getsentry/raven-js */ /* * Includes TraceKit * https://github.com/getsentry/TraceKit * * Copyright 2018 Matt Robenolt and other contributors * Released under the BSD license * https://github.com/getsentry/raven-js/blob/master/LICENSE * */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Raven = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Angular.js plugin * * Provides an $exceptionHandler for Angular.js */ var wrappedCallback = _dereq_(8).wrappedCallback; // See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/; var moduleName = 'ngRaven'; function angularPlugin(Raven, angular) { angular = angular || window.angular; if (!angular) return; function RavenProvider() { this.$get = [ '$window', function($window) { return Raven; } ]; } function ExceptionHandlerProvider($provide) { $provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]); } function exceptionHandler(R, $delegate) { return function(ex, cause) { R.captureException(ex, { extra: {cause: cause} }); $delegate(ex, cause); }; } angular .module(moduleName, []) .provider('Raven', RavenProvider) .config(['$provide', ExceptionHandlerProvider]); Raven.setDataCallback( wrappedCallback(function(data) { return angularPlugin._normalizeData(data); }) ); } angularPlugin._normalizeData = function(data) { // We only care about mutating an exception var exception = data.exception; if (exception) { exception = exception.values[0]; var matches = angularPattern.exec(exception.value); if (matches) { // This type now becomes something like: $rootScope:inprog exception.type = matches[1]; exception.value = matches[2]; data.message = exception.type + ': ' + exception.value; // auto set a new tag specifically for the angular error url data.extra.angularDocs = matches[3].substr(0, 250); } } return data; }; angularPlugin.moduleName = moduleName; module.exports = angularPlugin; _dereq_(7).addPlugin(module.exports); },{"7":7,"8":8}],2:[function(_dereq_,module,exports){ /** * console plugin * * Monkey patches console.* calls into Sentry messages with * their appropriate log levels. (Experimental) * * Options: * * `levels`: An array of levels (methods on `console`) to report to Sentry. * Defaults to debug, info, warn, and error. */ var wrapConsoleMethod = _dereq_(5).wrapMethod; function consolePlugin(Raven, console, pluginOptions) { console = console || window.console || {}; pluginOptions = pluginOptions || {}; var logLevels = pluginOptions.levels || ['debug', 'info', 'warn', 'error']; if ('assert' in console) logLevels.push('assert'); var callback = function(msg, data) { Raven.captureMessage(msg, data); }; var level = logLevels.pop(); while (level) { wrapConsoleMethod(console, level, callback); level = logLevels.pop(); } } module.exports = consolePlugin; _dereq_(7).addPlugin(module.exports); },{"5":5,"7":7}],3:[function(_dereq_,module,exports){ /*global define*/ /** * require.js plugin * * Automatically wrap define/require callbacks. (Experimental) */ function requirePlugin(Raven) { if (typeof define === 'function' && define.amd) { window.define = Raven.wrap({deep: false}, define); window.require = Raven.wrap({deep: false}, _dereq_); } } module.exports = requirePlugin; _dereq_(7).addPlugin(module.exports); },{"7":7}],4:[function(_dereq_,module,exports){ function RavenConfigError(message) { this.name = 'RavenConfigError'; this.message = message; } RavenConfigError.prototype = new Error(); RavenConfigError.prototype.constructor = RavenConfigError; module.exports = RavenConfigError; },{}],5:[function(_dereq_,module,exports){ var utils = _dereq_(8); var wrapMethod = function(console, level, callback) { var originalConsoleLevel = console[level]; var originalConsole = console; if (!(level in console)) { return; } var sentryLevel = level === 'warn' ? 'warning' : level; console[level] = function() { var args = [].slice.call(arguments); var msg = utils.safeJoin(args, ' '); var data = {level: sentryLevel, logger: 'console', extra: {arguments: args}}; if (level === 'assert') { if (args[0] === false) { // Default browsers message msg = 'Assertion failed: ' + (utils.safeJoin(args.slice(1), ' ') || 'console.assert'); data.extra.arguments = args.slice(1); callback && callback(msg, data); } } else { callback && callback(msg, data); } // this fails for some browsers. :( if (originalConsoleLevel) { // IE9 doesn't allow calling apply on console functions directly // See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193 Function.prototype.apply.call(originalConsoleLevel, originalConsole, args); } }; }; module.exports = { wrapMethod: wrapMethod }; },{"8":8}],6:[function(_dereq_,module,exports){ (function (global){ /*global XDomainRequest:false */ var TraceKit = _dereq_(9); var stringify = _dereq_(10); var md5 = _dereq_(11); var RavenConfigError = _dereq_(4); var utils = _dereq_(8); var isErrorEvent = utils.isErrorEvent; var isDOMError = utils.isDOMError; var isDOMException = utils.isDOMException; var isError = utils.isError; var isObject = utils.isObject; var isPlainObject = utils.isPlainObject; var isUndefined = utils.isUndefined; var isFunction = utils.isFunction; var isString = utils.isString; var isArray = utils.isArray; var isEmptyObject = utils.isEmptyObject; var each = utils.each; var objectMerge = utils.objectMerge; var truncate = utils.truncate; var objectFrozen = utils.objectFrozen; var hasKey = utils.hasKey; var joinRegExp = utils.joinRegExp; var urlencode = utils.urlencode; var uuid4 = utils.uuid4; var htmlTreeAsString = utils.htmlTreeAsString; var isSameException = utils.isSameException; var isSameStacktrace = utils.isSameStacktrace; var parseUrl = utils.parseUrl; var fill = utils.fill; var supportsFetch = utils.supportsFetch; var supportsReferrerPolicy = utils.supportsReferrerPolicy; var serializeKeysForMessage = utils.serializeKeysForMessage; var serializeException = utils.serializeException; var sanitize = utils.sanitize; var wrapConsoleMethod = _dereq_(5).wrapMethod; var dsnKeys = 'source protocol user pass host port path'.split(' '), dsnPattern = /^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/; function now() { return +new Date(); } // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785) var _window = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var _document = _window.document; var _navigator = _window.navigator; function keepOriginalCallback(original, callback) { return isFunction(callback) ? function(data) { return callback(data, original); } : callback; } // First, check for JSON support // If there is no JSON, we no-op the core features of Raven // since JSON is required to encode the payload function Raven() { this._hasJSON = !!(typeof JSON === 'object' && JSON.stringify); // Raven can run in contexts where there's no document (react-native) this._hasDocument = !isUndefined(_document); this._hasNavigator = !isUndefined(_navigator); this._lastCapturedException = null; this._lastData = null; this._lastEventId = null; this._globalServer = null; this._globalKey = null; this._globalProject = null; this._globalContext = {}; this._globalOptions = { // SENTRY_RELEASE can be injected by https://github.com/getsentry/sentry-webpack-plugin release: _window.SENTRY_RELEASE && _window.SENTRY_RELEASE.id, logger: 'javascript', ignoreErrors: [], ignoreUrls: [], whitelistUrls: [], includePaths: [], headers: null, collectWindowErrors: true, captureUnhandledRejections: true, maxMessageLength: 0, // By default, truncates URL values to 250 chars maxUrlLength: 250, stackTraceLimit: 50, autoBreadcrumbs: true, instrument: true, sampleRate: 1, sanitizeKeys: [] }; this._fetchDefaults = { method: 'POST', keepalive: true, // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default // https://caniuse.com/#feat=referrer-policy // It doesn't. And it throw exception instead of ignoring this parameter... // REF: https://github.com/getsentry/raven-js/issues/1233 referrerPolicy: supportsReferrerPolicy() ? 'origin' : '' }; this._ignoreOnError = 0; this._isRavenInstalled = false; this._originalErrorStackTraceLimit = Error.stackTraceLimit; // capture references to window.console *and* all its methods first // before the console plugin has a chance to monkey patch this._originalConsole = _window.console || {}; this._originalConsoleMethods = {}; this._plugins = []; this._startTime = now(); this._wrappedBuiltIns = []; this._breadcrumbs = []; this._lastCapturedEvent = null; this._keypressTimeout; this._location = _window.location; this._lastHref = this._location && this._location.href; this._resetBackoff(); // eslint-disable-next-line guard-for-in for (var method in this._originalConsole) { this._originalConsoleMethods[method] = this._originalConsole[method]; } } /* * The core Raven singleton * * @this {Raven} */ Raven.prototype = { // Hardcode version string so that raven source can be loaded directly via // webpack (using a build step causes webpack #1617). Grunt verifies that // this value matches package.json during build. // See: https://github.com/getsentry/raven-js/issues/465 VERSION: '3.25.2', debug: false, TraceKit: TraceKit, // alias to TraceKit /* * Configure Raven with a DSN and extra options * * @param {string} dsn The public Sentry DSN * @param {object} options Set of global options [optional] * @return {Raven} */ config: function(dsn, options) { var self = this; if (self._globalServer) { this._logDebug('error', 'Error: Raven has already been configured'); return self; } if (!dsn) return self; var globalOptions = self._globalOptions; // merge in options if (options) { each(options, function(key, value) { // tags and extra are special and need to be put into context if (key === 'tags' || key === 'extra' || key === 'user') { self._globalContext[key] = value; } else { globalOptions[key] = value; } }); } self.setDSN(dsn); // "Script error." is hard coded into browsers for errors that it can't read. // this is the result of a script being pulled in from an external domain and CORS. globalOptions.ignoreErrors.push(/^Script error\.?$/); globalOptions.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/); // join regexp rules into one big rule globalOptions.ignoreErrors = joinRegExp(globalOptions.ignoreErrors); globalOptions.ignoreUrls = globalOptions.ignoreUrls.length ? joinRegExp(globalOptions.ignoreUrls) : false; globalOptions.whitelistUrls = globalOptions.whitelistUrls.length ? joinRegExp(globalOptions.whitelistUrls) : false; globalOptions.includePaths = joinRegExp(globalOptions.includePaths); globalOptions.maxBreadcrumbs = Math.max( 0, Math.min(globalOptions.maxBreadcrumbs || 100, 100) ); // default and hard limit is 100 var autoBreadcrumbDefaults = { xhr: true, console: true, dom: true, location: true, sentry: true }; var autoBreadcrumbs = globalOptions.autoBreadcrumbs; if ({}.toString.call(autoBreadcrumbs) === '[object Object]') { autoBreadcrumbs = objectMerge(autoBreadcrumbDefaults, autoBreadcrumbs); } else if (autoBreadcrumbs !== false) { autoBreadcrumbs = autoBreadcrumbDefaults; } globalOptions.autoBreadcrumbs = autoBreadcrumbs; var instrumentDefaults = { tryCatch: true }; var instrument = globalOptions.instrument; if ({}.toString.call(instrument) === '[object Object]') { instrument = objectMerge(instrumentDefaults, instrument); } else if (instrument !== false) { instrument = instrumentDefaults; } globalOptions.instrument = instrument; TraceKit.collectWindowErrors = !!globalOptions.collectWindowErrors; // return for chaining return self; }, /* * Installs a global window.onerror error handler * to capture and report uncaught exceptions. * At this point, install() is required to be called due * to the way TraceKit is set up. * * @return {Raven} */ install: function() { var self = this; if (self.isSetup() && !self._isRavenInstalled) { TraceKit.report.subscribe(function() { self._handleOnErrorStackInfo.apply(self, arguments); }); if (self._globalOptions.captureUnhandledRejections) { self._attachPromiseRejectionHandler(); } self._patchFunctionToString(); if (self._globalOptions.instrument && self._globalOptions.instrument.tryCatch) { self._instrumentTryCatch(); } if (self._globalOptions.autoBreadcrumbs) self._instrumentBreadcrumbs(); // Install all of the plugins self._drainPlugins(); self._isRavenInstalled = true; } Error.stackTraceLimit = self._globalOptions.stackTraceLimit; return this; }, /* * Set the DSN (can be called multiple time unlike config) * * @param {string} dsn The public Sentry DSN */ setDSN: function(dsn) { var self = this, uri = self._parseDSN(dsn), lastSlash = uri.path.lastIndexOf('/'), path = uri.path.substr(1, lastSlash); self._dsn = dsn; self._globalKey = uri.user; self._globalSecret = uri.pass && uri.pass.substr(1); self._globalProject = uri.path.substr(lastSlash + 1); self._globalServer = self._getGlobalServer(uri); self._globalEndpoint = self._globalServer + '/' + path + 'api/' + self._globalProject + '/store/'; // Reset backoff state since we may be pointing at a // new project/server this._resetBackoff(); }, /* * Wrap code within a context so Raven can capture errors * reliably across domains that is executed immediately. * * @param {object} options A specific set of options for this context [optional] * @param {function} func The callback to be immediately executed within the context * @param {array} args An array of arguments to be called with the callback [optional] */ context: function(options, func, args) { if (isFunction(options)) { args = func || []; func = options; options = undefined; } return this.wrap(options, func).apply(this, args); }, /* * Wrap code within a context and returns back a new function to be executed * * @param {object} options A specific set of options for this context [optional] * @param {function} func The function to be wrapped in a new context * @param {function} func A function to call before the try/catch wrapper [optional, private] * @return {function} The newly wrapped functions with a context */ wrap: function(options, func, _before) { var self = this; // 1 argument has been passed, and it's not a function // so just return it if (isUndefined(func) && !isFunction(options)) { return options; } // options is optional if (isFunction(options)) { func = options; options = undefined; } // At this point, we've passed along 2 arguments, and the second one // is not a function either, so we'll just return the second argument. if (!isFunction(func)) { return func; } // We don't wanna wrap it twice! try { if (func.__raven__) { return func; } // If this has already been wrapped in the past, return that if (func.__raven_wrapper__) { return func.__raven_wrapper__; } } catch (e) { // Just accessing custom props in some Selenium environments // can cause a "Permission denied" exception (see raven-js#495). // Bail on wrapping and return the function as-is (defers to window.onerror). return func; } function wrapped() { var args = [], i = arguments.length, deep = !options || (options && options.deep !== false); if (_before && isFunction(_before)) { _before.apply(this, arguments); } // Recursively wrap all of a function's arguments that are // functions themselves. while (i--) args[i] = deep ? self.wrap(options, arguments[i]) : arguments[i]; try { // Attempt to invoke user-land function // NOTE: If you are a Sentry user, and you are seeing this stack frame, it // means Raven caught an error invoking your application code. This is // expected behavior and NOT indicative of a bug with Raven.js. return func.apply(this, args); } catch (e) { self._ignoreNextOnError(); self.captureException(e, options); throw e; } } // copy over properties of the old function for (var property in func) { if (hasKey(func, property)) { wrapped[property] = func[property]; } } wrapped.prototype = func.prototype; func.__raven_wrapper__ = wrapped; // Signal that this function has been wrapped/filled already // for both debugging and to prevent it to being wrapped/filled twice wrapped.__raven__ = true; wrapped.__orig__ = func; return wrapped; }, /** * Uninstalls the global error handler. * * @return {Raven} */ uninstall: function() { TraceKit.report.uninstall(); this._detachPromiseRejectionHandler(); this._unpatchFunctionToString(); this._restoreBuiltIns(); this._restoreConsole(); Error.stackTraceLimit = this._originalErrorStackTraceLimit; this._isRavenInstalled = false; return this; }, /** * Callback used for `unhandledrejection` event * * @param {PromiseRejectionEvent} event An object containing * promise: the Promise that was rejected * reason: the value with which the Promise was rejected * @return void */ _promiseRejectionHandler: function(event) { this._logDebug('debug', 'Raven caught unhandled promise rejection:', event); this.captureException(event.reason, { extra: { unhandledPromiseRejection: true } }); }, /** * Installs the global promise rejection handler. * * @return {raven} */ _attachPromiseRejectionHandler: function() { this._promiseRejectionHandler = this._promiseRejectionHandler.bind(this); _window.addEventListener && _window.addEventListener('unhandledrejection', this._promiseRejectionHandler); return this; }, /** * Uninstalls the global promise rejection handler. * * @return {raven} */ _detachPromiseRejectionHandler: function() { _window.removeEventListener && _window.removeEventListener('unhandledrejection', this._promiseRejectionHandler); return this; }, /** * Manually capture an exception and send it over to Sentry * * @param {error} ex An exception to be logged * @param {object} options A specific set of options for this error [optional] * @return {Raven} */ captureException: function(ex, options) { options = objectMerge({trimHeadFrames: 0}, options ? options : {}); if (isErrorEvent(ex) && ex.error) { // If it is an ErrorEvent with `error` property, extract it to get actual Error ex = ex.error; } else if (isDOMError(ex) || isDOMException(ex)) { // If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers) // then we just extract the name and message, as they don't provide anything else // https://developer.mozilla.org/en-US/docs/Web/API/DOMError // https://developer.mozilla.org/en-US/docs/Web/API/DOMException var name = ex.name || (isDOMError(ex) ? 'DOMError' : 'DOMException'); var message = ex.message ? name + ': ' + ex.message : name; return this.captureMessage( message, objectMerge(options, { // neither DOMError or DOMException provide stack trace and we most likely wont get it this way as well // but it's barely any overhead so we may at least try stacktrace: true, trimHeadFrames: options.trimHeadFrames + 1 }) ); } else if (isError(ex)) { // we have a real Error object ex = ex; } else if (isPlainObject(ex)) { // If it is plain Object, serialize it manually and extract options // This will allow us to group events based on top-level keys // which is much better than creating new group when any key/value change options = this._getCaptureExceptionOptionsFromPlainObject(options, ex); ex = new Error(options.message); } else { // If none of previous checks were valid, then it means that // it's not a DOMError/DOMException // it's not a plain Object // it's not a valid ErrorEvent (one with an error property) // it's not an Error // So bail out and capture it as a simple message: return this.captureMessage( ex, objectMerge(options, { stacktrace: true, // if we fall back to captureMessage, default to attempting a new trace trimHeadFrames: options.trimHeadFrames + 1 }) ); } // Store the raw exception object for potential debugging and introspection this._lastCapturedException = ex; // TraceKit.report will re-raise any exception passed to it, // which means you have to wrap it in try/catch. Instead, we // can wrap it here and only re-raise if TraceKit.report // raises an exception different from the one we asked to // report on. try { var stack = TraceKit.computeStackTrace(ex); this._handleStackInfo(stack, options); } catch (ex1) { if (ex !== ex1) { throw ex1; } } return this; }, _getCaptureExceptionOptionsFromPlainObject: function(currentOptions, ex) { var exKeys = Object.keys(ex).sort(); var options = objectMerge(currentOptions, { message: 'Non-Error exception captured with keys: ' + serializeKeysForMessage(exKeys), fingerprint: [md5(exKeys)], extra: currentOptions.extra || {} }); options.extra.__serialized__ = serializeException(ex); return options; }, /* * Manually send a message to Sentry * * @param {string} msg A plain message to be captured in Sentry * @param {object} options A specific set of options for this message [optional] * @return {Raven} */ captureMessage: function(msg, options) { // config() automagically converts ignoreErrors from a list to a RegExp so we need to test for an // early call; we'll error on the side of logging anything called before configuration since it's // probably something you should see: if ( !!this._globalOptions.ignoreErrors.test && this._globalOptions.ignoreErrors.test(msg) ) { return; } options = options || {}; msg = msg + ''; // Make sure it's actually a string var data = objectMerge( { message: msg }, options ); var ex; // Generate a "synthetic" stack trace from this point. // NOTE: If you are a Sentry user, and you are seeing this stack frame, it is NOT indicative // of a bug with Raven.js. Sentry generates synthetic traces either by configuration, // or if it catches a thrown object without a "stack" property. try { throw new Error(msg); } catch (ex1) { ex = ex1; } // null exception name so `Error` isn't prefixed to msg ex.name = null; var stack = TraceKit.computeStackTrace(ex); // stack[0] is `throw new Error(msg)` call itself, we are interested in the frame that was just before that, stack[1] var initialCall = isArray(stack.stack) && stack.stack[1]; // if stack[1] is `Raven.captureException`, it means that someone passed a string to it and we redirected that call // to be handled by `captureMessage`, thus `initialCall` is the 3rd one, not 2nd // initialCall => captureException(string) => captureMessage(string) if (initialCall && initialCall.func === 'Raven.captureException') { initialCall = stack.stack[2]; } var fileurl = (initialCall && initialCall.url) || ''; if ( !!this._globalOptions.ignoreUrls.test && this._globalOptions.ignoreUrls.test(fileurl) ) { return; } if ( !!this._globalOptions.whitelistUrls.test && !this._globalOptions.whitelistUrls.test(fileurl) ) { return; } if (this._globalOptions.stacktrace || (options && options.stacktrace)) { // fingerprint on msg, not stack trace (legacy behavior, could be revisited) data.fingerprint = data.fingerprint == null ? msg : data.fingerprint; options = objectMerge( { trimHeadFrames: 0 }, options ); // Since we know this is a synthetic trace, the top frame (this function call) // MUST be from Raven.js, so mark it for trimming // We add to the trim counter so that callers can choose to trim extra frames, such // as utility functions. options.trimHeadFrames += 1; var frames = this._prepareFrames(stack, options); data.stacktrace = { // Sentry expects frames oldest to newest frames: frames.reverse() }; } // Make sure that fingerprint is always wrapped in an array if (data.fingerprint) { data.fingerprint = isArray(data.fingerprint) ? data.fingerprint : [data.fingerprint]; } // Fire away! this._send(data); return this; }, captureBreadcrumb: function(obj) { var crumb = objectMerge( { timestamp: now() / 1000 }, obj ); if (isFunction(this._globalOptions.breadcrumbCallback)) { var result = this._globalOptions.breadcrumbCallback(crumb); if (isObject(result) && !isEmptyObject(result)) { crumb = result; } else if (result === false) { return this; } } this._breadcrumbs.push(crumb); if (this._breadcrumbs.length > this._globalOptions.maxBreadcrumbs) { this._breadcrumbs.shift(); } return this; }, addPlugin: function(plugin /*arg1, arg2, ... argN*/) { var pluginArgs = [].slice.call(arguments, 1); this._plugins.push([plugin, pluginArgs]); if (this._isRavenInstalled) { this._drainPlugins(); } return this; }, /* * Set/clear a user to be sent along with the payload. * * @param {object} user An object representing user data [optional] * @return {Raven} */ setUserContext: function(user) { // Intentionally do not merge here since that's an unexpected behavior. this._globalContext.user = user; return this; }, /* * Merge extra attributes to be sent along with the payload. * * @param {object} extra An object representing extra data [optional] * @return {Raven} */ setExtraContext: function(extra) { this._mergeContext('extra', extra); return this; }, /* * Merge tags to be sent along with the payload. * * @param {object} tags An object representing tags [optional] * @return {Raven} */ setTagsContext: function(tags) { this._mergeContext('tags', tags); return this; }, /* * Clear all of the context. * * @return {Raven} */ clearContext: function() { this._globalContext = {}; return this; }, /* * Get a copy of the current context. This cannot be mutated. * * @return {object} copy of context */ getContext: function() { // lol javascript return JSON.parse(stringify(this._globalContext)); }, /* * Set environment of application * * @param {string} environment Typically something like 'production'. * @return {Raven} */ setEnvironment: function(environment) { this._globalOptions.environment = environment; return this; }, /* * Set release version of application * * @param {string} release Typically something like a git SHA to identify version * @return {Raven} */ setRelease: function(release) { this._globalOptions.release = release; return this; }, /* * Set the dataCallback option * * @param {function} callback The callback to run which allows the * data blob to be mutated before sending * @return {Raven} */ setDataCallback: function(callback) { var original = this._globalOptions.dataCallback; this._globalOptions.dataCallback = keepOriginalCallback(original, callback); return this; }, /* * Set the breadcrumbCallback option * * @param {function} callback The callback to run which allows filtering * or mutating breadcrumbs * @return {Raven} */ setBreadcrumbCallback: function(callback) { var original = this._globalOptions.breadcrumbCallback; this._globalOptions.breadcrumbCallback = keepOriginalCallback(original, callback); return this; }, /* * Set the shouldSendCallback option * * @param {function} callback The callback to run which allows * introspecting the blob before sending * @return {Raven} */ setShouldSendCallback: function(callback) { var original = this._globalOptions.shouldSendCallback; this._globalOptions.shouldSendCallback = keepOriginalCallback(original, callback); return this; }, /** * Override the default HTTP transport mechanism that transmits data * to the Sentry server. * * @param {function} transport Function invoked instead of the default * `makeRequest` handler. * * @return {Raven} */ setTransport: function(transport) { this._globalOptions.transport = transport; return this; }, /* * Get the latest raw exception that was captured by Raven. * * @return {error} */ lastException: function() { return this._lastCapturedException; }, /* * Get the last event id * * @return {string} */ lastEventId: function() { return this._lastEventId; }, /* * Determine if Raven is setup and ready to go. * * @return {boolean} */ isSetup: function() { if (!this._hasJSON) return false; // needs JSON support if (!this._globalServer) { if (!this.ravenNotConfiguredError) { this.ravenNotConfiguredError = true; this._logDebug('error', 'Error: Raven has not been configured.'); } return false; } return true; }, afterLoad: function() { // TODO: remove window dependence? // Attempt to initialize Raven on load var RavenConfig = _window.RavenConfig; if (RavenConfig) { this.config(RavenConfig.dsn, RavenConfig.config).install(); } }, showReportDialog: function(options) { if ( !_document // doesn't work without a document (React native) ) return; options = options || {}; var lastEventId = options.eventId || this.lastEventId(); if (!lastEventId) { throw new RavenConfigError('Missing eventId'); } var dsn = options.dsn || this._dsn; if (!dsn) { throw new RavenConfigError('Missing DSN'); } var encode = encodeURIComponent; var qs = ''; qs += '?eventId=' + encode(lastEventId); qs += '&dsn=' + encode(dsn); var user = options.user || this._globalContext.user; if (user) { if (user.name) qs += '&name=' + encode(user.name); if (user.email) qs += '&email=' + encode(user.email); } var globalServer = this._getGlobalServer(this._parseDSN(dsn)); var script = _document.createElement('script'); script.async = true; script.src = globalServer + '/api/embed/error-page/' + qs; (_document.head || _document.body).appendChild(script); }, /**** Private functions ****/ _ignoreNextOnError: function() { var self = this; this._ignoreOnError += 1; setTimeout(function() { // onerror should trigger before setTimeout self._ignoreOnError -= 1; }); }, _triggerEvent: function(eventType, options) { // NOTE: `event` is a native browser thing, so let's avoid conflicting wiht it var evt, key; if (!this._hasDocument) return; options = options || {}; eventType = 'raven' + eventType.substr(0, 1).toUpperCase() + eventType.substr(1); if (_document.createEvent) { evt = _document.createEvent('HTMLEvents'); evt.initEvent(eventType, true, true); } else { evt = _document.createEventObject(); evt.eventType = eventType; } for (key in options) if (hasKey(options, key)) { evt[key] = options[key]; } if (_document.createEvent) { // IE9 if standards _document.dispatchEvent(evt); } else { // IE8 regardless of Quirks or Standards // IE9 if quirks try { _document.fireEvent('on' + evt.eventType.toLowerCase(), evt); } catch (e) { // Do nothing } } }, /** * Wraps addEventListener to capture UI breadcrumbs * @param evtName the event name (e.g. "click") * @returns {Function} * @private */ _breadcrumbEventHandler: function(evtName) { var self = this; return function(evt) { // reset keypress timeout; e.g. triggering a 'click' after // a 'keypress' will reset the keypress debounce so that a new // set of keypresses can be recorded self._keypressTimeout = null; // It's possible this handler might trigger multiple times for the same // event (e.g. event propagation through node ancestors). Ignore if we've // already captured the event. if (self._lastCapturedEvent === evt) return; self._lastCapturedEvent = evt; // try/catch both: // - accessing evt.target (see getsentry/raven-js#838, #768) // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly // can throw an exception in some circumstances. var target; try { target = htmlTreeAsString(evt.target); } catch (e) { target = '<unknown>'; } self.captureBreadcrumb({ category: 'ui.' + evtName, // e.g. ui.click, ui.input message: target }); }; }, /** * Wraps addEventListener to capture keypress UI events * @returns {Function} * @private */ _keypressEventHandler: function() { var self = this, debounceDuration = 1000; // milliseconds // TODO: if somehow user switches keypress target before // debounce timeout is triggered, we will only capture // a single breadcrumb from the FIRST target (acceptable?) return function(evt) { var target; try { target = evt.target; } catch (e) { // just accessing event properties can throw an exception in some rare circumstances // see: https://github.com/getsentry/raven-js/issues/838 return; } var tagName = target && target.tagName; // only consider keypress events on actual input elements // this will disregard keypresses targeting body (e.g. tabbing // through elements, hotkeys, etc) if ( !tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable) ) return; // record first keypress in a series, but ignore subsequent // keypresses until debounce clears var timeout = self._keypressTimeout; if (!timeout) { self._breadcrumbEventHandler('input')(evt); } clearTimeout(timeout); self._keypressTimeout = setTimeout(function() { self._keypressTimeout = null; }, debounceDuration); }; }, /** * Captures a breadcrumb of type "navigation", normalizing input URLs * @param to the originating URL * @param from the target URL * @private */ _captureUrlChange: function(from, to) { var parsedLoc = parseUrl(this._location.href); var parsedTo = parseUrl(to); var parsedFrom = parseUrl(from); // because onpopstate only tells you the "new" (to) value of location.href, and // not the previous (from) value, we need to track the value of the current URL // state ourselves this._lastHref = to; // Use only the path component of the URL if the URL matches the current // document (almost all the time when using pushState) if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) to = parsedTo.relative; if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) from = parsedFrom.relative; this.captureBreadcrumb({ category: 'navigation', data: { to: to, from: from } }); }, _patchFunctionToString: function() { var self = this; self._originalFunctionToString = Function.prototype.toString; // eslint-disable-next-line no-extend-native Function.prototype.toString = function() { if (typeof this === 'function' && this.__raven__) { return self._originalFunctionToString.apply(this.__orig__, arguments); } return self._originalFunctionToString.apply(this, arguments); }; }, _unpatchFunctionToString: function() { if (this._originalFunctionToString) { // eslint-disable-next-line no-extend-native Function.prototype.toString = this._originalFunctionToString; } }, /** * Wrap timer functions and event targets to catch errors and provide * better metadata. */ _instrumentTryCatch: function() { var self = this; var wrappedBuiltIns = self._wrappedBuiltIns; function wrapTimeFn(orig) { return function(fn, t) { // preserve arity // Make a copy of the arguments to prevent deoptimization // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } var originalCallback = args[0]; if (isFunction(originalCallback)) { args[0] = self.wrap(originalCallback); } // IE < 9 doesn't support .call/.apply on setInterval/setTimeout, but it // also supports only two arguments and doesn't care what this is, so we // can just call the original function directly. if (orig.apply) { return orig.apply(this, args); } else { return orig(args[0], args[1]); } }; } var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs; function wrapEventTarget(global) { var proto = _window[global] && _window[global].prototype; if (proto && proto.hasOwnProperty && proto.hasOwnProperty('addEventListener')) { fill( proto, 'addEventListener', function(orig) { return function(evtName, fn, capture, secure) { // preserve arity try { if (fn && fn.handleEvent) { fn.handleEvent = self.wrap(fn.handleEvent); } } catch (err) { // can sometimes get 'Permission denied to access property "handle Event' } // More breadcrumb DOM capture ... done here and not in `_instrumentBreadcrumbs` // so that we don't have more than one wrapper function var before, clickHandler, keypressHandler; if ( autoBreadcrumbs && autoBreadcrumbs.dom && (global === 'EventTarget' || global === 'Node') ) { // NOTE: generating multiple handlers per addEventListener invocation, should // revisit and verify we can just use one (almost certainly) clickHandler = self._breadcrumbEventHandler('click'); keypressHandler = self._keypressEventHandler(); before = function(evt) { // need to intercept every DOM event in `before` argument, in case that // same wrapped method is re-used for different events (e.g. mousemove THEN click) // see #724 if (!evt) return; var eventType; try { eventType = evt.type; } catch (e) { // just accessing event properties can throw an exception in some rare circumstances // see: https://github.com/getsentry/raven-js/issues/838 return; } if (eventType === 'click') return clickHandler(evt); else if (eventType === 'keypress') return keypressHandler(evt); }; } return orig.call( this, evtName, self.wrap(fn, undefined, before), capture, secure ); }; }, wrappedBuiltIns ); fill( proto, 'removeEventListener', function(orig) { return function(evt, fn, capture, secure) { try { fn = fn && (fn.__raven_wrapper__ ? fn.__raven_wrapper__ : fn); } catch (e) { // ignore, accessing __raven_wrapper__ will throw in some Selenium environments } return orig.call(this, evt, fn, capture, secure); }; }, wrappedBuiltIns ); } } fill(_window, 'setTimeout', wrapTimeFn, wrappedBuiltIns); fill(_window, 'setInterval', wrapTimeFn, wrappedBuiltIns); if (_window.requestAnimationFrame) { fill( _window, 'requestAnimationFrame', function(orig) { return function(cb) { return orig(self.wrap(cb)); }; }, wrappedBuiltIns ); } // event targets borrowed from bugsnag-js: // https://github.com/bugsnag/bugsnag-js/blob/master/src/bugsnag.js#L666 var eventTargets = [ '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 (var i = 0; i < eventTargets.length; i++) { wrapEventTarget(eventTargets[i]); } }, /** * Instrument browser built-ins w/ breadcrumb capturing * - XMLHttpRequests * - DOM interactions (click/typing) * - window.location changes * - console * * Can be disabled or individually configured via the `autoBreadcrumbs` config option */ _instrumentBreadcrumbs: function() { var self = this; var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs; var wrappedBuiltIns = self._wrappedBuiltIns; function wrapProp(prop, xhr) { if (prop in xhr && isFunction(xhr[prop])) { fill(xhr, prop, function(orig) { return self.wrap(orig); }); // intentionally don't track filled methods on XHR instances } } if (autoBreadcrumbs.xhr && 'XMLHttpRequest' in _window) { var xhrproto = _window.XMLHttpRequest && _window.XMLHttpRequest.prototype; fill( xhrproto, 'open', function(origOpen) { return function(method, url) { // preserve arity // if Sentry key appears in URL, don't capture if (isString(url) && url.indexOf(self._globalKey) === -1) { this.__raven_xhr = { method: method, url: url, status_code: null }; } return origOpen.apply(this, arguments); }; }, wrappedBuiltIns ); fill( xhrproto, 'send', function(origSend) { return function() { // preserve arity var xhr = this; function onreadystatechangeHandler() { if (xhr.__raven_xhr && xhr.readyState === 4) { try { // touching statusCode in some platforms throws // an exception xhr.__raven_xhr.status_code = xhr.status; } catch (e) { /* do nothing */ } self.captureBreadcrumb({ type: 'http', category: 'xhr', data: xhr.__raven_xhr }); } } var props = ['onload', 'onerror', 'onprogress']; for (var j = 0; j < props.length; j++) { wrapProp(props[j], xhr); } if ('onreadystatechange' in xhr && isFunction(xhr.onreadystatechange)) { fill( xhr, 'onreadystatechange', function(orig) { return self.wrap(orig, undefined, onreadystatechangeHandler); } /* intentionally don't track this instrumentation */ ); } else { // if onreadystatechange wasn't actually set by the page on this xhr, we // are free to set our own and capture the breadcrumb xhr.onreadystatechange = onreadystatechangeHandler; } return origSend.apply(this, arguments); }; }, wrappedBuiltIns ); } if (autoBreadcrumbs.xhr && supportsFetch()) { fill( _window, 'fetch', function(origFetch) { return function() { // preserve arity // Make a copy of the arguments to prevent deoptimization // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } var fetchInput = args[0]; var method = 'GET'; var url; if (typeof fetchInput === 'string') { url = fetchInput; } else if ('Request' in _window && fetchInput instanceof _window.Request) { url = fetchInput.url; if (fetchInput.method) { method = fetchInput.method; } } else { url = '' + fetchInput; } // if Sentry key appears in URL, don't capture, as it's our own request if (url.indexOf(self._globalKey) !== -1) { return origFetch.apply(this, args); } if (args[1] && args[1].method) { method = args[1].method; } var fetchData = { method: method, url: url, status_code: null }; return origFetch .apply(this, args) .then(function(response) { fetchData.status_code = response.status; self.captureBreadcrumb({ type: 'http', category: 'fetch', data: fetchData }); return response; }) ['catch'](function(err) { // if there is an error performing the request self.captureBreadcrumb({ type: 'http', category: 'fetch', data: fetchData, level: 'error' }); throw err; }); }; }, wrappedBuiltIns ); } // Capture breadcrumbs from any click that is unhandled / bubbled up all the way // to the document. Do this before we instrument addEventListener. if (autoBreadcrumbs.dom && this._hasDocument) { if (_document.addEventListener) { _document.addEventListener('click', self._breadcrumbEventHandler('click'), false); _document.addEventListener('keypress', self._keypressEventHandler(), false); } else if (_document.attachEvent) { // IE8 Compatibility _document.attachEvent('onclick', self._breadcrumbEventHandler('click')); _document.attachEvent('onkeypress', self._keypressEventHandler()); } } // record navigation (URL) changes // NOTE: in Chrome App environment, touching history.pushState, *even inside // a try/catch block*, will cause Chrome to output an error to console.error // borrowed from: https://github.com/angular/angular.js/pull/13945/files var chrome = _window.chrome; var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; var hasPushAndReplaceState = !isChromePackagedApp && _window.history && _window.history.pushState && _window.history.replaceState; if (autoBreadcrumbs.location && hasPushAndReplaceState) { // TODO: remove onpopstate handler on uninstall() var oldOnPopState = _window.onpopstate; _window.onpopstate = function() { var currentHref = self._location.href; self._captureUrlChange(self._lastHref, currentHref); if (oldOnPopState) { return oldOnPopState.apply(this, arguments); } }; var historyReplacementFunction = function(origHistFunction) { // note history.pushState.length is 0; intentionally not declaring // params to preserve 0 arity return function(/* state, title, url */) { var url = arguments.length > 2 ? arguments[2] : undefined; // url argument is optional if (url) { // coerce to string (this is what pushState does) self._captureUrlChange(self._lastHref, url + ''); } return origHistFunction.apply(this, arguments); }; }; fill(_window.history, 'pushState', historyReplacementFunction, wrappedBuiltIns); fill(_window.history, 'replaceState', historyReplacementFunction, wrappedBuiltIns); } if (autoBreadcrumbs.console && 'console' in _window && console.log) { // console var consoleMethodCallback = function(msg, data) { self.captureBreadcrumb({ message: msg, level: data.level, category: 'console' }); }; each(['debug', 'info', 'warn', 'error', 'log'], function(_, level) { wrapConsoleMethod(console, level, consoleMethodCallback); }); } }, _restoreBuiltIns: function() { // restore any wrapped builtins var builtin; while (this._wrappedBuiltIns.length) { builtin = this._wrappedBuiltIns.shift(); var obj = builtin[0], name = builtin[1], orig = builtin[2]; obj[name] = orig; } }, _restoreConsole: function() { // eslint-disable-next-line guard-for-in for (var method in this._originalConsoleMethods) { this._originalConsole[method] = this._originalConsoleMethods[method]; } }, _drainPlugins: function() { var self = this; // FIX ME TODO each(this._plugins, function(_, plugin) { var installer = plugin[0]; var args = plugin[1]; installer.apply(self, [self].concat(args)); }); }, _parseDSN: function(str) { var m = dsnPattern.exec(str), dsn = {}, i = 7; try { while (i--) dsn[dsnKeys[i]] = m[i] || ''; } catch (e) { throw new RavenConfigError('Invalid DSN: ' + str); } if (dsn.pass && !this._globalOptions.allowSecretKey) { throw new RavenConfigError( 'Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key' ); } return dsn; }, _getGlobalServer: function(uri) { // assemble the endpoint from the uri pieces var globalServer = '//' + uri.host + (uri.port ? ':' + uri.port : ''); if (uri.protocol) { globalServer = uri.protocol + ':' + globalServer; } return globalServer; }, _handleOnErrorStackInfo: function() { // if we are intentionally ignoring errors via onerror, bail out if (!this._ignoreOnError) { this._handleStackInfo.apply(this, arguments); } }, _handleStackInfo: function(stackInfo, options) { var frames = this._prepareFrames(stackInfo, options); this._triggerEvent('handle', { stackInfo: stackInfo, options: options }); this._processException( stackInfo.name, stackInfo.message, stackInfo.url, stackInfo.lineno, frames, options ); }, _prepareFrames: function(stackInfo, options) { var self = this; var frames = []; if (stackInfo.stack && stackInfo.stack.length) { each(stackInfo.stack, function(i, stack) { var frame = self._normalizeFrame(stack, stackInfo.url); if (frame) { frames.push(frame); } }); // e.g. frames captured via captureMessage throw if (options && options.trimHeadFrames) { for (var j = 0; j < options.trimHeadFrames && j < frames.length; j++) { frames[j].in_app = false; } } } frames = frames.slice(0, this._globalOptions.stackTraceLimit); return frames; }, _normalizeFrame: function(frame, stackInfoUrl) { // normalize the frames data var normalized = { filename: frame.url, lineno: frame.line, colno: frame.column, function: frame.func || '?' }; // Case when we don't have any information about the error // E.g. throwing a string or raw object, instead of an `Error` in Firefox // Generating synthetic error doesn't add any value here // // We should probably somehow let a user know that they should fix their code if (!frame.url) { normalized.filename = stackInfoUrl; // fallback to whole stacks url from onerror handler } normalized.in_app = !// determine if an exception came from outside of our app // first we check the global includePaths list. ( (!!this._globalOptions.includePaths.test && !this._globalOptions.includePaths.test(normalized.filename)) || // Now we check for fun, if the function name is Raven or TraceKit /(Raven|TraceKit)\./.test(normalized['function']) || // finally, we do a last ditch effort and check for raven.min.js /raven\.(min\.)?js$/.test(normalized.filename) ); return normalized; }, _processException: function(type, message, fileurl, lineno, frames, options) { var prefixedMessage = (type ? type + ': ' : '') + (message || ''); if ( !!this._globalOptions.ignoreErrors.test && (this._globalOptions.ignoreErrors.test(message) || this._globalOptions.ignoreErrors.test(prefixedMessage)) ) { return; } var stacktrace; if (frames && frames.length) { fileurl = frames[0].filename || fileurl; // Sentry expects frames oldest to newest // and JS sends them as newest to oldest frames.reverse(); stacktrace = {frames: frames}; } else if (fileurl) { stacktrace = { frames: [ { filename: fileurl, lineno: lineno, in_app: true } ] }; } if ( !!this._globalOptions.ignoreUrls.test && this._globalOptions.ignoreUrls.test(fileurl) ) { return; } if ( !!this._globalOptions.whitelistUrls.test && !this._globalOptions.whitelistUrls.test(fileurl) ) { return; } var data = objectMerge( { // sentry.interfaces.Exception exception: { values: [ { type: type, value: message, stacktrace: stacktrace } ] }, transaction: fileurl }, options ); // Fire away! this._send(data); }, _trimPacket: function(data) { // For now, we only want to truncate the two different messages // but this could/should be expanded to just trim everything var max = this._globalOptions.maxMessageLength; if (data.message) { data.message = truncate(data.message, max); } if (data.exception) { var exception = data.exception.values[0]; exception.value = truncate(exception.value, max); } var request = data.request; if (request) { if (request.url) { request.url = truncate(request.url, this._globalOptions.maxUrlLength); } if (request.Referer) { request.Referer = truncate(request.Referer, this._globalOptions.maxUrlLength); } } if (data.breadcrumbs && data.breadcrumbs.values) this._trimBreadcrumbs(data.breadcrumbs); return data; }, /** * Truncate breadcrumb values (right now just URLs) */ _trimBreadcrumbs: function(breadcrumbs) { // known breadcrumb properties with urls // TODO: also consider arbitrary prop values that start with (https?)?:// var urlProps = ['to', 'from', 'url'], urlProp, crumb, data; for (var i = 0; i < breadcrumbs.values.length; ++i) { crumb = breadcrumbs.values[i]; if ( !crumb.hasOwnProperty('data') || !isObject(crumb.data) || objectFrozen(crumb.data) ) continue; data = objectMerge({}, crumb.data); for (var j = 0; j < urlProps.length; ++j) { urlProp = urlProps[j]; if (data.hasOwnProperty(urlProp) && data[urlProp]) { data[urlProp] = truncate(data[urlProp], this._globalOptions.maxUrlLength); } } breadcrumbs.values[i].data = data; } }, _getHttpData: function() { if (!this._hasNavigator && !this._hasDocument) return; var httpData = {}; if (this._hasNavigator && _navigator.userAgent) { httpData.headers = { 'User-Agent': _navigator.userAgent }; } // Check in `window` instead of `document`, as we may be in ServiceWorker environment if (_window.location && _window.location.href) { httpData.url = _window.location.href; } if (this._hasDocument && _document.referrer) { if (!httpData.headers) httpData.headers = {}; httpData.headers.Referer = _document.referrer; } return httpData; }, _resetBackoff: function() { this._backoffDuration = 0; this._backoffStart = null; }, _shouldBackoff: function() { return this._backoffDuration && now() - this._backoffStart < this._backoffDuration; }, /** * Returns true if the in-process data payload matches the signature * of the previously-sent data * * NOTE: This has to be done at this level because TraceKit can generate * data from window.onerror WITHOUT an exception object (IE8, IE9, * other old browsers). This can take the form of an "exception" * data object with a single frame (derived from the onerror args). */ _isRepeatData: function(current) { var last = this._lastData; if ( !last || current.message !== last.message || // defined for captureMessage current.transaction !== last.transaction // defined for captureException/onerror ) return false; // Stacktrace interface (i.e. from captureMessage) if (current.stacktrace || last.stacktrace) { return isSameStacktrace(current.stacktrace, last.stacktrace); } else if (current.exception || last.exception) { // Exception interface (i.e. from captureException/onerror) return isSameException(current.exception, last.exception); } return true; }, _setBackoffState: function(request) { // If we are already in a backoff state, don't change anything if (this._shouldBackoff()) { return; } var status = request.status; // 400 - project_id doesn't exist or some other fatal // 401 - invalid/revoked dsn // 429 - too many requests if (!(status === 400 || status === 401 || status === 429)) return; var retry; try { // If Retry-After is not in Access-Control-Expose-Headers, most // browsers will throw an exception trying to access it if (supportsFetch()) { retry = request.headers.get('Retry-After'); } else { retry = request.getResponseHeader('Retry-After'); } // Retry-After is returned in seconds retry = parseInt(retry, 10) * 1000; } catch (e) { /* eslint no-empty:0 */ } this._backoffDuration = retry ? // If Sentry server returned a Retry-After value, use it retry : // Otherwise, double the last backoff duration (starts at 1 sec) this._backoffDuration * 2 || 1000; this._backoffStart = now(); }, _send: function(data) { var globalOptions = this._globalOptions; var baseData = { project: this._globalProject, logger: globalOptions.logger, platform: 'javascript' }, httpData = this._getHttpData(); if (httpData) { baseData.request = httpData; } // HACK: delete `trimHeadFrames` to prevent from appearing in outbound payload if (data.trimHeadFrames) delete data.trimHeadFrames; data = objectMerge(baseData, data); // Merge in the tags and extra separately since objectMerge doesn't handle a deep merge data.tags = objectMerge(objectMerge({}, this._globalContext.tags), data.tags); data.extra = objectMerge(objectMerge({}, this._globalContext.extra), data.extra); // Send along our own collected metadata with extra data.extra['session:duration'] = now() - this._startTime; if (this._breadcrumbs && this._breadcrumbs.length > 0) { // intentionally make shallow copy so that additions // to breadcrumbs aren't accidentally sent in this request data.breadcrumbs = { values: [].slice.call(this._breadcrumbs, 0) }; } if (this._globalContext.user) { // sentry.interfaces.User data.user = this._globalContext.user; } // Include the environment if it's defined in globalOptions if (globalOptions.environment) data.environment = globalOptions.environment; // Include the release if it's defined in globalOptions if (globalOptions.release) data.release = globalOptions.release; // Include server_name if it's defined in globalOptions if (globalOptions.serverName) data.server_name = globalOptions.serverName; data = this._sanitizeData(data); // Cleanup empty properties before sending them to the server Object.keys(data).forEach(function(key) { if (data[key] == null || data[key] === '' || isEmptyObject(data[key])) { delete data[key]; } }); if (isFunction(globalOptions.dataCallback)) { data = globalOptions.dataCallback(data) || data; } // Why?????????? if (!data || isEmptyObject(data)) { return; } // Check if the request should be filtered or not if ( isFunction(globalOptions.shouldSendCallback) && !globalOptions.shouldSendCallback(data) ) { return; } // Backoff state: Sentry server previously responded w/ an error (e.g. 429 - too many requests), // so drop requests until "cool-off" period has elapsed. if (this._shouldBackoff()) { this._logDebug('warn', 'Raven dropped error due to backoff: ', data); return; } if (typeof globalOptions.sampleRate === 'number') { if (Math.random() < globalOptions.sampleRate) { this._sendProcessedPayload(data); } } else { this._sendProcessedPayload(data); } }, _sanitizeData: function(data) { return sanitize(data, this._globalOptions.sanitizeKeys); }, _getUuid: function() { return uuid4(); }, _sendProcessedPayload: function(data, callback) { var self = this; var globalOptions = this._globalOptions; if (!this.isSetup()) return; // Try and clean up the packet before sending by truncating long values data = this._trimPacket(data); // ideally duplicate error testing should occur *before* dataCallback/shouldSendCallback, // but this would require copying an un-truncated copy of the data packet, which can be // arbitrarily deep (extra_data) -- could be worthwhile? will revisit if (!this._globalOptions.allowDuplicates && this._isRepeatData(data)) { this._logDebug('warn', 'Raven dropped repeat event: ', data); return; } // Send along an event_id if not explicitly passed. // This event_id can be used to reference the error within Sentry itself. // Set lastEventId after we know the error should actually be sent this._lastEventId = data.event_id || (data.event_id = this._getUuid()); // Store outbound payload after trim this._lastData = data; this._logDebug('debug', 'Raven about to send:', data); var auth = { sentry_version: '7', sentry_client: 'raven-js/' + this.VERSION, sentry_key: this._globalKey }; if (this._globalSecret) { auth.sentry_secret = this._globalSecret; } var exception = data.exception && data.exception.values[0]; // only capture 'sentry' breadcrumb is autoBreadcrumbs is truthy if ( this._globalOptions.autoBreadcrumbs && this._globalOptions.autoBreadcrumbs.sentry ) { this.captureBreadcrumb({ category: 'sentry', message: exception ? (exception.type ? exception.type + ': ' : '') + exception.value : data.message, event_id: data.event_id, level: data.level || 'error' // presume error unless specified }); } var url = this._globalEndpoint; (globalOptions.transport || this._makeRequest).call(this, { url: url, auth: auth, data: data, options: globalOptions, onSuccess: function success() { self._resetBackoff(); self._triggerEvent('success', { data: data, src: url }); callback && callback(); }, onError: function failure(error) { self._logDebug('error', 'Raven transport failed to send: ', error); if (error.request) { self._setBackoffState(error.request); } self._triggerEvent('failure', { data: data, src: url }); error = error || new Error('Raven send failed (no additional details provided)'); callback && callback(error); } }); }, _makeRequest: function(opts) { // Auth is intentionally sent as part of query string (NOT as custom HTTP header) to avoid preflight CORS requests var url = opts.url + '?' + urlencode(opts.auth); var evaluatedHeaders = null; var evaluatedFetchParameters = {}; if (opts.options.headers) { evaluatedHeaders = this._evaluateHash(opts.options.headers); } if (opts.options.fetchParameters) { evaluatedFetchParameters = this._evaluateHash(opts.options.fetchParameters); } if (supportsFetch()) { evaluatedFetchParameters.body = stringify(opts.data); var defaultFetchOptions = objectMerge({}, this._fetchDefaults); var fetchOptions = objectMerge(defaultFetchOptions, evaluatedFetchParameters); if (evaluatedHeaders) { fetchOptions.headers = evaluatedHeaders; } return _window .fetch(url, fetchOptions) .then(function(response) { if (response.ok) { opts.onSuccess && opts.onSuccess(); } else { var error = new Error('Sentry error code: ' + response.status); // It's called request only to keep compatibility with XHR interface // and not add more redundant checks in setBackoffState method error.request = response; opts.onError && opts.onError(error); } }) ['catch'](function() { opts.onError && opts.onError(new Error('Sentry error code: network unavailable')); }); } var request = _window.XMLHttpRequest && new _window.XMLHttpRequest(); if (!request) return; // if browser doesn't support CORS (e.g. IE7), we are out of luck var hasCORS = 'withCredentials' in request || typeof XDomainRequest !== 'undefined'; if (!hasCORS) return; if ('withCredentials' in request) { request.onreadystatechange = function() { if (request.readyState !== 4) { return; } else if (request.status === 200) { opts.onSuccess && opts.onSuccess(); } else if (opts.onError) { var err = new Error('Sentry error code: ' + request.status); err.request = request; opts.onError(err); } }; } else { request = new XDomainRequest(); // xdomainrequest cannot go http -> https (or vice versa), // so always use protocol relative url = url.replace(/^https?:/, ''); // onreadystatechange not supported by XDomainRequest if (opts.onSuccess) { request.onload = opts.onSuccess; } if (opts.onError) { request.onerror = function() { var err = new Error('Sentry error code: XDomainRequest'); err.request = request; opts.onError(err); }; } } request.open('POST', url); if (evaluatedHeaders) { each(evaluatedHeaders, function(key, value) { request.setRequestHeader(key, value); }); } request.send(stringify(opts.data)); }, _evaluateHash: function(hash) { var evaluated = {}; for (var key in hash) { if (hash.hasOwnProperty(key)) { var value = hash[key]; evaluated[key] = typeof value === 'function' ? value() : value; } } return evaluated; }, _logDebug: function(level) { // We allow `Raven.debug` and `Raven.config(DSN, { debug: true })` to not make backward incompatible API change if ( this._originalConsoleMethods[level] && (this.debug || this._globalOptions.debug) ) { // In IE<10 console methods do not have their own 'apply' method Function.prototype.apply.call( this._originalConsoleMethods[level], this._originalConsole, [].slice.call(arguments, 1) ); } }, _mergeContext: function(key, context) { if (isUndefined(context)) { delete this._globalContext[key]; } else { this._globalContext[key] = objectMerge(this._globalContext[key] || {}, context); } } }; // Deprecations Raven.prototype.setUser = Raven.prototype.setUserContext; Raven.prototype.setReleaseContext = Raven.prototype.setRelease; module.exports = Raven; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"10":10,"11":11,"4":4,"5":5,"8":8,"9":9}],7:[function(_dereq_,module,exports){ (function (global){ /** * Enforces a single instance of the Raven client, and the * main entry point for Raven. If you are a consumer of the * Raven library, you SHOULD load this file (vs raven.js). **/ var RavenConstructor = _dereq_(6); // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785) var _window = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var _Raven = _window.Raven; var Raven = new RavenConstructor(); /* * Allow multiple versions of Raven to be installed. * Strip Raven from the global context and returns the instance. * * @return {Raven} */ Raven.noConflict = function() { _window.Raven = _Raven; return Raven; }; Raven.afterLoad(); module.exports = Raven; /** * DISCLAIMER: * * Expose `Client` constructor for cases where user want to track multiple "sub-applications" in one larger app. * It's not meant to be used by a wide audience, so pleaaase make sure that you know what you're doing before using it. * Accidentally calling `install` multiple times, may result in an unexpected behavior that's very hard to debug. * * It's called `Client' to be in-line with Raven Node implementation. * * HOWTO: * * import Raven from 'raven-js'; * * const someAppReporter = new Raven.Client(); * const someOtherAppReporter = new Raven.Client(); * * someAppReporter.config('__DSN__', { * ...config goes here * }); * * someOtherAppReporter.config('__OTHER_DSN__', { * ...config goes here * }); * * someAppReporter.captureMessage(...); * someAppReporter.captureException(...); * someAppReporter.captureBreadcrumb(...); * * someOtherAppReporter.captureMessage(...); * someOtherAppReporter.captureException(...); * someOtherAppReporter.captureBreadcrumb(...); * * It should "just work". */ module.exports.Client = RavenConstructor; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"6":6}],8:[function(_dereq_,module,exports){ (function (global){ var stringify = _dereq_(10); var _window = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function isObject(what) { return typeof what === 'object' && what !== null; } // Yanked from https://git.io/vS8DV re-used under CC0 // with some tiny modifications function isError(value) { switch (Object.prototype.toString.call(value)) { case '[object Error]': return true; case '[object Exception]': return true; case '[object DOMException]': return true; default: return value instanceof Error; } } function isErrorEvent(value) { return Object.prototype.toString.call(value) === '[object ErrorEvent]'; } function isDOMError(value) { return Object.prototype.toString.call(value) === '[object DOMError]'; } function isDOMException(value) { return Object.prototype.toString.call(value) === '[object DOMException]'; } function isUndefined(what) { return what === void 0; } function isFunction(what) { return typeof what === 'function'; } function isPlainObject(what) { return Object.prototype.toString.call(what) === '[object Object]'; } function isString(what) { return Object.prototype.toString.call(what) === '[object String]'; } function isArray(what) { return Object.prototype.toString.call(what) === '[object Array]'; } function isEmptyObject(what) { if (!isPlainObject(what)) return false; for (var _ in what) { if (what.hasOwnProperty(_)) { return false; } } return true; } function supportsErrorEvent() { try { new ErrorEvent(''); // eslint-disable-line no-new return true; } catch (e) { return false; } } function supportsDOMError() { try { new DOMError(''); // eslint-disable-line no-new return true; } catch (e) { return false; } } function supportsDOMException() { try { new DOMException(''); // eslint-disable-line no-new return true; } catch (e) { return false; } } function supportsFetch() { if (!('fetch' in _window)) return false; try { new Headers(); // eslint-disable-line no-new new Request(''); // eslint-disable-line no-new new Response(); // eslint-disable-line no-new return true; } catch (e) { return false; } } // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default // https://caniuse.com/#feat=referrer-policy // It doesn't. And it throw exception instead of ignoring this parameter... // REF: https://github.com/getsentry/raven-js/issues/1233 function supportsReferrerPolicy() { if (!supportsFetch()) return false; try { // eslint-disable-next-line no-new new Request('pickleRick', { referrerPolicy: 'origin' }); return true; } catch (e) { return false; } } function supportsPromiseRejectionEvent() { return typeof PromiseRejectionEvent === 'function'; } function wrappedCallback(callback) { function dataCallback(data, original) { var normalizedData = callback(data) || data; if (original) { return original(normalizedData) || normalizedData; } return normalizedData; } return dataCallback; } function each(obj, callback) { var i, j; if (isUndefined(obj.length)) { for (i in obj) { if (hasKey(obj, i)) { callback.call(null, i, obj[i]); } } } else { j = obj.length; if (j) { for (i = 0; i < j; i++) { callback.call(null, i, obj[i]); } } } } function objectMerge(obj1, obj2) { if (!obj2) { return obj1; } each(obj2, function(key, value) { obj1[key] = value; }); return obj1; } /** * This function is only used for react-native. * react-native freezes object that have already been sent over the * js bridge. We need this function in order to check if the object is frozen. * So it's ok that objectFrozen returns false if Object.isFrozen is not * supported because it's not relevant for other "platforms". See related issue: * https://github.com/getsentry/react-native-sentry/issues/57 */ function objectFrozen(obj) { if (!Object.isFrozen) { return false; } return Object.isFrozen(obj); } function truncate(str, max) { if (typeof max !== 'number') { throw new Error('2nd argument to `truncate` function should be a number'); } if (typeof str !== 'string' || max === 0) { return str; } return str.length <= max ? str : str.substr(0, max) + '\u2026'; } /** * hasKey, a better form of hasOwnProperty * Example: hasKey(MainHostObject, property) === true/false * * @param {Object} host object to check property * @param {string} key to check */ function hasKey(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function joinRegExp(patterns) { // Combine an array of regular expressions and strings into one large regexp // Be mad. var sources = [], i = 0, len = patterns.length, pattern; for (; i < len; i++) { pattern = patterns[i]; if (isString(pattern)) { // If it's a string, we need to escape it // Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1')); } else if (pattern && pattern.source) { // If it's a regexp already, we want to extract the source sources.push(pattern.source); } // Intentionally skip other cases } return new RegExp(sources.join('|'), 'i'); } function urlencode(o) { var pairs = []; each(o, function(key, value) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); return pairs.join('&'); } // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B // intentionally using regex and not <a/> href parsing trick because React Native and other // environments where DOM might not be available function parseUrl(url) { if (typeof url !== 'string') return {}; var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); // coerce to undefined values to empty string so we don't get 'undefined' var query = match[6] || ''; var fragment = match[8] || ''; return { protocol: match[2], host: match[4], path: match[5], relative: match[5] + query + fragment // everything minus origin }; } function uuid4() { var crypto = _window.crypto || _window.msCrypto; if (!isUndefined(crypto) && crypto.getRandomValues) { // Use window.crypto API if available // eslint-disable-next-line no-undef var arr = new Uint16Array(8); crypto.getRandomValues(arr); // set 4 in byte 7 arr[3] = (arr[3] & 0xfff) | 0x4000; // set 2 most significant bits of byte 9 to '10' arr[4] = (arr[4] & 0x3fff) | 0x8000; var pad = function(num) { var v = num.toString(16); while (v.length < 4) { v = '0' + v; } return v; }; return ( pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7]) ); } else { // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); } } /** * Given a child DOM element, returns a query-selector statement describing that * and its ancestors * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] * @param elem * @returns {string} */ function htmlTreeAsString(elem) { /* eslint no-extra-parens:0*/ var MAX_TRAVERSE_HEIGHT = 5, MAX_OUTPUT_LEN = 80, out = [], height = 0, len = 0, separator = ' > ', sepLength = separator.length, nextStr; while (elem && height++ < MAX_TRAVERSE_HEIGHT) { nextStr = htmlElementAsString(elem); // bail out if // - nextStr is the 'html' element // - the length of the string that would be created exceeds MAX_OUTPUT_LEN // (ignore this limit if we are on the first iteration) if ( nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN) ) { break; } out.push(nextStr); len += nextStr.length; elem = elem.parentNode; } return out.reverse().join(separator); } /** * Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @param HTMLElement * @returns {string} */ function htmlElementAsString(elem) { var out = [], className, classes, key, attr, i; if (!elem || !elem.tagName) { return ''; } out.push(elem.tagName.toLowerCase()); if (elem.id) { out.push('#' + elem.id); } className = elem.className; if (className && isString(className)) { classes = className.split(/\s+/); for (i = 0; i < classes.length; i++) { out.push('.' + classes[i]); } } var attrWhitelist = ['type', 'name', 'title', 'alt']; for (i = 0; i < attrWhitelist.length; i++) { key = attrWhitelist[i]; attr = elem.getAttribute(key); if (attr) { out.push('[' + key + '="' + attr + '"]'); } } return out.join(''); } /** * Returns true if either a OR b is truthy, but not both */ function isOnlyOneTruthy(a, b) { return !!(!!a ^ !!b); } /** * Returns true if both parameters are undefined */ function isBothUndefined(a, b) { return isUndefined(a) && isUndefined(b); } /** * Returns true if the two input exception interfaces have the same content */ function isSameException(ex1, ex2) { if (isOnlyOneTruthy(ex1, ex2)) return false; ex1 = ex1.values[0]; ex2 = ex2.values[0]; if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false; // in case both stacktraces are undefined, we can't decide so default to false if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false; return isSameStacktrace(ex1.stacktrace, ex2.stacktrace); } /** * Returns true if the two input stack trace interfaces have the same content */ function isSameStacktrace(stack1, stack2) { if (isOnlyOneTruthy(stack1, stack2)) return false; var frames1 = stack1.frames; var frames2 = stack2.frames; // Exit early if frame count differs if (frames1.length !== frames2.length) return false; // Iterate through every frame; bail out if anything differs var a, b; for (var i = 0; i < frames1.length; i++) { a = frames1[i]; b = frames2[i]; if ( a.filename !== b.filename || a.lineno !== b.lineno || a.colno !== b.colno || a['function'] !== b['function'] ) return false; } return true; } /** * Polyfill a method * @param obj object e.g. `document` * @param name method name present on object e.g. `addEventListener` * @param replacement replacement function * @param track {optional} record instrumentation to an array */ function fill(obj, name, replacement, track) { if (obj == null) return; var orig = obj[name]; obj[name] = replacement(orig); obj[name].__raven__ = true; obj[name].__orig__ = orig; if (track) { track.push([obj, name, orig]); } } /** * Join values in array * @param input array of values to be joined together * @param delimiter string to be placed in-between values * @returns {string} */ function safeJoin(input, delimiter) { if (!isArray(input)) return ''; var output = []; for (var i = 0; i < input.length; i++) { try { output.push(String(input[i])); } catch (e) { output.push('[value cannot be serialized]'); } } return output.join(delimiter); } // Default Node.js REPL depth var MAX_SERIALIZE_EXCEPTION_DEPTH = 3; // 50kB, as 100kB is max payload size, so half sounds reasonable var MAX_SERIALIZE_EXCEPTION_SIZE = 50 * 1024; var MAX_SERIALIZE_KEYS_LENGTH = 40; function utf8Length(value) { return ~-encodeURI(value).split(/%..|./).length; } function jsonSize(value) { return utf8Length(JSON.stringify(value)); } function serializeValue(value) { if (typeof value === 'string') { var maxLength = 40; return truncate(value, maxLength); } else if ( typeof value === 'number' || typeof value === 'boolean' || typeof value === 'undefined' ) { return value; } var type = Object.prototype.toString.call(value); // Node.js REPL notation if (type === '[object Object]') return '[Object]'; if (type === '[object Array]') return '[Array]'; if (type === '[object Function]') return value.name ? '[Function: ' + value.name + ']' : '[Function]'; return value; } function serializeObject(value, depth) { if (depth === 0) return serializeValue(value); if (isPlainObject(value)) { return Object.keys(value).reduce(function(acc, key) { acc[key] = serializeObject(value[key], depth - 1); return acc; }, {}); } else if (Array.isArray(value)) { return value.map(function(val) { return serializeObject(val, depth - 1); }); } return serializeValue(value); } function serializeException(ex, depth, maxSize) { if (!isPlainObject(ex)) return ex; depth = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_DEPTH : depth; maxSize = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_SIZE : maxSize; var serialized = serializeObject(ex, depth); if (jsonSize(stringify(serialized)) > maxSize) { return serializeException(ex, depth - 1); } return serialized; } function serializeKeysForMessage(keys, maxLength) { if (typeof keys === 'number' || typeof keys === 'string') return keys.toString(); if (!Array.isArray(keys)) return ''; keys = keys.filter(function(key) { return typeof key === 'string'; }); if (keys.length === 0) return '[object has no keys]'; maxLength = typeof maxLength !== 'number' ? MAX_SERIALIZE_KEYS_LENGTH : maxLength; if (keys[0].length >= maxLength) return keys[0]; for (var usedKeys = keys.length; usedKeys > 0; usedKeys--) { var serialized = keys.slice(0, usedKeys).join(', '); if (serialized.length > maxLength) continue; if (usedKeys === keys.length) return serialized; return serialized + '\u2026'; } return ''; } function sanitize(input, sanitizeKeys) { if (!isArray(sanitizeKeys) || (isArray(sanitizeKeys) && sanitizeKeys.length === 0)) return input; var sanitizeRegExp = joinRegExp(sanitizeKeys); var sanitizeMask = '********'; var safeInput; try { safeInput = JSON.parse(stringify(input)); } catch (o_O) { return input; } function sanitizeWorker(workerInput) { if (isArray(workerInput)) { return workerInput.map(function(val) { return sanitizeWorker(val); }); } if (isPlainObject(workerInput)) { return Object.keys(workerInput).reduce(function(acc, k) { if (sanitizeRegExp.test(k)) { acc[k] = sanitizeMask; } else { acc[k] = sanitizeWorker(workerInput[k]); } return acc; }, {}); } return workerInput; } return sanitizeWorker(safeInput); } module.exports = { isObject: isObject, isError: isError, isErrorEvent: isErrorEvent, isDOMError: isDOMError, isDOMException: isDOMException, isUndefined: isUndefined, isFunction: isFunction, isPlainObject: isPlainObject, isString: isString, isArray: isArray, isEmptyObject: isEmptyObject, supportsErrorEvent: supportsErrorEvent, supportsDOMError: supportsDOMError, supportsDOMException: supportsDOMException, supportsFetch: supportsFetch, supportsReferrerPolicy: supportsReferrerPolicy, supportsPromiseRejectionEvent: supportsPromiseRejectionEvent, wrappedCallback: wrappedCallback, each: each, objectMerge: objectMerge, truncate: truncate, objectFrozen: objectFrozen, hasKey: hasKey, joinRegExp: joinRegExp, urlencode: urlencode, uuid4: uuid4, htmlTreeAsString: htmlTreeAsString, htmlElementAsString: htmlElementAsString, isSameException: isSameException, isSameStacktrace: isSameStacktrace, parseUrl: parseUrl, fill: fill, safeJoin: safeJoin, serializeException: serializeException, serializeKeysForMessage: serializeKeysForMessage, sanitize: sanitize }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"10":10}],9:[function(_dereq_,module,exports){ (function (global){ var utils = _dereq_(8); /* TraceKit - Cross brower stack traces This was originally forked from github.com/occ/TraceKit, but has since been largely re-written and is now maintained as part of raven-js. Tests for this are in test/vendor. MIT license */ var TraceKit = { collectWindowErrors: true, debug: false }; // This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785) var _window = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; // global reference to slice var _slice = [].slice; var UNKNOWN_FUNCTION = '?'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/; function getLocationHref() { if (typeof document === 'undefined' || document.location == null) return ''; return document.location.href; } function getLocationOrigin() { if (typeof document === 'undefined' || document.location == null) return ''; // Oh dear IE10... if (!document.location.origin) { document.location.origin = document.location.protocol + '//' + document.location.hostname + (document.location.port ? ':' + document.location.port : ''); } return document.location.origin; } /** * TraceKit.report: cross-browser processing of unhandled exceptions * * Syntax: * TraceKit.report.subscribe(function(stackInfo) { ... }) * TraceKit.report.unsubscribe(function(stackInfo) { ... }) * TraceKit.report(exception) * try { ...code... } catch(ex) { TraceKit.report(ex); } * * Supports: * - Firefox: full stack trace with line numbers, plus column number * on top frame; column number is not guaranteed * - Opera: full stack trace with line and column numbers * - Chrome: full stack trace with line and column numbers * - Safari: line and column number for the top frame only; some frames * may be missing, and column number is not guaranteed * - IE: line and column number for the top frame only; some frames * may be missing, and column number is not guaranteed * * In theory, TraceKit should work on all of the following versions: * - IE5.5+ (only 8.0 tested) * - Firefox 0.9+ (only 3.5+ tested) * - Opera 7+ (only 10.50 tested; versions 9 and earlier may require * Exceptions Have Stacktrace to be enabled in opera:config) * - Safari 3+ (only 4+ tested) * - Chrome 1+ (only 5+ tested) * - Konqueror 3.5+ (untested) * * Requires TraceKit.computeStackTrace. * * Tries to catch all unhandled exceptions and report them to the * subscribed handlers. Please note that TraceKit.report will rethrow the * exception. This is REQUIRED in order to get a useful stack trace in IE. * If the exception does not reach the top of the browser, you will only * get a stack trace from the point where TraceKit.report was called. * * Handlers receive a stackInfo object as described in the * TraceKit.computeStackTrace docs. */ TraceKit.report = (function reportModuleWrapper() { var handlers = [], lastArgs = null, lastException = null, lastExceptionStack = null; /** * Add a crash handler. * @param {Function} handler */ function subscribe(handler) { installGlobalHandler(); handlers.push(handler); } /** * Remove a crash handler. * @param {Function} handler */ function unsubscribe(handler) { for (var i = handlers.length - 1; i >= 0; --i) { if (handlers[i] === handler) { handlers.splice(i, 1); } } } /** * Remove all crash handlers. */ function unsubscribeAll() { uninstallGlobalHandler(); handlers = []; } /** * Dispatch stack information to all handlers. * @param {Object.<string, *>} stack */ function notifyHandlers(stack, isWindowError) { var exception = null; if (isWindowError && !TraceKit.collectWindowErrors) { return; } for (var i in handlers) { if (handlers.hasOwnProperty(i)) { try { handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2))); } catch (inner) { exception = inner; } } } if (exception) { throw exception; } } var _oldOnerrorHandler, _onErrorHandlerInstalled; /** * Ensures all global unhandled exceptions are recorded. * Supported by Gecko and IE. * @param {string} msg Error message. * @param {string} url URL of script that generated the exception. * @param {(number|string)} lineNo The line number at which the error * occurred. * @param {?(number|string)} colNo The column number at which the error * occurred. * @param {?Error} ex The actual Error object. */ function traceKitWindowOnError(msg, url, lineNo, colNo, ex) { var stack = null; // If 'ex' is ErrorEvent, get real Error from inside var exception = utils.isErrorEvent(ex) ? ex.error : ex; // If 'msg' is ErrorEvent, get real message from inside var message = utils.isErrorEvent(msg) ? msg.message : msg; if (lastExceptionStack) { TraceKit.computeStackTrace.augmentStackTraceWithInitialElement( lastExceptionStack, url, lineNo, message ); processLastException(); } else if (exception && utils.isError(exception)) { // non-string `exception` arg; attempt to extract stack trace // New chrome and blink send along a real error object // Let's just report that like a normal error. // See: https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror stack = TraceKit.computeStackTrace(exception); notifyHandlers(stack, true); } else { var location = { url: url, line: lineNo, column: colNo }; var name = undefined; var groups; if ({}.toString.call(message) === '[object String]') { var groups = message.match(ERROR_TYPES_RE); if (groups) { name = groups[1]; message = groups[2]; } } location.func = UNKNOWN_FUNCTION; stack = { name: name, message: message, url: getLocationHref(), stack: [location] }; notifyHandlers(stack, true); } if (_oldOnerrorHandler) { return _oldOnerrorHandler.apply(this, arguments); } return false; } function installGlobalHandler() { if (_onErrorHandlerInstalled) { return; } _oldOnerrorHandler = _window.onerror; _window.onerror = traceKitWindowOnError; _onErrorHandlerInstalled = true; } function uninstallGlobalHandler() { if (!_onErrorHandlerInstalled) { return; } _window.onerror = _oldOnerrorHandler; _onErrorHandlerInstalled = false; _oldOnerrorHandler = undefined; } function processLastException() { var _lastExceptionStack = lastExceptionStack, _lastArgs = lastArgs; lastArgs = null; lastExceptionStack = null; lastException = null; notifyHandlers.apply(null, [_lastExceptionStack, false].concat(_lastArgs)); } /** * Reports an unhandled Error to TraceKit. * @param {Error} ex * @param {?boolean} rethrow If false, do not re-throw the exception. * Only used for window.onerror to not cause an infinite loop of * rethrowing. */ function report(ex, rethrow) { var args = _slice.call(arguments, 1); if (lastExceptionStack) { if (lastException === ex) { return; // already caught by an inner catch block, ignore } else { processLastException(); } } var stack = TraceKit.computeStackTrace(ex); lastExceptionStack = stack; lastException = ex; lastArgs = args; // If the stack trace is incomplete, wait for 2 seconds for // slow slow IE to see if onerror occurs or not before reporting // this exception; otherwise, we will end up with an incomplete // stack trace setTimeout(function() { if (lastException === ex) { processLastException(); } }, stack.incomplete ? 2000 : 0); if (rethrow !== false) { throw ex; // re-throw to propagate to the top level (and cause window.onerror) } } report.subscribe = subscribe; report.unsubscribe = unsubscribe; report.uninstall = unsubscribeAll; return report; })(); /** * TraceKit.computeStackTrace: cross-browser stack traces in JavaScript * * Syntax: * s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below) * Returns: * s.name - exception name * s.message - exception message * s.stack[i].url - JavaScript or HTML file URL * s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work) * s.stack[i].args - arguments passed to the function, if known * s.stack[i].line - line number, if known * s.stack[i].column - column number, if known * * Supports: * - Firefox: full stack trace with line numbers and unreliable column * number on top frame * - Opera 10: full stack trace with line and column numbers * - Opera 9-: full stack trace with line numbers * - Chrome: full stack trace with line and column numbers * - Safari: line and column number for the topmost stacktrace element * only * - IE: no line numbers whatsoever * * Tries to guess names of anonymous functions by looking for assignments * in the source code. In IE and Safari, we have to guess source file names * by searching for function bodies inside all page scripts. This will not * work for scripts that are loaded cross-domain. * Here be dragons: some function names may be guessed incorrectly, and * duplicate functions may be mismatched. * * TraceKit.computeStackTrace should only be used for tracing purposes. * Logging of unhandled exceptions should be done with TraceKit.report, * which builds on top of TraceKit.computeStackTrace and provides better * IE support by utilizing the window.onerror event to retrieve information * about the top of the stack. * * Note: In IE and Safari, no stack trace is recorded on the Error object, * so computeStackTrace instead walks its *own* chain of callers. * This means that: * * in Safari, some methods may be missing from the stack trace; * * in IE, the topmost function in the stack trace will always be the * caller of computeStackTrace. * * This is okay for tracing (because you are likely to be calling * computeStackTrace from the function you want to be the topmost element * of the stack trace anyway), but not okay for logging unhandled * exceptions (because your catch block will likely be far away from the * inner function that actually caused the exception). * */ TraceKit.computeStackTrace = (function computeStackTraceWrapper() { // Contents of Exception in various browsers. // // SAFARI: // ex.message = Can't find variable: qq // ex.line = 59 // ex.sourceId = 580238192 // ex.sourceURL = http://... // ex.expressionBeginOffset = 96 // ex.expressionCaretOffset = 98 // ex.expressionEndOffset = 98 // ex.name = ReferenceError // // FIREFOX: // ex.message = qq is not defined // ex.fileName = http://... // ex.lineNumber = 59 // ex.columnNumber = 69 // ex.stack = ...stack trace... (see the example below) // ex.name = ReferenceError // // CHROME: // ex.message = qq is not defined // ex.name = ReferenceError // ex.type = not_defined // ex.arguments = ['aa'] // ex.stack = ...stack trace... // // INTERNET EXPLORER: // ex.message = ... // ex.name = ReferenceError // // OPERA: // ex.message = ...message... (see the example below) // ex.name = ReferenceError // ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message) // ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace' /** * Computes stack trace information from the stack property. * Chrome and Gecko use this property. * @param {Error} ex * @return {?Object.<string, *>} Stack trace information. */ function computeStackTraceFromStackProp(ex) { if (typeof ex.stack === 'undefined' || !ex.stack) return; var chrome = /^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; var winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx(?:-web)|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; // NOTE: blob urls are now supposed to always have an origin, therefore it's format // which is `blob:http://url/path/with-some-uuid`, is matched by `blob.*?:\/` as well var gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; // Used to additionally parse URL/line/column from eval frames var geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; var chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/; var lines = ex.stack.split('\n'); var stack = []; var submatch; var parts; var element; var reference = /^(.*) is undefined$/.exec(ex.message); for (var i = 0, j = lines.length; i < j; ++i) { if ((parts = chrome.exec(lines[i]))) { var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line if (isEval && (submatch = chromeEval.exec(parts[2]))) { // throw out eval line/column and use top-most line/column number parts[2] = submatch[1]; // url parts[3] = submatch[2]; // line parts[4] = submatch[3]; // column } element = { url: !isNative ? parts[2] : null, func: parts[1] || UNKNOWN_FUNCTION, args: isNative ? [parts[2]] : [], line: parts[3] ? +parts[3] : null, column: parts[4] ? +parts[4] : null }; } else if ((parts = winjs.exec(lines[i]))) { element = { url: parts[2], func: parts[1] || UNKNOWN_FUNCTION, args: [], line: +parts[3], column: parts[4] ? +parts[4] : null }; } else if ((parts = gecko.exec(lines[i]))) { var isEval = parts[3] && parts[3].indexOf(' > eval') > -1; if (isEval && (submatch = geckoEval.exec(parts[3]))) { // throw out eval line/column and use top-most line number parts[3] = submatch[1]; parts[4] = submatch[2]; parts[5] = null; // no column when eval } else if (i === 0 && !parts[5] && typeof ex.columnNumber !== 'undefined') { // FireFox uses this awesome columnNumber property for its top frame // Also note, Firefox's column number is 0-based and everything else expects 1-based, // so adding 1 // NOTE: this hack doesn't work if top-most frame is eval stack[0].column = ex.columnNumber + 1; } element = { url: parts[3], func: parts[1] || UNKNOWN_FUNCTION, args: parts[2] ? parts[2].split(',') : [], line: parts[4] ? +parts[4] : null, column: parts[5] ? +parts[5] : null }; } else { continue; } if (!element.func && element.line) { element.func = UNKNOWN_FUNCTION; } if (element.url && element.url.substr(0, 5) === 'blob:') { // Special case for handling JavaScript loaded into a blob. // We use a synchronous AJAX request here as a blob is already in // memory - it's not making a network request. This will generate a warning // in the browser console, but there has already been an error so that's not // that much of an issue. var xhr = new XMLHttpRequest(); xhr.open('GET', element.url, false); xhr.send(null); // If we failed to download the source, skip this patch if (xhr.status === 200) { var source = xhr.responseText || ''; // We trim the source down to the last 300 characters as sourceMappingURL is always at the end of the file. // Why 300? To be in line with: https://github.com/getsentry/sentry/blob/4af29e8f2350e20c28a6933354e4f42437b4ba42/src/sentry/lang/javascript/processor.py#L164-L175 source = source.slice(-300); // Now we dig out the source map URL var sourceMaps = source.match(/\/\/# sourceMappingURL=(.*)$/); // If we don't find a source map comment or we find more than one, continue on to the next element. if (sourceMaps) { var sourceMapAddress = sourceMaps[1]; // Now we check to see if it's a relative URL. // If it is, convert it to an absolute one. if (sourceMapAddress.charAt(0) === '~') { sourceMapAddress = getLocationOrigin() + sourceMapAddress.slice(1); } // Now we strip the '.map' off of the end of the URL and update the // element so that Sentry can match the map to the blob. element.url = sourceMapAddress.slice(0, -4); } } } stack.push(element); } if (!stack.length) { return null; } return { name: ex.name, message: ex.message, url: getLocationHref(), stack: stack }; } /** * Adds information about the first frame to incomplete stack traces. * Safari and IE require this to get complete data on the first frame. * @param {Object.<string, *>} stackInfo Stack trace information from * one of the compute* methods. * @param {string} url The URL of the script that caused an error. * @param {(number|string)} lineNo The line number of the script that * caused an error. * @param {string=} message The error generated by the browser, which * hopefully contains the name of the object that caused the error. * @return {boolean} Whether or not the stack information was * augmented. */ function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) { var initial = { url: url, line: lineNo }; if (initial.url && initial.line) { stackInfo.incomplete = false; if (!initial.func) { initial.func = UNKNOWN_FUNCTION; } if (stackInfo.stack.length > 0) { if (stackInfo.stack[0].url === initial.url) { if (stackInfo.stack[0].line === initial.line) { return false; // already in stack trace } else if ( !stackInfo.stack[0].line && stackInfo.stack[0].func === initial.func ) { stackInfo.stack[0].line = initial.line; return false; } } } stackInfo.stack.unshift(initial); stackInfo.partial = true; return true; } else { stackInfo.incomplete = true; } return false; } /** * Computes stack trace information by walking the arguments.caller * chain at the time the exception occurred. This will cause earlier * frames to be missed but is the only way to get any stack trace in * Safari and IE. The top frame is restored by * {@link augmentStackTraceWithInitialElement}. * @param {Error} ex * @return {?Object.<string, *>} Stack trace information. */ function computeStackTraceByWalkingCallerChain(ex, depth) { var functionName = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i, stack = [], funcs = {}, recursion = false, parts, item, source; for ( var curr = computeStackTraceByWalkingCallerChain.caller; curr && !recursion; curr = curr.caller ) { if (curr === computeStackTrace || curr === TraceKit.report) { // console.log('skipping internal function'); continue; } item = { url: null, func: UNKNOWN_FUNCTION, line: null, column: null }; if (curr.name) { item.func = curr.name; } else if ((parts = functionName.exec(curr.toString()))) { item.func = parts[1]; } if (typeof item.func === 'undefined') { try { item.func = parts.input.substring(0, parts.input.indexOf('{')); } catch (e) {} } if (funcs['' + curr]) { recursion = true; } else { funcs['' + curr] = true; } stack.push(item); } if (depth) { // console.log('depth is ' + depth); // console.log('stack is ' + stack.length); stack.splice(0, depth); } var result = { name: ex.name, message: ex.message, url: getLocationHref(), stack: stack }; augmentStackTraceWithInitialElement( result, ex.sourceURL || ex.fileName, ex.line || ex.lineNumber, ex.message || ex.description ); return result; } /** * Computes a stack trace for an exception. * @param {Error} ex * @param {(string|number)=} depth */ function computeStackTrace(ex, depth) { var stack = null; depth = depth == null ? 0 : +depth; try { stack = computeStackTraceFromStackProp(ex); if (stack) { return stack; } } catch (e) { if (TraceKit.debug) { throw e; } } try { stack = computeStackTraceByWalkingCallerChain(ex, depth + 1); if (stack) { return stack; } } catch (e) { if (TraceKit.debug) { throw e; } } return { name: ex.name, message: ex.message, url: getLocationHref() }; } computeStackTrace.augmentStackTraceWithInitialElement = augmentStackTraceWithInitialElement; computeStackTrace.computeStackTraceFromStackProp = computeStackTraceFromStackProp; return computeStackTrace; })(); module.exports = TraceKit; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"8":8}],10:[function(_dereq_,module,exports){ /* json-stringify-safe Like JSON.stringify, but doesn't throw on circular references. Originally forked from https://github.com/isaacs/json-stringify-safe version 5.0.1 on 3/8/2017 and modified to handle Errors serialization and IE8 compatibility. Tests for this are in test/vendor. ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE */ exports = module.exports = stringify; exports.getSerialize = serializer; function indexOf(haystack, needle) { for (var i = 0; i < haystack.length; ++i) { if (haystack[i] === needle) return i; } return -1; } function stringify(obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces); } // https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106 function stringifyError(value) { var err = { // These properties are implemented as magical getters and don't show up in for in stack: value.stack, message: value.message, name: value.name }; for (var i in value) { if (Object.prototype.hasOwnProperty.call(value, i)) { err[i] = value[i]; } } return err; } function serializer(replacer, cycleReplacer) { var stack = []; var keys = []; if (cycleReplacer == null) { cycleReplacer = function(key, value) { if (stack[0] === value) { return '[Circular ~]'; } return '[Circular ~.' + keys.slice(0, indexOf(stack, value)).join('.') + ']'; }; } return function(key, value) { if (stack.length > 0) { var thisPos = indexOf(stack, this); ~thisPos ? stack.splice(thisPos + 1) : stack.push(this); ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key); if (~indexOf(stack, value)) { value = cycleReplacer.call(this, key, value); } } else { stack.push(value); } return replacer == null ? value instanceof Error ? stringifyError(value) : value : replacer.call(this, key, value); }; } },{}],11:[function(_dereq_,module,exports){ /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * https://opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safeAdd(x, y) { var lsw = (x & 0xffff) + (y & 0xffff); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xffff); } /* * Bitwise rotate a 32-bit number to the left. */ function bitRotateLeft(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn((b & c) | (~b & d), a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn((b & d) | (c & ~d), a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | ~d), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binlMD5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i; var olda; var oldb; var oldc; var oldd; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5ff(a, b, c, d, x[i], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i; var output = ''; var length32 = input.length * 32; for (i = 0; i < length32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xff); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i; var output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } var length8 = input.length * 8; for (i = 0; i < length8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstrMD5(s) { return binl2rstr(binlMD5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstrHMACMD5(key, data) { var i; var bkey = rstr2binl(key); var ipad = []; var opad = []; var hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binlMD5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5c5c5c5c; } hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binlMD5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hexTab = '0123456789abcdef'; var output = ''; var x; var i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f); } return output; } /* * Encode a string as utf-8 */ function str2rstrUTF8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function rawMD5(s) { return rstrMD5(str2rstrUTF8(s)); } function hexMD5(s) { return rstr2hex(rawMD5(s)); } function rawHMACMD5(k, d) { return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d)); } function hexHMACMD5(k, d) { return rstr2hex(rawHMACMD5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hexMD5(string); } return rawMD5(string); } if (!raw) { return hexHMACMD5(key, string); } return rawHMACMD5(key, string); } module.exports = md5; },{}]},{},[7,1,2,3])(7) });
ajax/libs/rxjs/2.3.8/rx.compat.js
ThibWeb/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; }; // 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 = { done: true, value: undefined }; /** `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; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } 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; 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; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ 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)); }); }; // Collection polyfills 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 var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (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) { if (index === undefined) { 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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * 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 BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; 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) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } 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; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * 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 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 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) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { 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; (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 setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * 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 = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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 (exception) { var notification = new Notification('E'); notification.exception = exception; 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 enumerableFor = Enumerable.forEach = 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. * * @param observer Observer object. * @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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @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. * * @memberOf AbstractObserver * @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 (exception) { this._onError(exception); }; /** * 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 (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ 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. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; 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 new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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 Error('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; }, function (err) { reject(err); }, function () { if (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. */ 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 = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = 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(); } }); }); }; /** * 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; }); }; /** * 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); }; /** * 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 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @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 = 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. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @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(); if (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.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. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).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. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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 if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (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), function () { self(); }, function () { 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 if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * 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. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @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) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.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) { try { if (!hasValue) { hasValue = true; } 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 () { if (!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); if (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. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, 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); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } 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)); }); }; /** * 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 (exception) { observer.onError(exception); 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} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, 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 observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.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; } } if (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 Error(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) { remaining--; observer.onNext(x); if (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. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(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 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 (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(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; }); }; 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)); /** @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 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 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 = []; } }, /** * 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) { 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));
src/Event/components/EventComments.js
jirkae/hobby_hub
import React, { Component } from 'react'; import { connect } from "react-redux"; import moment from 'moment'; import { Row, Col } from 'react-bootstrap'; import { addComment } from './../actions/eventActionCreators'; class EventComments extends Component { constructor(props) { super(props); this.state = { newComment: '' }; this.handleAddComment = this.handleAddComment.bind(this); } handleAddComment() { const { addComment, event } = this.props; if (this.state.newComment !== '') { addComment(event.id, this.state.newComment); this.setState({ newComment: '' }); } } render() { const {comments} = this.props; return ( <Row> <Col xs={12}> <h4>Komentáře</h4> <div className="form-group"> <textarea rows="4" className="form-control" value={this.state.newComment} onChange={(e) => { this.setState({ newComment: e.target.value }); } }></textarea> <button className="btn btn-success btn-xs" onClick={this.handleAddComment}>Přidat komentář</button> </div> {comments && comments.length > 0 ? comments.map((item) => ( <div key={item.id} className="media"> <div className="media-body"> <div> <strong>{item.user.firstName} {item.user.lastName}</strong> {moment(item.dateCreated).fromNow()} </div> {item.text} </div> </div> )) : "K této akci nebyly přidány žádné komentáře. Buďte první!"} </Col> </Row> ); } } const mapStateToProps = (store) => { return { user: store.userReducer.user } }; EventComments = connect( mapStateToProps, { addComment } )(EventComments); export default EventComments;
app/javascript/mastodon/features/standalone/compose/index.js
Chronister/mastodon
import React from 'react'; import ComposeFormContainer from '../../compose/containers/compose_form_container'; import NotificationsContainer from '../../ui/containers/notifications_container'; import LoadingBarContainer from '../../ui/containers/loading_bar_container'; import ModalContainer from '../../ui/containers/modal_container'; export default class Compose extends React.PureComponent { render () { return ( <div> <ComposeFormContainer /> <NotificationsContainer /> <ModalContainer /> <LoadingBarContainer className='loading-bar' /> </div> ); } }
front_end/src/pages/Errors/Error404Page.js
oyiptong/splice
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { updateDocTitle } from 'actions/App/AppActions'; class Error404Page extends Component { componentDidMount() { updateDocTitle('Page Not Found'); } render() { return ( <div className="module"> <div className="module-header"> Page Not Found </div> <div className="module-body"> <div className="row"> <div className="col-xs-12"> <p>The page you are looking for does not exist.</p> </div> </div> </div> </div> ); } } Error404Page.propTypes = {}; // Which props do we want to inject, given the global state? function select(state) { return { Account: state.Account, App: state.App }; } // Wrap the component to inject dispatch and state into it export default connect(select)(Error404Page);
modules/__tests__/transitionHooks-test.js
chf2/react-router
/*eslint-env mocha */ /*eslint react/prop-types: 0*/ import expect, { spyOn } from 'expect' import React from 'react' import createHistory from 'history/lib/createMemoryHistory' import execSteps from './execSteps' import Router from '../Router' describe('When a router enters a branch', function () { let node, Dashboard, NewsFeed, Inbox, DashboardRoute, NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute, routes beforeEach(function () { node = document.createElement('div') Dashboard = React.createClass({ render() { return ( <div className="Dashboard"> <h1>The Dashboard</h1> {this.props.children} </div> ) } }) NewsFeed = React.createClass({ render() { return <div>News</div> } }) Inbox = React.createClass({ render() { return <div>Inbox</div> } }) NewsFeedRoute = { path: 'news', component: NewsFeed, onEnter(nextState, replaceState) { expect(this).toBe(NewsFeedRoute) expect(nextState.routes).toContain(NewsFeedRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(NewsFeedRoute) } } InboxRoute = { path: 'inbox', component: Inbox, onEnter(nextState, replaceState) { expect(this).toBe(InboxRoute) expect(nextState.routes).toContain(InboxRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(InboxRoute) } } RedirectToInboxRoute = { path: 'redirect-to-inbox', onEnter(nextState, replaceState) { expect(this).toBe(RedirectToInboxRoute) expect(nextState.routes).toContain(RedirectToInboxRoute) expect(replaceState).toBeA('function') replaceState(null, '/inbox') }, onLeave() { expect(this).toBe(RedirectToInboxRoute) } } MessageRoute = { path: 'messages/:messageID', onEnter(nextState, replaceState) { expect(this).toBe(MessageRoute) expect(nextState.routes).toContain(MessageRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(MessageRoute) } } DashboardRoute = { component: Dashboard, onEnter(nextState, replaceState) { expect(this).toBe(DashboardRoute) expect(nextState.routes).toContain(DashboardRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(DashboardRoute) }, childRoutes: [ NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute ] } routes = [ DashboardRoute ] }) afterEach(function () { React.unmountComponentAtNode(node) }) it('calls the onEnter hooks of all routes in that branch', function (done) { const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough() const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough() React.render(<Router history={createHistory('/news')} routes={routes}/>, node, function () { expect(dashboardRouteEnterSpy).toHaveBeenCalled() expect(newsFeedRouteEnterSpy).toHaveBeenCalled() done() }) }) describe('and one of the transition hooks navigates to another route', function () { it('immediately transitions to the new route', function (done) { const redirectRouteEnterSpy = spyOn(RedirectToInboxRoute, 'onEnter').andCallThrough() const redirectRouteLeaveSpy = spyOn(RedirectToInboxRoute, 'onLeave').andCallThrough() const inboxEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough() React.render(<Router history={createHistory('/redirect-to-inbox')} routes={routes}/>, node, function () { expect(this.state.location.pathname).toEqual('/inbox') expect(redirectRouteEnterSpy).toHaveBeenCalled() expect(redirectRouteLeaveSpy.calls.length).toEqual(0) expect(inboxEnterSpy).toHaveBeenCalled() done() }) }) }) describe('and then navigates to another branch', function () { it('calls the onLeave hooks of all routes in the previous branch that are not in the next branch', function (done) { const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough() const inboxRouteEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough() const inboxRouteLeaveSpy = spyOn(InboxRoute, 'onLeave').andCallThrough() const steps = [ function () { expect(inboxRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called') this.history.pushState(null, '/news') }, function () { expect(inboxRouteLeaveSpy).toHaveBeenCalled('InboxRoute.onLeave was not called') expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called') } ] const execNextStep = execSteps(steps, done) React.render( <Router history={createHistory('/inbox')} routes={routes} onUpdate={execNextStep} />, node, execNextStep) }) }) describe('and then navigates to the same branch, but with different params', function () { it('calls the onLeave and onEnter hooks of all routes whose params have changed', function (done) { const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough() const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough() const messageRouteLeaveSpy = spyOn(MessageRoute, 'onLeave').andCallThrough() const messageRouteEnterSpy = spyOn(MessageRoute, 'onEnter').andCallThrough() const steps = [ function () { expect(dashboardRouteEnterSpy).toHaveBeenCalled('DashboardRoute.onEnter was not called') expect(messageRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called') this.history.pushState(null, '/messages/456') }, function () { expect(messageRouteLeaveSpy).toHaveBeenCalled('MessageRoute.onLeave was not called') expect(messageRouteEnterSpy).toHaveBeenCalled('MessageRoute.onEnter was not called') expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called') } ] const execNextStep = execSteps(steps, done) React.render( <Router history={createHistory('/messages/123')} routes={routes} onUpdate={execNextStep} />, node, execNextStep) }) }) })
examples/star-wars/src/components/StarWarsApp.js
denvned/isomorphic-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 React from 'react'; import Relay from 'react-relay'; import StarWarsShip from './StarWarsShip'; class StarWarsApp extends React.Component { render() { var {factions} = this.props; return ( <ol> {factions.map(faction => ( <li key={faction.id}> <h1>{faction.name}</h1> <ol> {faction.ships.edges.map(edge => ( <li key={edge.node.id}><StarWarsShip ship={edge.node} /></li> ))} </ol> </li> ))} </ol> ); } } export default Relay.createContainer(StarWarsApp, { fragments: { factions: () => Relay.QL` fragment on Faction @relay(plural: true) { id, name, ships(first: 10) { edges { node { id, ${StarWarsShip.getFragment('ship')} } } } } `, }, });
src/components/common/AsyncComponent.js
securely-app/web
import React, { Component } from 'react'; export default function asyncComponent(importComponent) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { component: null }; } async componentDidMount() { const { default: component } = await importComponent(); // eslint-disable-next-line react/no-did-mount-set-state this.setState({ component }); } render() { const ImportedComponent = this.state.component; return ImportedComponent ? <ImportedComponent {...this.props} /> : null; } } return AsyncComponent; }
src/components/file-input.js
tylerlee/former
import BasicInput from 'components/basic-input'; import Cursors from 'cursors'; import React from 'react'; export default React.createClass({ mixins: [Cursors], render: function () { return <BasicInput {...this.props} type='file' />; } });
ajax/libs/inferno-redux/1.0.0-beta18/inferno-redux.js
froala/cdnjs
/*! * inferno-redux v1.0.0-beta18 * (c) 2016 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component'), require('./inferno-create-element')) : typeof define === 'function' && define.amd ? define(['inferno-component', 'inferno-create-element'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Redux = factory(global.Inferno.Component,global.Inferno.createElement)); }(this, (function (Component,createElement) { 'use strict'; Component = 'default' in Component ? Component['default'] : Component; createElement = 'default' in createElement ? createElement['default'] : createElement; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Built-in value references. */ var Symbol = root.Symbol; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$1.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto$1.toString; /** Built-in value references. */ var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$1.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$2.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } value = Object(value); return (symToStringTag && symToStringTag in value) ? getRawTag(value) : objectToString(value); } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); /** * 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 != null && typeof value == 'object'; } /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype; var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * 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) || baseGetTag(value) != objectTag) { 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; } 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; } /* global window */ var root$2; if (typeof self !== 'undefined') { root$2 = self; } else if (typeof window !== 'undefined') { root$2 = window; } else if (typeof global !== 'undefined') { root$2 = global; } else if (typeof module !== 'undefined') { root$2 = module; } else { root$2 = Function('return this')(); } var result = symbolObservablePonyfill(root$2); /** * 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 = { 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} [preloadedState] 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, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; 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 state 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 (!isPlainObject(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 }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[result] = function () { return this; }, _ref; } // 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 _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[result] = observable, _ref2; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning$1(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 if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState 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 (!isPlainObject(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) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); 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: 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 ' + 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.'); } }); } 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; } /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { var arguments$1 = arguments; for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments$1[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } var _extends = Object.assign || function (target) { var arguments$1 = arguments; for (var i = 1; i < arguments.length; i++) { var source = arguments$1[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* * 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 (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { warning$1('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.'); } /** * 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 if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); } catch (e) { } /* eslint-enable no-empty */ } 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; } function wrapActionCreators(actionCreators) { return function (dispatch) { return bindActionCreators(actionCreators, dispatch); }; } var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; function toArray(children) { return isArray(children) ? children : (children ? [children] : children); } // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isNull(obj) { return obj === null; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var didWarnAboutReceivingStore = false; function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return; } didWarnAboutReceivingStore = true; warning('<Provider> does not support changing `store` on the fly.'); } var Provider = (function (Component$$1) { function Provider(props, context) { Component$$1.call(this, props, context); this.store = props.store; } if ( Component$$1 ) Provider.__proto__ = Component$$1; Provider.prototype = Object.create( Component$$1 && Component$$1.prototype ); Provider.prototype.constructor = Provider; Provider.prototype.getChildContext = function getChildContext () { return { store: this.store }; }; Provider.prototype.render = function render () { if (isNullOrUndef(this.props.children) || toArray(this.props.children).length !== 1) { throw Error('Inferno Error: Only one child is allowed within the `Provider` component'); } return this.props.children; }; return Provider; }(Component)); if (process.env.NODE_ENV !== 'production') { Provider.prototype.componentWillReceiveProps = function (nextProps) { var ref = this; var store = ref.store; var nextStore = nextProps.store; if (store !== nextStore) { warnAboutReceivingStore(); } }; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var index$1 = createCommonjsModule(function (module) { 'use strict'; var INFERNO_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!INFERNO_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) { } } } } return targetComponent; } module.exports = hoistNonReactStatics; module.exports.default = module.exports; }); // From https://github.com/lodash/lodash/blob/es function overArg$2(func, transform) { return function (arg) { return func(transform(arg)); }; } var getPrototype$2 = overArg$2(Object.getPrototypeOf, Object); function isObjectLike$2(value) { return value != null && typeof value === 'object'; } var objectTag$1 = '[object Object]'; var funcProto$1 = Function.prototype; var objectProto$3 = Object.prototype; var funcToString$1 = funcProto$1.toString; var hasOwnProperty$2 = objectProto$3.hasOwnProperty; var objectCtorString$1 = funcToString$1.call(Object); var objectToString$2 = objectProto$3.toString; function isPlainObject$2(value) { if (!isObjectLike$2(value) || objectToString$2.call(value) !== objectTag$1) { return false; } var proto = getPrototype$2(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor; return (typeof Ctor === 'function' && Ctor instanceof Ctor && funcToString$1.call(Ctor) === objectCtorString$1); } var errorObject = { value: null }; var defaultMapStateToProps = function (state) { return ({}); }; // eslint-disable-line no-unused-vars var defaultMapDispatchToProps = function (dispatch) { return ({ dispatch: dispatch }); }; var defaultMergeProps = function (stateProps, dispatchProps, parentProps) { return Object.assign({}, parentProps, stateProps, dispatchProps); }; function tryCatch(fn, ctx) { try { return fn.apply(ctx); } catch (e) { errorObject.value = e; return errorObject; } } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } // Helps track hot reloading. var nextVersion = 0; function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) { if ( options === void 0 ) options = {}; var shouldSubscribe = Boolean(mapStateToProps); var mapState = mapStateToProps || defaultMapStateToProps; var mapDispatch; if (isFunction(mapDispatchToProps)) { mapDispatch = mapDispatchToProps; } else if (!mapDispatchToProps) { mapDispatch = defaultMapDispatchToProps; } else { mapDispatch = wrapActionCreators(mapDispatchToProps); } var finalMergeProps = mergeProps || defaultMergeProps; var pure = options.pure; if ( pure === void 0 ) pure = true; var withRef = options.withRef; if ( withRef === void 0 ) withRef = false; var checkMergedEquals = pure && finalMergeProps !== defaultMergeProps; // Helps track hot reloading. var version = nextVersion++; return function wrapWithConnect(WrappedComponent) { var connectDisplayName = "Connect(" + (getDisplayName(WrappedComponent)) + ")"; function checkStateShape(props, methodName) { if (!isPlainObject$2(props)) { warning(methodName + "() in " + connectDisplayName + " must return a plain object. " + "Instead received " + props + "."); } } function computeMergedProps(stateProps, dispatchProps, parentProps) { var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); if (process.env.NODE_ENV !== 'production') { checkStateShape(mergedProps, 'mergeProps'); } return mergedProps; } var Connect = (function (Component$$1) { function Connect(props, context) { var this$1 = this; Component$$1.call(this, props, context); this.version = version; this.store = (props && props.store) || (context && context.store); this.componentDidMount = function () { this$1.trySubscribe(); }; if (!this.store) { throwError('Could not find "store" in either the context or ' + "props of \"" + connectDisplayName + "\". " + 'Either wrap the root component in a <Provider>, ' + "or explicitly pass \"store\" as a prop to \"" + connectDisplayName + "\"."); } var storeState = this.store.getState(); this.state = { storeState: storeState }; this.clearCache(); } if ( Component$$1 ) Connect.__proto__ = Component$$1; Connect.prototype = Object.create( Component$$1 && Component$$1.prototype ); Connect.prototype.constructor = Connect; Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate () { return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged; }; 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 stateProps; }; Connect.prototype.configureFinalMapState = function configureFinalMapState (store, props) { var mappedState = mapState(store.getState(), props); var isFactory = isFunction(mappedState); this.finalMapStateToProps = isFactory ? mappedState : mapState; this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1; if (isFactory) { return this.computeStateProps(store, props); } return 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 dispatchProps; }; Connect.prototype.configureFinalMapDispatch = function configureFinalMapDispatch (store, props) { var mappedDispatch = mapDispatch(store.dispatch, props); var isFactory = isFunction(mappedDispatch); this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch; this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1; if (isFactory) { return this.computeDispatchProps(store, props); } return mappedDispatch; }; Connect.prototype.updateStatePropsIfNeeded = function updateStatePropsIfNeeded () { var nextStateProps = this.computeStateProps(this.store, this.props); if (this.stateProps && shallowEqual(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 && shallowEqual(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 && shallowEqual(nextMergedProps, this.mergedProps)) { return false; } this.mergedProps = nextMergedProps; return true; }; Connect.prototype.isSubscribed = function isSubscribed () { return isFunction(this.unsubscribe); }; 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.componentWillReceiveProps = function componentWillReceiveProps (nextProps) { if (!pure || !shallowEqual(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.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; this.renderedElement = null; this.finalMapDispatchToProps = null; this.finalMapStateToProps = null; }; Connect.prototype.handleChange = function handleChange () { if (!this.unsubscribe) { return; } var storeState = this.store.getState(); var prevStoreState = this.state.storeState; if (pure && prevStoreState === storeState) { return; } if (pure && !this.doStatePropsDependOnOwnProps) { var haveStatePropsChanged = tryCatch(this.updateStatePropsIfNeeded, this); if (!haveStatePropsChanged) { return; } if (haveStatePropsChanged === errorObject) { this.statePropsPrecalculationError = errorObject.value; } this.haveStatePropsBeenPrecalculated = true; } this.hasStoreStateChanged = true; this.setState({ storeState: storeState }); }; Connect.prototype.getWrappedInstance = function getWrappedInstance () { return this.refs.wrappedInstance; }; Connect.prototype.render = function render () { var ref = this; var haveOwnPropsChanged = ref.haveOwnPropsChanged; var hasStoreStateChanged = ref.hasStoreStateChanged; var haveStatePropsBeenPrecalculated = ref.haveStatePropsBeenPrecalculated; var statePropsPrecalculationError = ref.statePropsPrecalculationError; var renderedElement = ref.renderedElement; this.haveOwnPropsChanged = false; this.hasStoreStateChanged = false; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; if (statePropsPrecalculationError) { throw statePropsPrecalculationError; } 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 (haveStatePropsBeenPrecalculated) { haveStatePropsChanged = true; } else 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 = createElement(WrappedComponent, Object.assign({}, this.mergedProps, { ref: 'wrappedInstance' })); } else { this.renderedElement = createElement(WrappedComponent, this.mergedProps); } return this.renderedElement; }; return Connect; }(Component)); Connect.displayName = connectDisplayName; Connect.WrappedComponent = WrappedComponent; if (process.env.NODE_ENV !== 'production') { Connect.prototype.componentWillUpdate = function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; this.trySubscribe(); this.clearCache(); }; } return index$1(Connect, WrappedComponent); }; } var index = { Provider: Provider, connect: connect, }; return index; })));
src/modules/SpacedFlexbox.js
markmiro/ui-experiments
import React from 'react'; let SpacedFlexbox = React.createClass({ render () { let margin = this.props.spacing / 2; // flexbox margins don't collapse let children = React.Children.map(this.props.children, child => ( <li style={{margin, ...this.props.childWrapperStyle}}> {child} </li> )); return ( <ul style={{ // defaults flexWrap: 'wrap', // overrides ...this.props.style, // required margin: -margin, display: 'flex' }}> {children} </ul> ); } }); export default SpacedFlexbox;
app/shared/routes.js
esnunes/restaurants
import React from 'react'; import { Route, NotFoundRoute } from 'react-router'; export default ( <Route handler={require('./containers/app')}> <Route path="/" name="dashboard" handler={require('./containers/dashboard')} /> <Route path="/hello" handler={require('./containers/hello')} name="hello" /> <NotFoundRoute handler={require('./containers/not-found')} name="not-found" /> </Route> );
src/components/TodoItem/__tests__/index.js
henriquesosa/intro-ao-electron
jest.unmock('./') import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-addons-test-utils' import TodoItem from './' describe('TodoItem Component', () => { it('shows a title', () => { // const TodoItem = TestUtils.renderIntoDocument( // <TodoItem /> // ) // const TodoItemNode = ReactDOM.findDOMNode(TodoItem) // expect(TodoItemNode.textContent).equals('Todos') }) })
src/components/slide11-store.js
lucky3mvp/react-demo
import React from 'react' export default React.createClass({ render () { return ( <div className="m-code-dis with-border"> <ul> <li>store 是将 action 和 reducer 联系起来的对象</li> <li>通过 createStore( reducer, initialState ) 生成一个 store <img src="../img/s11-store-create.jpg" height="50" width="200" /> </li> <li>调用 store.dispatch( action ) 传递 action 时会自动触发 reducer</li> </ul> <p style={{marginTop:10}}>store 方法:</p> <ul style={{marginLeft:20}}> <li>store.dispatch( action ) : 更新state</li> <li>store.getState( ) : 获取state</li> <li>store.subscribe( listener ) : 注册监听器,以及返回函数注销监听器</li> </ul> </div> ) } })
ajax/libs/forerunnerdb/1.3.29/fdb-legacy.js
sreym/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'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":4,"../lib/Core":5,"../lib/Document":7,"../lib/Highchart":8,"../lib/OldView":22,"../lib/OldView.Bind":21,"../lib/Overview":25,"../lib/Persist":27,"../lib/View":30}],2:[function(_dereq_,module,exports){ "use strict"; /** * 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. */ var Shared = _dereq_('./Shared'); /** * The active bucket class. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * 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 obj[sortType.key]; 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.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -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 += obj[sortType.key]; } // 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; },{"./Shared":29}],3:[function(_dereq_,module,exports){ "use strict"; /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Core, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { 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._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // 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'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Core = Shared.modules.Core; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * 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 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'); /** * Get the internal data * @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 () { var key; if (this._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } 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; return true; } } else { return 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) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } 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); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Core=} 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()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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.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('ForerunnerDB.Collection "' + this.name() + '": 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 = JSON.stringify(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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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.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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // 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 {}; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { 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, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, 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, originalDoc, 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(originalDoc, update, query, options, ''); } 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: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; 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('ForerunnerDB.Collection "' + this.name() + '": 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 true; }; /** * 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 {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * 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, 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': // Ignore some operators operation = 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], '', {})) { 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': this._updateIncrement(doc, i, update[i]); updated = true; 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('ForerunnerDB.Collection "' + this.name() + '": 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], '', {})) { 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('ForerunnerDB.Collection "' + this.name() + '": 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 = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(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('ForerunnerDB.Collection "' + this.name() + '": 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('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": 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], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": 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 '$unset': this._updateUnset(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } 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) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @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 */ Collection.prototype._updateProperty = function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Collection: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } }; /** * 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 */ Collection.prototype._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 */ Collection.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } }; /** * 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 */ Collection.prototype._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 */ Collection.prototype._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 */ Collection.prototype._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 */ Collection.prototype._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 */ Collection.prototype._updateRename = function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ Collection.prototype._updateUnset = function (doc, prop) { delete doc[prop]; }; /** * Pops an item from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ Collection.prototype._updatePop = function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; 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 { 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); }; // 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); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * 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. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 100); } else { this.emit.apply(this, arguments); } }; /** * 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. */ Collection.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[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { 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.insert = function (data, index, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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, 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 (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // 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 }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * 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; 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); }; 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 false; } } 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 = JSON.stringify(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 = JSON.stringify(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); } } }; /** * 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(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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 = JSON.stringify(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. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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, //finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(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); } 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) { // 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); } // 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'); } op.time('tableScan: ' + scanLength); } if (options.$limit && resultArr && resultArr.length > 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 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 joinSearch = {}; joinMulti = false; joinRequire = false; 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 '$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; /*default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break;*/ } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // 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 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 = []; } // 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], '', {})) { // 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], '', {})) { // 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'); } op.stop(); resultArr.__fdbOp = op; return resultArr; }; /** * 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. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * 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) { // 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 = 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, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } 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('ForerunnerDB.Collection "' + this.name() + '": $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, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * 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, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), 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 match * @param path * @param subDocQuery * @param subDocOptions * @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: '' }; 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]; } resultObj.subDocs.push(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.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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; 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 pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw('ForerunnerDB.Collection "' + this.name() + '": Collection 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[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // 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[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = 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!'); } }; Core.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {Object} options An options object. * @returns {Collection} */ 'object': function (options) { 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. * @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. * @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. * @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. * @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 get's called by all the other variants and * handles the actual logic of the overloaded method. * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log('Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name).db(this); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Core.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @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. */ Core.prototype.collections = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":6,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":26,"./ReactorIO":28,"./Shared":29}],4:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CoreInit, Collection; Shared = _dereq_('./Shared'); 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'); Collection = _dereq_('./Collection'); Core = Shared.modules.Core; CoreInit = Shared.modules.Core.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 {Core=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); 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('ForerunnerDB.CollectionGroup "' + this.name() + '": 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 () { if (this._state !== 'dropped') { var i, collArr, viewArr; if (this._debug) { console.log('Dropping collection group ' + this._name); } 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); } return true; }; // Extend DB to include collection groups Core.prototype.init = function () { this._collectionGroup = {}; CoreInit.apply(this, arguments); }; Core.prototype.collectionGroup = function (collectionGroupName) { if (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. */ Core.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":3,"./Shared":29}],5:[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, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @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. * @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; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @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; // 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.ChainReactor'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Core.prototype._isServer = false; /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * 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; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Core.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. */ 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; }; /** * 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. */ Core.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 {*} */ Core.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 {*} */ Core.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 {*} */ Core.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; }; /** * 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} */ Core.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} */ Core.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; }; /** * Drops all collections in the database. * @param {Function=} callback Optional callback method. */ Core.prototype.drop = function (callback) { if (this._state !== 'dropped') { 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); } return true; }; module.exports = Core; },{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":29}],6:[function(_dereq_,module,exports){ "use strict"; 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 }; },{}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Collection, Core, CoreInit; Shared = _dereq_('./Shared'); (function init () { var Document = function () { this.init.apply(this, arguments); }; Document.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', Document); Shared.mixin(Document.prototype, 'Mixin.Common'); Shared.mixin(Document.prototype, 'Mixin.Events'); Shared.mixin(Document.prototype, 'Mixin.ChainReactor'); Shared.mixin(Document.prototype, 'Mixin.Constants'); Shared.mixin(Document.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Core = Shared.modules.Core; CoreInit = Shared.modules.Core.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Document.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @param {Core=} db The db instance. * @returns {*} */ Shared.synthesize(Document.prototype, 'db'); /** * Gets / sets the document name. * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(Document.prototype, 'name'); Document.prototype.setData = function (data) { var i, $unset; if (data) { 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; } } return this; }; /** * Modifies the document. This will update the document with the data held in 'update'. * * @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. */ Document.prototype.update = function (query, update, options) { this.updateObject(this._data, update, query, options); }; /** * 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 */ Document.prototype.updateObject = Collection.prototype.updateObject; /** * 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 */ Document.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. * @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 */ Document.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log('ForerunnerDB.Document: Setting data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Document: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } } }; /** * 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 */ Document.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. * @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 */ Document.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log('ForerunnerDB.Document: Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } } }; /** * 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 */ Document.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. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ Document.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. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ Document.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. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ Document.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. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ Document.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. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ Document.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {*} val The property to delete. * @return {Boolean} * @private */ Document.prototype._updatePop = function (doc, val) { var index, updated = false; if (doc.length > 0) { if (this._linked) { if (val === 1) { index = doc.length - 1; } else if (val === -1) { index = 0; } if (index > -1) { window.jQuery.observable(doc).remove(index); updated = true; } } else { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } } return updated; }; Document.prototype.drop = function () { if (this._state !== 'dropped') { 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); return true; } } } else { return true; } return false; }; // Extend DB to include documents Core.prototype.init = function () { CoreInit.apply(this, arguments); }; Core.prototype.document = function (documentName) { if (documentName) { this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new Document(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. * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Core.prototype.documents = function () { var arr = [], i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; Shared.finishModule('Document'); module.exports = Document; }()); },{"./Collection":3,"./Shared":29}],8:[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('ForerunnerDB.Highchart "' + 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.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw('ForerunnerDB.Highchart "' + 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.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) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = { categories: [] }, seriesName, query, dataSearch, seriesValues, 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++) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } seriesData.push({ name: seriesName, data: seriesValues }); } 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, arguments); }); }; /** * 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._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 () { if (this._state !== 'dropped') { 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); 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. * @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. * @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 options object. * @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. * @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. * @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. * @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. * @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. * @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. * @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. * @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. * @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. * @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. * @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":24,"./Shared":29}],9:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map 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 (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); 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('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 = new (btree.create(2, this.sortAsc))(); 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, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; 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) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.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); }; 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; },{"./Path":26,"./Shared":29}],10:[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 = {}; 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.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":26,"./Shared":29}],11:[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 {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * 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":29}],12:[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":23,"./Shared":29}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; // TODO: Document the methods in this mixin var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { 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, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // 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; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * 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 JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * 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; } ]) }; module.exports = Common; },{"./Overload":24}],16:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); 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; } }), 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 (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; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].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 var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; 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++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":24}],18:[function(_dereq_,module,exports){ "use strict"; 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 {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, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // 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 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 if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; 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], 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 (typeof(source) === '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], 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], 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], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], 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], 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], 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=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, 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 '$ne': // Not equals return source != test; // jshint ignore:line case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], '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], '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 (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": 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 (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; 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; },{}],20:[function(_dereq_,module,exports){ "use strict"; 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 }); 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 does not exist, create it self._trigger[type][phase].splice(triggerIndex, 1); } 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) { return this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length; }, /** * 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]; 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; },{}],21:[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":29}],22:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, CoreInit; 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; Core = Shared.modules.Core; CoreInit = Core.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]; } 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 Core.prototype.init = function () { this._oldViews = {}; CoreInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Core.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} */ Core.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. */ Core.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":3,"./CollectionGroup":4,"./Shared":29}],23:[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":26,"./Shared":29}],24:[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; // 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'; } // 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); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(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; },{}],25:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CoreInit, 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._collections = []; this._collectionDroppedWrap = function () { self._collectionDropped.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'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Core = Shared.modules.Core; CoreInit = Core.prototype.init; /** * 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 (collection) { if (collection !== undefined) { if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._addCollection(collection); return this; } return this._collections; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._addCollection = function (collection) { if (this._collections.indexOf(collection) === -1) { this._collections.push(collection); collection.chain(this); collection.on('drop', this._collectionDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeCollection = function (collection) { var collectionIndex = this._collections.indexOf(collection); if (collectionIndex > -1) { this._collections.splice(collection, 1); collection.unChain(this); collection.off('drop', this._collectionDroppedWrap); this._refresh(); } return this; }; Overview.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from overview this._removeCollection(collection); } }; Overview.prototype._refresh = function () { if (this._state !== 'dropped') { if (this._collections && this._collections[0]) { this._collData.primaryKey(this._collections[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._collections.length; i++) { tempArr = tempArr.concat(this._collections[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce(); // 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 () { if (this._state !== 'dropped') { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all collection references while (this._collections.length) { this._removeCollection(this._collections[0]); } delete this._collections; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); } return true; }; // Extend DB to include collection groups Core.prototype.init = function () { this._overview = {}; CoreInit.apply(this, arguments); }; Core.prototype.overview = function (overviewName) { if (overviewName) { 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; } }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":3,"./Document":7,"./Shared":29}],26:[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.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. * * @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') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * 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(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; 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])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * 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; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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; }; /** * 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":29}],27:[function(_dereq_,module,exports){ "use strict"; // TODO: Add doc comments to this class // Import external names locally var Shared = _dereq_('./Shared'), localforage = _dereq_('localforage'), Core, Collection, CollectionDrop, CollectionGroup, CollectionInit, CoreInit, Persist, Overload; Persist = function () { this.init.apply(this, arguments); }; Persist.prototype.init = function (db) { // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: 'ForerunnerDB', storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Core = Shared.modules.Core; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; CoreInit = Core.prototype.init; Overload = Shared.overload; Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; 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(); }; Persist.prototype.save = function (key, data, callback) { var encode; encode = function (val, finished) { if (typeof val === 'object') { val = 'json::fdb::' + JSON.stringify(val); } else { val = 'raw::fdb::' + val; } if (finished) { finished(false, val); } }; switch (this.mode()) { case 'localforage': encode(data, function (err, data) { localforage.setItem(key, data).then(function (data) { callback(false, data); }, function (err) { callback(err); }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; Persist.prototype.load = function (key, callback) { var parts, data, decode; decode = function (val, finished) { if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = JSON.parse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (finished) { finished(false, data); } } else { finished(false, val); } }; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { decode(val, callback); }, function (err) { callback(err); }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { callback(false); }, function (err) { 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._state !== 'dropped') { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { 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._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name); } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.apply(this, arguments); } }, /** * 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) { if (this._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name, callback); } 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!'); } } } // Call the original method CollectionDrop.apply(this, arguments); } } }); Collection.prototype.save = function (callback) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.save(this._name, this._data, callback); } 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!'); } } }; Collection.prototype.load = function (callback) { var self = this; if (this._name) { if (this._db) { // Load the collection data this._db.persist.load(this._name, function (err, data) { if (!err) { if (data) { self.setData(data); } if (callback) { callback(false); } } 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!'); } } }; // Override the DB init to instantiate the plugin Core.prototype.init = function () { this.persist = new Persist(this); CoreInit.apply(this, arguments); }; Core.prototype.load = function (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) { callback(false); } } else { callback(err); } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method obj[index].load(loadCallback); } } }; Core.prototype.save = function (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) { callback(false); } } else { callback(err); } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":3,"./CollectionGroup":4,"./Shared":29,"localforage":38}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { 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); ReactorIO.prototype.drop = function () { if (this._state !== 'dropped') { 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); } 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.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":29}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = { version: '1.3.29', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = 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. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; 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. * @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) { callback(name, this.modules[name]); } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @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. * @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: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @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. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ 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') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Triggers":20,"./Overload":24}],30:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, Collection, CollectionGroup, CollectionInit, CoreInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * The view constructor. * @param name * @param query * @param options * @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('__FDB__view_privateData_' + this._name); }; 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'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Core = Shared.modules.Core; CoreInit = Core.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); Shared.synthesize(View.prototype, 'name'); /** * Executes an insert against the view's underlying data-source. */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the collection from which the view will assemble its data. * @param {Collection} collection The collection to use to assemble view data. * @returns {View} */ View.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); delete this._from; } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" collection 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(collection, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // 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, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, '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 = collection.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(collection.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(collection.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } } return this; }; View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" 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); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in 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]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); 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; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" 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); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; View.prototype.on = function () { this._privateData.on.apply(this._privateData, arguments); }; View.prototype.off = function () { this._privateData.off.apply(this._privateData, arguments); }; View.prototype.emit = function () { 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) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.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 () { if (this._state !== 'dropped') { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); if (this.debug() || (this._db && this._db.debug())) { console.log('ForerunnerDB.View: Dropping view ' + this._name); } 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._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ View.prototype.db = function (db) { if (db !== undefined) { this._db = db; this.privateData().db(db); this.publicData().db(db); return this; } return this._db; }; /** * 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 {*} */ 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 (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 {*} */ 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 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(); // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); this._privateData.insert(this._from.find(this._querySettings.query, this._querySettings.options)); /*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 trasforms 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 () { return this._privateData && this._privateData._data ? this._privateData._data.length : 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) { 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; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * 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; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data 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 }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // 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('ForerunnerDB.Collection "' + this.name() + '": 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 Core.prototype.init = function () { this._view = {}; CoreInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Core.prototype.view = function (viewName) { if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log('Core.View: Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); 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} */ Core.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. */ Core.prototype.views = function () { var arr = [], i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { arr.push({ name: i, count: this._view[i].count() }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":28,"./Shared":29}],31:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],32:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":34}],33:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":32,"asap":34}],34:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":31}],35:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // 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; } // 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]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function() { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } 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') { window.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; } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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 result = iterator(cursor.value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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') { window.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); // 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() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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') { window.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 aborted if we've exceeded our storage // space. In this case, we will reject with a specific // "QuotaExceededError". transaction.onabort = function(event) { var error = event.target.error; if (error === 'QuotaExceededError') { reject(error); } }; })['catch'](reject); }); executeDeferedCallback(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() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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); }); } } function executeDeferedCallback(promise, callback) { if (callback) { promise.then(function(result) { deferCallback(callback, result); }, function(error) { callback(error); }); } } // Under Chrome the callback is called before the changes (save, clear) // are actually made. So we use a defer function which wait that the // call stack to be empty. // For more info : https://github.com/mozilla/localForage/issues/175 // Pull request : https://github.com/mozilla/localForage/pull/178 function deferCallback(callback, result) { if (callback) { return setTimeout(function() { return callback(null, result); }, 0); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports) { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":33}],36:[function(_dereq_,module,exports){ // 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). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; 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; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { 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') { window.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 = 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 keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); 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 = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); 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') { window.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') { window.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) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; 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 }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":39,"promise":33}],37:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); 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 serializerPromise.then(function(lib) { 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') { window.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 = 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 = 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') { window.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; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; 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') { window.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 }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":39,"promise":33}],38:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // 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 ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; 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 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // 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]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // 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(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(driverObject, callback, errorCallback) { var defineDriver = 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); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], function(lib) { self._extend(lib); resolve(); }); return; } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly var driver; switch (driverName) { case self.INDEXEDDB: driver = _dereq_('./drivers/indexeddb'); break; case self.LOCALSTORAGE: driver = _dereq_('./drivers/localstorage'); break; case self.WEBSQL: driver = _dereq_('./drivers/websql'); } self._extend(driver); } else { self._extend(globalObject[driverName]); } } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); } else { self._driverSet = Promise.reject(error); reject(error); return; } resolve(); }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":35,"./drivers/localstorage":36,"./drivers/websql":37,"promise":33}],39:[function(_dereq_,module,exports){ (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 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; // 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() { var str = bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { window.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 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 new Blob([buffer]); 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 }; if (typeof module !== 'undefined' && module.exports) { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}]},{},[1]);
blueprints/dumb/files/__root__/components/__name__/__name__.js
Rkiouak/react-redux-python-stocks
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/components/charts/charts/svg/text.js
noahehall/udacity-corporate-dashboard
import React from 'react'; export const Text = ({ chartType = '', className = '', dx = 0, // eslintignore x offset from current position dy = 0, // eslintignore y offset from current position fill = 'black', text = '', transform = 'rotate(20, 30, 40)', x = 0, // eslintignore relative to upper left y = 20, // eslintignore relative to upper left }) => { if (!text.length || !chartType) { appFuncs.logError({ data: [ chartType, dx, dy, fill, text, transform, x, y, ], msg: 'text must be a valid variable in svg/text.js, returning null', }); return null; } const thisClassName = `${className} ${chartType} labels`.trim(); return ( <text className={thisClassName} dx={dx} dy={dy} fill={fill} transform={transform} x={x} y={y} > {text} </text> ); }; Text.propTypes = { chartType: React.PropTypes.string, className: React.PropTypes.string, dx: React.PropTypes.number, dy: React.PropTypes.number, fill: React.PropTypes.string, text: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.string, ]), transform: React.PropTypes.string, x: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), y: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), }; export default Text;
web-app/src/components/ResetPassword/index.js
oSoc17/code9000
import React, { Component } from 'react'; import Title from '../Title'; import GuestMode, { GoBack } from '../GuestMode'; import { Form, Input, Button } from '../Form'; import { Success, Errors } from '../Alerts'; import api from '../../utils/api'; import './ResetPassword.css'; class RequestResetPassword extends Component { constructor(...props) { super(...props); this.state = { isValid: false, success: false, error: false, }; } requestResetPassword(body) { const token = this.props.match.params.token; api.post(`/auth/reset/${token}`, body).then(() => { this.setState({ success: true }); }) .catch(() => { this.setState({ error: true }); }); } render() { const { isValid, success, error } = this.state; return ( <GuestMode className="ResetPassword"> <Title name="Reset Password" /> {success && <Success body="We have reset your password." />} {error && <Errors errors={['Sorry. Something went wrong!']} />} {!success && ( <Form onValidationChange={(valid) => this.setState({ isValid: valid })} onSubmit={(body) => this.requestResetPassword(body)} > <div className="GuestMode__Label">Fill in your new password:</div> <Input type="password" name="password" rules={['required', 'password']} placeholder="Password" className="ResetPassword__Input" icon="lock" /> <div className="ResetPassword__Button"> <Button disabled={!isValid}>Reset password</Button> </div> </Form> )} <GoBack /> </GuestMode> ); } } export default RequestResetPassword;
local-cli/templates/HelloNavigation/components/ListItem.js
thotegowda/react-native
'use strict'; import React, { Component } from 'react'; import { Platform, StyleSheet, Text, TouchableHighlight, TouchableNativeFeedback, View, } from 'react-native'; /** * Renders the right type of Touchable for the list item, based on platform. */ const Touchable = ({onPress, children}) => { const child = React.Children.only(children); if (Platform.OS === 'android') { return ( <TouchableNativeFeedback onPress={onPress}> {child} </TouchableNativeFeedback> ); } else { return ( <TouchableHighlight onPress={onPress} underlayColor="#ddd"> {child} </TouchableHighlight> ); } } const ListItem = ({label, onPress}) => ( <Touchable onPress={onPress}> <View style={styles.item}> <Text style={styles.label}>{label}</Text> </View> </Touchable> ); const styles = StyleSheet.create({ item: { height: 48, justifyContent: 'center', paddingLeft: 12, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#ddd', }, label: { fontSize: 16, } }); export default ListItem;
app/components/About/LinkRenderer.js
sysrex/sysrex
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const LinkRenderer = (props) => { if (props.href.match(/^(https?:)?\/\//)) { return ( <a href={props.href}> {props.children} </a> ); } return ( <Link to={props.href}>{props.children}</Link> ); }; LinkRenderer.propTypes = { children: PropTypes.node.isRequired, href: PropTypes.string.isRequired, }; export default LinkRenderer;
ajax/libs/rxjs/2.1.2/rx.js
Ranks/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. (function (window, undefined) { var freeExports = typeof exports == 'object' && exports && (typeof global == 'object' && global && global == global.global && (window = global), exports); /** * @name Rx * @type Object */ var Rx = { Internals: {} }; // Defaults function noop() { } function identity(x) { return x; } function defaultNow() { return new Date().getTime(); } function defaultComparer(x, y) { return x === y; } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } // 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); } } 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; /** @private */ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ 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)); }); }; // Collection polyfills 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; }; } 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) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != "[object Function]") { 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) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != "[object Function]") { 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 Object.prototype.toString.call(arg) == '[object Array]'; }; } 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 var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var 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) { if (index === undefined) { 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. * * @memberOf 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. * * @memberOf CompositeDisposable# */ 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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. * * @memberOf CompositeDisposable# */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * * @memberOf CompositeDisposable# * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * * @memberOf CompositeDisposable# * @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; }; /** * Performs the task of cleaning up resources. * * @memberOf Disposable# */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * * @static * @memberOf Disposable * @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. * * @static * @memberOf Disposable */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. * * @constructor */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; /** * Gets or sets the underlying disposable. After disposal, the result of getting this method is undefined. * * @memberOf SingleAssignmentDisposable# * @param {Disposable} [value] The new underlying disposable. * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.disposable = function (value) { return !value ? this.getDisposable() : this.setDisposable(value); }; /** * Gets the underlying disposable. After disposal, the result of getting this method is undefined. * * @memberOf SingleAssignmentDisposable# * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * * @memberOf SingleAssignmentDisposable# * @param {Disposable} value The new underlying disposable. */ SingleAssignmentDisposablePrototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; if (!shouldDispose) { this.current = value; } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable. * * @memberOf SingleAssignmentDisposable# */ SingleAssignmentDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. * * @constructor */ var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; /** * Gets the underlying disposable. * @return The underlying disposable</returns> */ SerialDisposable.prototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * * @memberOf SerialDisposable# * @param {Disposable} value The new underlying disposable. */ SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Gets or sets the underlying disposable. * If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object. * * @memberOf SerialDisposable# * @param {Disposable} [value] The new underlying disposable. * @returns {Disposable} The underlying disposable. */ SerialDisposable.prototype.disposable = function (value) { if (!value) { return this.getDisposable(); } else { this.setDisposable(value); } }; /** * Disposes the underlying disposable as well as all future replacements. * * @memberOf SerialDisposable# */ SerialDisposable.prototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { /** * @constructor * @private */ function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } /** @private */ 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 * * @memberOf RefCountDisposable# */ 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. * * @memberOf RefCountDisposable# * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.H */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); /** * @constructor * @private */ function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; } /** * @private * @memberOf ScheduledDisposable# */ ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; /** * @private * @constructor */ function ScheduledItem(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(); } /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.invoke = function () { this.disposable.disposable(this.invokeCore()); }; /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; /** * @private * @memberOf ScheduledItem# */ ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; /** * @private * @memberOf ScheduledItem# */ 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 () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } 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 invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * * @memberOf Scheduler# * @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.catchException = function (handler) { return new CatchScheduler(this, handler); }; /** * 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. * * @memberOf Scheduler# * @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). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { 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. * * @memberOf Scheduler# * @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). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = window.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { window.clearInterval(id); }); }; /** * Schedules an action to be executed. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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); }; /** * Schedules an action to be executed recursively. * * @memberOf Scheduler# * @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. * * @memberOf Scheduler# * @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 }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * * @memberOf Scheduler * @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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * * @memberOf Scheduler * @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. * * @memberOf Scheduler * @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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * * @memberOf Scheduler * @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'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * * @static * @memberOf Scheduler * @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) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; /** * Gets a scheduler that schedules work immediately on the current thread. * * @memberOf Scheduler */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { if (dueTime > 0) throw new Error(schedulerNoBlockError); 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; /** * @private * @constructor */ function Trampoline() { queue = new PriorityQueue(4); } /** * @private * @memberOf Trampoline */ Trampoline.prototype.dispose = function () { queue = null; }; /** * @private * @memberOf Trampoline */ Trampoline.prototype.run = function () { var item; while (queue.length > 0) { item = queue.dequeue(); if (!item.isCancelled()) { 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), t; if (!queue) { t = new Trampoline(); try { queue.enqueue(si); t.run(); } catch (e) { throw e; } finally { t.dispose(); } } 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 === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); /** * @private */ var SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } /** * @constructor * @private */ 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; }()); /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { 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; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * * @memberOf VirtualTimeScheduler# * @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. * * @memberOf VirtualTimeScheduler# * @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. * * @memberOf VirtualTimeScheduler# * @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. * * @memberOf VirtualTimeScheduler# */ VirtualTimeSchedulerPrototype.start = function () { var next; if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null) { if (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. * * @memberOf VirtualTimeScheduler# */ 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 next; 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 { next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { if (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. * * @memberOf VirtualTimeScheduler# * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time); var dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } return this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * * @memberOf VirtualTimeScheduler# * @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. * * @memberOf VirtualTimeScheduler# * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { var next; while (this.queue.length > 0) { next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * * @memberOf VirtualTimeScheduler# * @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. * * @memberOf VirtualTimeScheduler# * @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, run = function (scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); }, si = new ScheduledItem(self, state, run, dueTime, self.comparer); self.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. * * @memberOf HistoricalScheduler * @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; }; /** * @private * @memberOf HistoricalScheduler */ 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 scheduleMethod, clearMethod = noop; (function () { function postMessageSupported () { // Ensure not in a worker if (!window.postMessage || window.importScripts) { return false; } var isAsync = false, oldHandler = window.onmessage; // Test for async window.onmessage = function () { isAsync = true; }; window.postMessage('','*'); window.onmessage = oldHandler; return isAsync; } if (typeof window.process !== 'undefined' && Object.prototype.toString.call(window.process) === '[object process]') { scheduleMethod = window.process.nextTick; } else if (typeof window.setImmediate === 'function') { scheduleMethod = window.setImmediate; clearMethod = window.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 (window.addEventListener) { window.addEventListener('message', onGlobalPostMessage, false); } else { window.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; window.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!window.MessageChannel) { var channel = new window.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 window && 'onreadystatechange' in window.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = window.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; window.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return window.setTimeout(action, 0); }; clearMethod = window.clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. * * @memberOf Scheduler */ 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 = window.setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { window.clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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; } var NotificationPrototype = Notification.prototype; /** * 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. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @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. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler = scheduler || immediateScheduler; return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; NotificationPrototype.equals = function (other) { var otherString = other == null ? '' : other.toString(); return this.toString() === otherString; }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * * @static * @memberOf Notification * @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.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * * @static s * @memberOf Notification * @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 (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * * @static * @memberOf Notification * @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.bind(notification); notification._acceptObservable = _acceptObservable.bind(notification); notification.toString = toString.bind(notification); return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { this.moveNext = moveNext; this.getCurrent = getCurrent; this.dispose = dispose; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { var done = false; dispose || (dispose = noop); return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; dispose(); } return result; }, function () { return getCurrent(); }, function () { if (!done) { dispose(); done = true; } }); }; /** @private */ var Enumerable = Rx.Internals.Enumerable = (function () { /** * @constructor * @private */ function Enumerable(getEnumerator) { this.getEnumerator = getEnumerator; } /** * @private * @memberOf Enumerable# */ Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } else { e.dispose(); } } catch (exception) { ex = exception; e.dispose(); } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; e.dispose(); })); }); }; /** * @private * @memberOf Enumerable# */ Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext; hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (exception) { ex = exception; } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; return Enumerable; }()); /** * @static * @private * @memberOf Enumerable */ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount === undefined) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; /** * @static * @private * @memberOf Enumerable */ var enumerableFor = Enumerable.forEach = function (source, selector) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector(source[index], index); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * 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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @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. * * @memberOf AbstractObserver * @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 () { if (!this.isStopped) { this.isStopped = true; this.error(true); 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. * * @constructor * @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. * * @memberOf AnonymousObserver * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * * @memberOf AnonymousObserver * @param {Any{ error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. * * @memberOf AnonymousObserver */ 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)); /** @private */ 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(); } /** @private */ ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; /** @private */ ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; /** @private */ ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; /** @private */ 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(); })); } }; /** @private */ ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ 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 () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; 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(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); } return Observable; })(); /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * 1 - res = Rx.Observable.start(function () { console.log('hello'); }); * 2 - res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * 2 - 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, scheduler, context) { return observableToAsync(func, 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 * 1 - res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * 2 - res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * 2 - res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param 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, scheduler, context) { scheduler || (scheduler = timeoutScheduler); return function () { var args = slice.call(arguments, 0), 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(); }; }; /** * 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; }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * 1 - res = Rx.Observable.create(function (observer) { return function () { } ); * * @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 = function (subscribe) { return new AnonymousObservable(function (o) { return disposableCreate(subscribe(o)); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * 1 - res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * @static * @memberOf Observable * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * 1 - res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @static * @memberOf Observable * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @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); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * 1 - res = Rx.Observable.empty(); * 2 - res = Rx.Observable.empty(Rx.Scheduler.timeout); * @static * @memberOf Observable * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * 1 - res = Rx.Observable.fromArray([1,2,3]); * 2 - res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @static * @memberOf Observable * @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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { 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 * 1 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * 2 - res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @static * @memberOf Observable * @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) { 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(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * * @static * @memberOf Observable * @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 * 1 - res = Rx.Observable.range(0, 10); * 2 - res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @static * @memberOf Observable * @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) { 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 * 1 - res = Rx.Observable.repeat(42); * 2 - 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); * @static * @memberOf Observable * @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) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == undefined) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * * @example * 1 - res = Rx.Observable.returnValue(42); * 2 - res = Rx.Observable.returnValue(42, Rx.Scheduler.timeout); * @static * @memberOf Observable * @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.returnValue = function (value, scheduler) { 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. * * @example * 1 - res = Rx.Observable.throwException(new Error('Error')); * 2 - res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @static * @memberOf Observable * @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.throwException = function (exception, scheduler) { 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. * * @example * 1 - res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @static * @memberOf Observable * @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(); if (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 that reacts first. * * @memberOf Observable# * @param {Observable} rightSource Second observable sequence. * @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(); 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 that reacts first. * * @example * E.g. winner = Rx.Observable.amb(xs, ys, zs); * @static * @memberOf Observable * @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; } 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); }) * @memberOf Observable# * @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.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences 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; }); * @memberOf Observable# * @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 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; }); * @static * @memberOf Observable * @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(function (x) { return x; }))) { 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(function (x) { return x; })) { 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) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); })(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]); * @memberOf Observable# * @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. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * * @memberOf Observable# * @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); * @memberOf Observable# * @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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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]); * * @static * @memberOf Observable * @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. * * @memberOf Observable# * @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); innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @memberOf Observable * @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]); * @static * @memberOf Observable * @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++]; d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { 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. * * @memberOf Observable# * @param {Observable} other The observable sequence 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) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); 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. * * @memberOf Observable# * @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.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); d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other Observable sequence 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) { 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); * @memberOf Observable# * @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; }); var next = function (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(function (x) { return x; })) { 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) { 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); } 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. * * @static * @memberOf Observable * @param {Array} sources 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 (sources, resultSelector) { var first = sources[0], rest = sources.slice(1); rest.push(resultSelector); return first.zip.apply(first, rest); }; /** * Hides the identity of an observable sequence. * * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * 1 - xs.bufferWithCount(10); * 2 - xs.bufferWithCount(10, 1); * * @memberOf Observable# * @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 (skip === undefined) { 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. * * @memberOf Observable# * @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. * * 1 - var obs = observable.distinctUntilChanged(); * 2 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @memberOf Observable# * @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. * * @example * 1 - observable.doAction(observer); * 2 - observable.doAction(onNext); * 3 - observable.doAction(onNext, onError); * 4 - observable.doAction(onNext, onError, onCompleted); * * @memberOf Observable# * @param {Mixed} 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.doAction = 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 (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * 1 - obs = observable.finallyAction(function () { console.log('sequence ended'; }); * * @memberOf Observable# * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * * @memberOf Observable# * @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. * * @memberOf Observable# * @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 (exception) { observer.onNext(notificationCreateOnError(exception)); 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 * 1 - repeated = source.repeat(); * 2 - repeated = source.repeat(42); * * @memberOf Observable# * @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. * * @example * 1 - retried = retry.repeat(); * 2 - retried = retry.repeat(42); * * @memberOf Observable# * @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. * * 1 - scanned = source.scan(function (acc, x) { return acc + x; }); * 2 - scanned = source.scan(0, function (acc, x) { return acc + x; }); * * @memberOf Observable# * @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 seed, hasSeed = false, accumulator; if (arguments.length === 2) { seed = arguments[0]; accumulator = arguments[1]; hasSeed = true; } else { accumulator = arguments[0]; } var source = this; return observableDefer(function () { var hasAccumulation = false, accumulation; return source.select(function (x) { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } return accumulation; }); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * * @memberOf Observable# * @description * This operator accumulates a queue with a length enough to store the first <paramref name="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); if (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. * * 1 - source.startWith(1, 2, 3); * 2 - source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (arguments.length > 0 && arguments[0] != null && arguments[0].now !== undefined) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * 1 - obs = source.takeLast(5); * 2 - obs = source.takeLast(5, Rx.Scheduler.timeout); * * @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. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * 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. * * @memberOf Observable# * @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); if (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. * * 1 - xs.windowWithCount(10); * 2 - xs.windowWithCount(10, 1); * * @memberOf Observable# * @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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (skip == null) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * 1 - 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(); }); }); }; /** * 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 * 1 - obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; 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 * 1 - 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(); }); * * @memberOf Observable# * @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} [keySerializer] Used to serialize the given object into a string for object comparison. * @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, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * 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 * 1 - 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(); }); * * @memberOf Observable# * @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} [keySerializer] Used to serialize the given object into a string for object comparison. * @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, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, expire, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * * @example * source.select(function (value, index) { return value * value + index; }); * * @memberOf Observable# * @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 = 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 (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.map = observableProto.select; function selectMany(selector) { return this.select(selector).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 * 1 - 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. * * 1 - 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. * * 1 - source.selectMany(Rx.Observable.fromArray([1,2,3])); * * @memberOf Observable# * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. * @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.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x) { return selector(x).select(function (y) { return resultSelector(x, y); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * * @memberOf Observable# * @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 observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.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. * * 1 - source.skipWhile(function (value) { return value < 10; }); * 1 - source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @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. * @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) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate(x, i++); } catch (e) { observer.onError(e); return; } } if (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). * * 1 - source.take(5); * 2 - source.take(0, Rx.Scheduler.timeout); * * @memberOf Observable# * @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 Error(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) { remaining--; observer.onNext(x); if (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. * * @example * 1 - source.takeWhile(function (value) { return value < 10; }); * 1 - source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @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. * @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) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate(x, i++); } 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 * 1 - source.where(function (value) { return value < 10; }); * 1 - source.where(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @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 = 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 (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.filter = observableProto.where; /** @private */ var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); /** * @private * @constructor */ function AnonymousObservable(subscribe) { function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.disposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.disposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); /** * @private * @constructor */ function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.disposable = function (value) { return this.m.disposable(value); }; /** * @private * @memberOf AutoDetachObserver# */ AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ 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)); /** @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 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. * * @memberOf ReplaySubject# * @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. * * @memberOf ReplaySubject# */ 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. * * @memberOf ReplaySubject# * @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. * * @memberOf ReplaySubject# * @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. * * @memberOf ReplaySubject# */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * * @static * @memberOf Subject * @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; var hv = this.hasValue; var 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. * * @memberOf AsyncSubject# * @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, also causing the last received value to be sent out (if any). * * @memberOf AsyncSubject# */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; var v = this.value; var 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 exception. * * @memberOf AsyncSubject# * @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 = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * * @memberOf AsyncSubject# * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. * * @memberOf AsyncSubject# */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); // Check for AMD if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.Rx = Rx; return define(function () { return Rx; }); } else if (freeExports) { if (typeof module == 'object' && module && module.exports == freeExports) { module.exports = Rx; } else { freeExports = Rx; } } else { window.Rx = Rx; } }(this));
public/js/libs/ember-data.js
amooma/GS5
// Version: v0.13-33-g8cf224d // Last commit: 8cf224d (2013-06-19 00:23:32 -0400) (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod, deps, callback, reified , exports; mod = registry[name]; if (!mod) { throw new Error("Module '" + name + "' not found."); } 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(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /** @module data @main data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ window.DS = Ember.Namespace.create(); })(); (function() { var set = Ember.set; /** This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'App.MyCustomAdapter' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "injectStore", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); } }); }); })(); (function() { /** * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> * © 2011 Colin Snover <http://zetafleet.com> * Released under MIT license. */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { var Evented = Ember.Evented, // ember-runtime/mixins/evented Deferred = Ember.DeferredMixin, // ember-runtime/mixins/evented run = Ember.run, // ember-metal/run-loop get = Ember.get; // ember-metal/accessors var LoadPromise = Ember.Mixin.create(Evented, Deferred, { init: function() { this._super.apply(this, arguments); this.one('didLoad', this, function() { this.resolve(this); }); this.one('becameError', this, function() { this.reject(this); }); if (get(this, 'isLoaded')) { this.trigger('didLoad'); } } }); DS.LoadPromise = LoadPromise; })(); (function() { /** */ var get = Ember.get, set = Ember.set; var LoadPromise = DS.LoadPromise; // system/mixins/load_promise /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of DS.RecordArray or its subclasses will be returned by your application's store in response to queries. @module data @submodule data-record-array @main data-record-array @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented @uses DS.LoadPromise */ DS.RecordArray = Ember.ArrayProxy.extend(LoadPromise, { /** The model type contained by this record array. @type DS.Model */ type: null, // The array of client ids backing the record array. When a // record is requested from the record array, the record // for the client id at the same index is materialized, if // necessary, by the store. content: null, isLoaded: false, isUpdating: false, // The store that created this record array. store: null, objectAtContent: function(index) { var content = get(this, 'content'), reference = content.objectAt(index), store = get(this, 'store'); if (reference) { return store.recordForReference(reference); } }, materializedObjectAt: function(index) { var reference = get(this, 'content').objectAt(index); if (!reference) { return; } if (get(this, 'store').recordIsMaterialized(reference)) { return this.objectAt(index); } }, update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); store.fetchAll(type, this); }, addReference: function(reference) { get(this, 'content').addObject(reference); }, removeReference: function(reference) { get(this, 'content').removeObject(reference); } }); })(); (function() { /** @module data @submodule data-record-array */ var get = Ember.get; /** @class FilteredRecordArray @namespace DS @extends DS.RecordArray @constructor */ DS.FilteredRecordArray = DS.RecordArray.extend({ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, updateFilter: Ember.observer(function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { /** @module data @submodule data-record-array */ var get = Ember.get, set = Ember.set; /** @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray @constructor */ DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, load: function(references) { this.setProperties({ content: Ember.A(references), isLoaded: true }); // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); })(); (function() { /** @module data @submodule data-record-array */ var get = Ember.get, set = Ember.set; /** A ManyArray is a RecordArray that represents the contents of a has-many relationship. The ManyArray is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: App.Post = DS.Model.extend({ comments: DS.hasMany('App.Comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('App.Post') }); If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray @constructor */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** @private The record to which this relationship belongs. @property {DS.Model} */ owner: null, /** @private `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} */ isPolymorphic: false, // LOADING STATE isLoaded: false, loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, fetch: function() { var references = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'); store.fetchUnloadedReferences(references, owner); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = added.map(function(record) { Ember.assert("You can only add records of " + (get(this, 'type') && get(this, 'type').toString()) + " to this relationship.", !get(this, 'type') || (get(this, 'type').detectInstance(record)) ); return get(record, '_reference'); }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { this.fetch(); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); DS.OneToManyChange.ensureSameTransaction(this._changesToSync, store); this._changesToSync.clear(); } }, // Create a child record within the owner createRecord: function(hash, transaction) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; Ember.assert("You can not create records of " + (get(this, 'type') && get(this, 'type').toString()) + " on this polymorphic relationship.", !get(this, 'isPolymorphic')); transaction = transaction || get(owner, 'transaction'); record = store.createRecord.call(store, type, hash, transaction); this.pushObject(record); return record; } }); })(); (function() { /** @module data @submodule data-record-array */ })(); (function() { var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** @module data @submodule data-transaction */ /** A transaction allows you to collect multiple records into a unit of work that can be committed or rolled back as a group. For example, if a record has local modifications that have not yet been saved, calling `commit()` on its transaction will cause those modifications to be sent to the adapter to be saved. Calling `rollback()` on its transaction would cause all of the modifications to be discarded and the record to return to the last known state before changes were made. If a newly created record's transaction is rolled back, it will immediately transition to the deleted state. If you do not explicitly create a transaction, a record is assigned to an implicit transaction called the default transaction. In these cases, you can treat your application's instance of `DS.Store` as a transaction and call the `commit()` and `rollback()` methods on the store itself. Once a record has been successfully committed or rolled back, it will be moved back to the implicit transaction. Because it will now be in a clean state, it can be moved to a new transaction if you wish. ### Creating a Transaction To create a new transaction, call the `transaction()` method of your application's `DS.Store` instance: var transaction = App.store.transaction(); This will return a new instance of `DS.Transaction` with no records yet assigned to it. ### Adding Existing Records Add records to a transaction using the `add()` method: record = App.store.find(App.Person, 1); transaction.add(record); Note that only records whose `isDirty` flag is `false` may be added to a transaction. Once modifications to a record have been made (its `isDirty` flag is `true`), it is not longer able to be added to a transaction. ### Creating New Records Because newly created records are dirty from the time they are created, and because dirty records can not be added to a transaction, you must use the `createRecord()` method to assign new records to a transaction. For example, instead of this: var transaction = store.transaction(); var person = App.Person.createRecord({ name: "Steve" }); // won't work because person is dirty transaction.add(person); Call `createRecord()` on the transaction directly: var transaction = store.transaction(); transaction.createRecord(App.Person, { name: "Steve" }); ### Asynchronous Commits Typically, all of the records in a transaction will be committed together. However, new records that have a dependency on other new records need to wait for their parent record to be saved and assigned an ID. In that case, the child record will continue to live in the transaction until its parent is saved, at which time the transaction will attempt to commit again. For this reason, you should not re-use transactions once you have committed them. Always make a new transaction and move the desired records to it before calling commit. */ DS.Transaction = Ember.Object.extend({ /** @private Creates the bucket data structure used to segregate records by type. */ init: function() { set(this, 'records', Ember.OrderedSet.create()); }, /** Creates a new record of the given type and assigns it to the transaction on which the method was called. This is useful as only clean records can be added to a transaction and new records created using other methods immediately become dirty. @param {DS.Model} type the model type to create @param {Object} hash the data hash to assign the new record */ createRecord: function(type, hash) { var store = get(this, 'store'); return store.createRecord(type, hash, this); }, isEqualOrDefault: function(other) { if (this === other || other === get(this, 'store.defaultTransaction')) { return true; } }, isDefault: Ember.computed(function() { return this === get(this, 'store.defaultTransaction'); }).volatile(), /** Adds an existing record to this transaction. Only records without modificiations (i.e., records whose `isDirty` property is `false`) can be added to a transaction. @param {DS.Model} record the record to add to the transaction */ add: function(record) { Ember.assert("You must pass a record into transaction.add()", record instanceof DS.Model); var store = get(this, 'store'); var adapter = get(store, '_adapter'); var serializer = get(adapter, 'serializer'); serializer.eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { if (embeddedType === 'load') { return; } this.add(embeddedRecord); }, this); this.adoptRecord(record); }, relationships: Ember.computed(function() { var relationships = Ember.OrderedSet.create(), records = get(this, 'records'), store = get(this, 'store'); records.forEach(function(record) { var reference = get(record, '_reference'); var changes = store.relationshipChangesFor(reference); for(var i = 0; i < changes.length; i++) { relationships.add(changes[i]); } }); return relationships; }).volatile(), commitDetails: Ember.computed(function() { var commitDetails = Ember.MapWithDefault.create({ defaultValue: function() { return { created: Ember.OrderedSet.create(), updated: Ember.OrderedSet.create(), deleted: Ember.OrderedSet.create() }; } }); var records = get(this, 'records'), store = get(this, 'store'); records.forEach(function(record) { if(!get(record, 'isDirty')) return; record.send('willCommit'); var adapter = store.adapterForType(record.constructor); commitDetails.get(adapter)[get(record, 'dirtyType')].add(record); }); return commitDetails; }).volatile(), /** Commits the transaction, which causes all of the modified records that belong to the transaction to be sent to the adapter to be saved. Once you call `commit()` on a transaction, you should not re-use it. When a record is saved, it will be removed from this transaction and moved back to the store's default transaction. */ commit: function() { var store = get(this, 'store'); if (get(this, 'isDefault')) { set(store, 'defaultTransaction', store.transaction()); } this.removeCleanRecords(); var commitDetails = get(this, 'commitDetails'), relationships = get(this, 'relationships'); commitDetails.forEach(function(adapter, commitDetails) { Ember.assert("You tried to commit records but you have no adapter", adapter); Ember.assert("You tried to commit records but your adapter does not implement `commit`", adapter.commit); adapter.commit(store, commitDetails); }); // Once we've committed the transaction, there is no need to // keep the OneToManyChanges around. Destroy them so they // can be garbage collected. relationships.forEach(function(relationship) { relationship.destroy(); }); }, /** Rolling back a transaction resets the records that belong to that transaction. Updated records have their properties reset to the last known value from the persistence layer. Deleted records are reverted to a clean, non-deleted state. Newly created records immediately become deleted, and are not sent to the adapter to be persisted. After the transaction is rolled back, any records that belong to it will return to the store's default transaction, and the current transaction should not be used again. */ rollback: function() { // Destroy all relationship changes and compute // all references affected var references = Ember.OrderedSet.create(); var relationships = get(this, 'relationships'); relationships.forEach(function(r) { references.add(r.firstRecordReference); references.add(r.secondRecordReference); r.destroy(); }); var records = get(this, 'records'); records.forEach(function(record) { if (!record.get('isDirty')) return; record.send('rollback'); }); // Now that all records in the transaction are guaranteed to be // clean, migrate them all to the store's default transaction. this.removeCleanRecords(); // Remaining associated references are not part of the transaction, but // can still have hasMany's which have not been reloaded references.forEach(function(r) { if (r && r.record) { var record = r.record; record.suspendRelationshipObservers(function() { record.reloadHasManys(); }); } }, this); }, /** @private Removes a record from this transaction and back to the store's default transaction. Note: This method is private for now, but should probably be exposed in the future once we have stricter error checking (for example, in the case of the record being dirty). @param {DS.Model} record */ remove: function(record) { var defaultTransaction = get(this, 'store.defaultTransaction'); defaultTransaction.adoptRecord(record); }, /** @private Removes all of the records in the transaction's clean bucket. */ removeCleanRecords: function() { var records = get(this, 'records'); records.forEach(function(record) { if(!record.get('isDirty')) { this.remove(record); } }, this); }, /** @private This method moves a record into a different transaction without the normal checks that ensure that the user is not doing something weird, like moving a dirty record into a new transaction. It is designed for internal use, such as when we are moving a clean record into a new transaction when the transaction is committed. This method must not be called unless the record is clean. @param {DS.Model} record */ adoptRecord: function(record) { var oldTransaction = get(record, 'transaction'); if (oldTransaction) { oldTransaction.removeRecord(record); } get(this, 'records').add(record); set(record, 'transaction', this); }, /** @private Removes the record without performing the normal checks to ensure that the record is re-added to the store's default transaction. */ removeRecord: function(record) { get(this, 'records').remove(record); } }); DS.Transaction.reopenClass({ ensureSameTransaction: function(records){ var transactions = Ember.A(); forEach( records, function(record){ if (record){ transactions.pushObject(get(record, 'transaction')); } }); var transaction = transactions.reduce(function(prev, t) { if (!get(t, 'isDefault')) { if (prev === null) { return t; } Ember.assert("All records in a changed relationship must be in the same transaction. You tried to change the relationship between records when one is in " + t + " and the other is in " + prev, t === prev); } return prev; }, null); if (transaction) { forEach( records, function(record){ if (record){ transaction.add(record); } }); } else { transaction = transactions.objectAt(0); } return transaction; } }); })(); (function() { var get = Ember.get; /** The Mappable mixin is designed for classes that would like to behave as a map for configuration purposes. For example, the DS.Adapter class can behave like a map, with more semantic API, via the `map` API: DS.Adapter.map('App.Person', { firstName: { key: 'FIRST' } }); Class configuration via a map-like API has a few common requirements that differentiate it from the standard Ember.Map implementation. First, values often are provided as strings that should be normalized into classes the first time the configuration options are used. Second, the values configured on parent classes should also be taken into account. Finally, setting the value of a key sometimes should merge with the previous value, rather than replacing it. This mixin provides a instance method, `createInstanceMapFor`, that will reify all of the configuration options set on an instance's constructor and provide it for the instance to use. Classes can implement certain hooks that allow them to customize the requirements listed above: * `resolveMapConflict` - called when a value is set for an existing value * `transformMapKey` - allows a key name (for example, a global path to a class) to be normalized * `transformMapValue` - allows a value (for example, a class that should be instantiated) to be normalized Classes that implement this mixin should also implement a class method built using the `generateMapFunctionFor` method: DS.Adapter.reopenClass({ map: DS.Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { var existingValue = map.get(key); for (var prop in newValue) { if (!newValue.hasOwnProperty(prop)) { continue; } existingValue[prop] = newValue[prop]; } }) }); The function passed to `generateMapFunctionFor` is invoked every time a new value is added to the map. @class _Mappable @private @namespace DS @extends Ember.Mixin **/ var resolveMapConflict = function(oldValue, newValue) { return oldValue; }; var transformMapKey = function(key, value) { return key; }; var transformMapValue = function(key, value) { return value; }; DS._Mappable = Ember.Mixin.create({ createInstanceMapFor: function(mapName) { var instanceMeta = getMappableMeta(this); instanceMeta.values = instanceMeta.values || {}; if (instanceMeta.values[mapName]) { return instanceMeta.values[mapName]; } var instanceMap = instanceMeta.values[mapName] = new Ember.Map(); var klass = this.constructor; while (klass && klass !== DS.Store) { this._copyMap(mapName, klass, instanceMap); klass = klass.superclass; } instanceMeta.values[mapName] = instanceMap; return instanceMap; }, _copyMap: function(mapName, klass, instanceMap) { var classMeta = getMappableMeta(klass); var classMap = classMeta[mapName]; if (classMap) { classMap.forEach(eachMap, this); } function eachMap(key, value) { var transformedKey = (klass.transformMapKey || transformMapKey)(key, value); var transformedValue = (klass.transformMapValue || transformMapValue)(key, value); var oldValue = instanceMap.get(transformedKey); var newValue = transformedValue; if (oldValue) { newValue = (this.constructor.resolveMapConflict || resolveMapConflict)(oldValue, newValue); } instanceMap.set(transformedKey, newValue); } } }); DS._Mappable.generateMapFunctionFor = function(mapName, transform) { return function(key, value) { var meta = getMappableMeta(this); var map = meta[mapName] || Ember.MapWithDefault.create({ defaultValue: function() { return {}; } }); transform.call(this, key, value, map); meta[mapName] = map; }; }; function getMappableMeta(obj) { var meta = Ember.meta(obj, true), keyName = 'DS.Mappable', value = meta[keyName]; if (!value) { meta[keyName] = {}; } if (!meta.hasOwnProperty(keyName)) { meta[keyName] = Ember.create(meta[keyName]); } return meta[keyName]; } })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ /** @module data @submodule data-store */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var map = Ember.EnumerableUtils.map; // These values are used in the data cache when clientIds are // needed but the underlying data has not yet been loaded by // the server. var UNLOADED = 'unloaded'; var LOADING = 'loading'; var MATERIALIZED = { materialized: true }; var CREATED = { created: true }; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: MyApp.Store = DS.Store.extend(); Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Model`'s `find()` method: var person = App.Person.find(123); If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: var person = store.find(App.Person, 123); In general, you should retrieve models using the methods on `DS.Model`; you should rarely need to interact with the store directly. By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. @class Store @namespace DS @extends Ember.Object @uses DS._Mappable @constructor */ DS.Store = Ember.Object.extend(DS._Mappable, { /** Many methods can be invoked without specifying which store should be used. In those cases, the first store created will be used as the default. If an application has multiple stores, it should specify which store to use when performing actions, such as finding records by ID. The init method registers this store as the default if none is specified. */ init: function() { if (!get(DS, 'defaultStore') || get(this, 'isDefaultStore')) { set(DS, 'defaultStore', this); } // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = DS.RecordArrayManager.create({ store: this }); this.relationshipChanges = {}; set(this, 'currentTransaction', this.transaction()); set(this, 'defaultTransaction', this.transaction()); }, /** Returns a new transaction scoped to this store. This delegates responsibility for invoking the adapter's commit mechanism to a transaction. Transaction are responsible for tracking changes to records added to them, and supporting `commit` and `rollback` functionality. Committing a transaction invokes the store's adapter, while rolling back a transaction reverses all changes made to records added to the transaction. A store has an implicit (default) transaction, which tracks changes made to records not explicitly added to a transaction. @see {DS.Transaction} @returns DS.Transaction */ transaction: function() { return DS.Transaction.create({ store: this }); }, /** @private Instructs the store to materialize the data for a given record. To materialize a record, the store first retrieves the opaque data that was passed to either `load()` or `loadMany()`. Then, the data and the record are passed to the adapter's `materialize()` method, which allows the adapter to translate arbitrary data structures from the adapter into the normalized form the record expects. The adapter's `materialize()` method will invoke `materializeAttribute()`, `materializeHasMany()` and `materializeBelongsTo()` on the record to populate it with normalized values. @param {DS.Model} record */ materializeData: function(record) { var reference = get(record, '_reference'), data = reference.data, adapter = this.adapterForType(record.constructor); reference.data = MATERIALIZED; record.setupData(); if (data !== CREATED) { // Instructs the adapter to extract information from the // opaque data and materialize the record's attributes and // relationships. adapter.materialize(record, data, reference.prematerialized); } }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, a class, or a property path that specifies where the adapter can be located. @property {DS.Adapter|String} */ adapter: Ember.computed(function(){ if (!Ember.testing) { Ember.debug("A custom DS.Adapter was not provided as the 'Adapter' property of your application's Store. The default (DS.RESTAdapter) will be used."); } return 'DS.RESTAdapter'; }).property(), /** @private Returns a JSON representation of the record using the adapter's serialization strategy. This method exists primarily to enable a record, which has access to its store (but not the store's adapter) to provide a `serialize()` convenience. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.adapterForType(record.constructor).serialize(record, options); }, /** @private This property returns the adapter, after resolving a possible property path. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @returns DS.Adapter */ _adapter: Ember.computed(function() { var adapter = get(this, 'adapter'); if (typeof adapter === 'string') { adapter = get(this, adapter, false) || get(Ember.lookup, adapter); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create(); } return adapter; }).property('adapter'), /** @private A monotonically increasing number to be used to uniquely identify data and records. It starts at 1 so other parts of the code can test for truthiness when provided a `clientId` instead of having to explicitly test for undefined. */ clientIdCounter: 1, // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. Note: The third `transaction` property is for internal use only. If you want to create a record inside of a given transaction, use `transaction.createRecord()` instead of `store.createRecord()`. @method createRecord @param {subclass of DS.Model} type @param {Object} properties a hash of properties to set on the newly created record. @returns DS.Model */ createRecord: function(type, properties, transaction) { properties = properties || {}; // Create a new instance of the model `type` and put it // into the specified `transaction`. If no transaction is // specified, the default transaction will be used. var record = type._create({ store: this }); transaction = transaction || get(this, 'defaultTransaction'); // adoptRecord is an internal API that allows records to move // into a transaction without assertions designed for app // code. It is used here to ensure that regardless of new // restrictions on the use of the public `transaction.add()` // API, we will always be able to insert new records into // their transaction. transaction.adoptRecord(record); // `id` is a special property that may not be a `DS.attr` var id = properties.id; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(id)) { var adapter = this.adapterForType(type); if (adapter && adapter.generateIdForRecord) { id = coerceId(adapter.generateIdForRecord(this, record)); properties.id = id; } } // Coerce ID to a string id = coerceId(id); // Create a new `clientId` and associate it with the // specified (or generated) `id`. Since we don't have // any data for the server yet (by definition), store // the sentinel value CREATED as the data for this // clientId. If we see this value later, we will skip // materialization. var reference = this.createReference(type, id); reference.data = CREATED; // Now that we have a reference, attach it to the record we // just created. set(record, '_reference', reference); reference.record = record; // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); record.setupData(); // Set the properties specified on the record. record.setProperties(properties); // Resolve record promise Ember.run(record, 'resolve', record); return record; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is always a subclass of `DS.Model`. You can use the `find` method on a subclass of `DS.Model` directly if your application only has one store. For example, instead of `store.find(App.Person, 1)`, you could say `App.Person.find(1)`. --- To find a record by ID, pass the `id` as the second parameter: store.find(App.Person, 1); App.Person.find(1); If the record with that `id` had not previously been loaded, the store will return an empty record immediately and ask the adapter to find the data by calling the adapter's `find` method. The `find` method will always return the same object for a given type and `id`. To check whether the adapter has populated a record, you can check its `isLoaded` property. --- To find all records for a type, call `find` with no additional parameters: store.find(App.Person); App.Person.find(); This will return a `RecordArray` representing all known records for the given type and kick off a request to the adapter's `findAll` method to load any additional records for the type. The `RecordArray` returned by `find()` is live. If any more records for the type are added at a later time through any mechanism, it will automatically update to reflect the change. --- To find a record by a query, call `find` with a hash as the second parameter: store.find(App.Person, { page: 1 }); App.Person.find({ page: 1 }); This will return a `RecordArray` immediately, but it will always be an empty `RecordArray` at first. It will call the adapter's `findQuery` method, which will populate the `RecordArray` once the server has returned results. You can check whether a query results `RecordArray` has loaded by checking its `isLoaded` property. @method find @param {DS.Model} type @param {Object|String|Integer|null} id */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** @private This method returns a record for a given type and id combination. If the store has never seen this combination of type and id before, it creates a new `clientId` with the LOADING sentinel and asks the adapter to load the data. If the store has seen the combination, this method delegates to `getByReference`. */ findById: function(type, id) { var reference; if (this.hasReferenceForId(type, id)) { reference = this.referenceForId(type, id); if (reference.data !== UNLOADED) { return this.recordForReference(reference); } } if (!reference) { reference = this.createReference(type, id); } reference.data = LOADING; // create a new instance of the model type in the // 'isLoading' state var record = this.materializeRecord(reference); if (reference.data === LOADING) { // let the adapter set the data, possibly async var adapter = this.adapterForType(type), store = this; Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter does not implement `find`", adapter.find); var thenable = adapter.find(this, type, id); if (thenable && thenable.then) { thenable.then(null /* for future use */, function(error) { store.recordWasError(record); }); } } return record; }, reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterForType(type), store = this, id = get(record, 'id'); Ember.assert("You cannot update a record without an ID", id); Ember.assert("You tried to update a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to update a record but your adapter does not implement `find`", adapter.find); var thenable = adapter.find(this, type, id); if (thenable && thenable.then) { thenable.then(null /* for future use */, function(error) { store.recordWasError(record); }); } }, /** @private This method returns a record for a given record refeence. If no record for the reference has yet been materialized, this method will materialize a new `DS.Model` instance. This allows adapters to eagerly load large amounts of data into the store, and avoid incurring the cost of creating models until they are requested. In short, it's a convenient way to get a record for a known record reference, materializing it if necessary. @param {Object} reference @returns {DS.Model} */ recordForReference: function(reference) { var record = reference.record; if (!record) { // create a new instance of the model type in the // 'isLoading' state record = this.materializeRecord(reference); } return record; }, /** @private Given an array of `reference`s, determines which of those `clientId`s has not yet been loaded. In preparation for loading, this method also marks any unloaded `clientId`s as loading. */ unloadedReferences: function(references) { var unloadedReferences = []; for (var i=0, l=references.length; i<l; i++) { var reference = references[i]; if (reference.data === UNLOADED) { unloadedReferences.push(reference); reference.data = LOADING; } } return unloadedReferences; }, /** @private This method is the entry point that relationships use to update themselves when their underlying data changes. First, it determines which of its `reference`s are still unloaded, then invokes `findMany` on the adapter. */ fetchUnloadedReferences: function(references, owner) { var unloadedReferences = this.unloadedReferences(references); this.fetchMany(unloadedReferences, owner); }, /** @private This method takes a list of `reference`s, groups the `reference`s by type, converts the `reference`s into IDs, and then invokes the adapter's `findMany` method. The `reference`s are grouped by type to invoke `findMany` on adapters for each unique type in `reference`s. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes (via the `fetchUnloadedReferences` method). */ fetchMany: function(references, owner) { if (!references.length) { return; } // Group By Type var referencesByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(references, function(reference) { referencesByTypeMap.get(reference.type).push(reference); }); forEach(referencesByTypeMap, function(type) { var references = referencesByTypeMap.get(type), ids = map(references, function(reference) { return reference.id; }); var adapter = this.adapterForType(type); Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany); adapter.findMany(this, type, ids, owner); }, this); }, hasReferenceForId: function(type, id) { id = coerceId(id); return !!this.typeMapFor(type).idToReference[id]; }, referenceForId: function(type, id) { id = coerceId(id); // Check to see if we have seen this type/id pair before. var reference = this.typeMapFor(type).idToReference[id]; // If not, create a reference for it but don't populate it // with any data yet. if (!reference) { reference = this.createReference(type, id); reference.data = UNLOADED; } return reference; }, /** @private `findMany` is the entry point that relationships use to generate a new `ManyArray` for the list of IDs specified by the server for the relationship. Its responsibilities are: * convert the IDs into clientIds * determine which of the clientIds still need to be loaded * create a new ManyArray whose content is *all* of the clientIds * notify the ManyArray of the number of its elements that are already loaded * insert the unloaded references into the `loadingRecordArrays` bookkeeping structure, which will allow the `ManyArray` to know when all of its loading elements are loaded from the server. * ask the adapter to load the unloaded elements, by invoking findMany with the still-unloaded IDs. */ findMany: function(type, idsOrReferencesOrOpaque, record, relationship) { // 1. Determine which of the client ids need to be loaded // 2. Create a new ManyArray whose content is ALL of the clientIds // 3. Decrement the ManyArray's counter by the number of loaded clientIds // 4. Put the ManyArray into our bookkeeping data structure, keyed on // the needed clientIds // 5. Ask the adapter to load the records for the unloaded clientIds (but // convert them back to ids) if (!Ember.isArray(idsOrReferencesOrOpaque)) { var adapter = this.adapterForType(type); if (adapter && adapter.findHasMany) { adapter.findHasMany(this, record, relationship, idsOrReferencesOrOpaque); } else if (idsOrReferencesOrOpaque !== undefined) { Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findHasMany`", adapter.findHasMany); } return this.recordArrayManager.createManyArray(type, Ember.A()); } // Coerce server IDs into Record Reference var references = map(idsOrReferencesOrOpaque, function(reference) { if (typeof reference !== 'object' && reference !== null) { return this.referenceForId(type, reference); } return reference; }, this); var unloadedReferences = this.unloadedReferences(references), manyArray = this.recordArrayManager.createManyArray(type, Ember.A(references)), reference, i, l; // Start the decrementing counter on the ManyArray at the number of // records we need to load from the adapter manyArray.loadingRecordsCount(unloadedReferences.length); if (unloadedReferences.length) { for (i=0, l=unloadedReferences.length; i<l; i++) { reference = unloadedReferences[i]; // keep track of the record arrays that a given loading record // is part of. This way, if the same record is in multiple // ManyArrays, all of their loading records counters will be // decremented when the adapter provides the data. this.recordArrayManager.registerWaitingRecordArray(manyArray, reference); } this.fetchMany(unloadedReferences, record); } else { // all requested records are available manyArray.set('isLoaded', true); Ember.run.once(function() { manyArray.trigger('didLoad'); }); } return manyArray; }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. @private @method findQuery @param {Class} type @param {Object} query an opaque query to be used by the adapter @return {DS.AdapterPopulatedRecordArray} */ findQuery: function(type, query) { var array = DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A([]), store: this }); var adapter = this.adapterForType(type); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); adapter.findQuery(this, type, query, array); return array; }, /** @private This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @param {Class} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { return this.fetchAll(type, this.all(type)); }, /** @private */ fetchAll: function(type, array) { var adapter = this.adapterForType(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); adapter.findAll(this, type, sinceToken); return array; }, /** */ metaForType: function(type, property, data) { var target = this.typeMapFor(type).metadata; set(target, property, data); }, /** */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. @method all @param {Class} type @return {DS.RecordArray} */ all: function(type) { var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = DS.RecordArray.create({ type: type, content: Ember.A([]), store: this, isLoaded: true }); this.recordArrayManager.registerFilteredRecordArray(array, type); typeMap.findAllCache = array; return array; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Note that the existence of a filter on a type will trigger immediate materialization of all loaded data for a given type, so you might not want to use filters for a type if you are loading many records into the store, many of which are not active at any given time. In this scenario, you might want to consider filtering the raw data before loading it into the store. @method filter @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ filter: function(type, query, filter) { // allow an optional server query if (arguments.length === 3) { this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A([]), store: this, manager: this.recordArrayManager, filterFunction: filter }); this.recordArrayManager.registerFilteredRecordArray(array, type, filter); return array; }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. @param {Class} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasReferenceForId(type, id)) { return false; } return typeof this.referenceForId(type, id).data === 'object'; }, // ............ // . UPDATING . // ............ /** @private If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @param {Class} type @param {Number|String} clientId @param {DS.Model} record */ dataWasUpdated: function(type, reference, record) { // Because data updates are invoked at the end of the run loop, // it is possible that a record might be deleted after its data // has been modified and this method was scheduled to be called. // // If that's the case, the record would have already been removed // from all record arrays; calling updateRecordArrays would just // add it back. If the record is deleted, just bail. It shouldn't // give us any more trouble after this. if (get(record, 'isDeleted')) { return; } if (typeof reference.data === "object") { this.recordArrayManager.referenceDidChange(reference); } }, // .............. // . PERSISTING . // .............. /** This method delegates saving to the store's implicit transaction. Calling this method is essentially a request to persist any changes to records that were not explicitly added to a transaction. */ save: function() { once(this, 'commitDefaultTransaction'); }, commit: Ember.aliasMethod('save'), commitDefaultTransaction: function() { get(this, 'defaultTransaction').commit(); }, scheduleSave: function(record) { get(this, 'currentTransaction').add(record); once(this, 'flushSavedRecords'); }, flushSavedRecords: function() { get(this, 'currentTransaction').commit(); set(this, 'currentTransaction', this.transaction()); }, /** Adapters should call this method if they would like to acknowledge that all changes related to a record (other than relationship changes) have persisted. Because relationship changes affect multiple records, the adapter is responsible for acknowledging the change to the relationship directly (using `store.didUpdateRelationship`) when all aspects of the relationship change have persisted. It can be called for created, deleted or updated records. If the adapter supplies new data, that data will become the new canonical data for the record. That will result in blowing away all local changes and rematerializing the record with the new data (the "sledgehammer" approach). Alternatively, if the adapter does not supply new data, the record will collapse all local changes into its saved data. Subsequent rollbacks of the record will roll back to this point. If an adapter is acknowledging receipt of a newly created record that did not generate an id in the client, it *must* either provide data or explicitly invoke `store.didReceiveId` with the server-provided id. Note that an adapter may not supply new data when acknowledging a deleted record. @see DS.Store#didUpdateRelationship @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { this.updateId(record, data); this.updateRecordData(record, data); } else { this.didUpdateAttributes(record); } record.adapterDidCommit(); }, /** For convenience, if an adapter is performing a bulk commit, it can also acknowledge all of the records at once. If the adapter supplies an array of data, they must be in the same order as the array of records passed in as the first parameter. @param {#forEach} list a list of records whose changes the adapter is acknowledging. You can pass any object that has an ES5-like `forEach` method, including the `OrderedSet` objects passed into the adapter at commit time. @param {Array[Object]} dataList an Array of data. This parameter must be an integer-indexed Array-like. */ didSaveRecords: function(list, dataList) { var i = 0; list.forEach(function(record) { this.didSaveRecord(record, dataList && dataList[i++]); }, this); }, /** This method allows the adapter to specify that a record could not be saved because it had backend-supplied validation errors. The errors object must have keys that correspond to the attribute names. Once each of the specified attributes have changed, the record will automatically move out of the invalid state and be ready to commit again. TODO: We should probably automate the process of converting server names to attribute names using the existing serializer infrastructure. @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method allows the adapter to specify that a record could not be saved because the server returned an unhandled error. @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** This is a lower-level API than `didSaveRecord` that allows an adapter to acknowledge the persistence of a single attribute. This is useful if an adapter needs to make multiple asynchronous calls to fully persist a record. The record will keep track of which attributes and relationships are still outstanding and automatically move into the `saved` state once the adapter has acknowledged everything. If a value is provided, it clobbers the locally specified value. Otherwise, the local value becomes the record's last known saved value (which is used when rolling back a record). Note that the specified attributeName is the normalized name specified in the definition of the `DS.Model`, not a key in the server-provided data. Also note that the adapter is responsible for performing any transformations on the value using the serializer API. @param {DS.Model} record @param {String} attributeName @param {Object} value */ didUpdateAttribute: function(record, attributeName, value) { record.adapterDidUpdateAttribute(attributeName, value); }, /** This method allows an adapter to acknowledge persistence of all attributes of a record but not relationships or other factors. It loops through the record's defined attributes and notifies the record that they are all acknowledged. This method does not take optional values, because the adapter is unlikely to have a hash of normalized keys and transformed values, and instead of building one up, it should just call `didUpdateAttribute` as needed. This method is intended as a middle-ground between `didSaveRecord`, which acknowledges all changes to a record, and `didUpdateAttribute`, which allows an adapter fine-grained control over updates. @param {DS.Model} record */ didUpdateAttributes: function(record) { record.eachAttribute(function(attributeName) { this.didUpdateAttribute(record, attributeName); }, this); }, /** This allows an adapter to acknowledge that it has saved all necessary aspects of a relationship change. This is separated from acknowledging the record itself (via `didSaveRecord`) because a relationship change can involve as many as three separate records. Records should only move out of the in-flight state once the server has acknowledged all of their relationships, and this differs based upon the adapter's semantics. There are three basic scenarios by which an adapter can save a relationship. ### Foreign Key An adapter can save all relationship changes by updating a foreign key on the child record. If it does this, it should acknowledge the changes when the child record is saved. record.eachRelationship(function(name, meta) { if (meta.kind === 'belongsTo') { store.didUpdateRelationship(record, name); } }); store.didSaveRecord(record, data); ### Embedded in Parent An adapter can save one-to-many relationships by embedding IDs (or records) in the parent object. In this case, the relationship is not considered acknowledged until both the old parent and new parent have acknowledged the change. In this case, the adapter should keep track of the old parent and new parent, and acknowledge the relationship change once both have acknowledged. If one of the two sides does not exist (e.g. the new parent does not exist because of nulling out the belongs-to relationship), the adapter should acknowledge the relationship once the other side has acknowledged. ### Separate Entity An adapter can save relationships as separate entities on the server. In this case, they should acknowledge the relationship as saved once the server has acknowledged the entity. @see DS.Store#didSaveRecord @param {DS.Model} record @param {DS.Model} relationshipName */ didUpdateRelationship: function(record, relationshipName) { var clientId = get(record, '_reference').clientId; var relationship = this.relationshipChangeFor(clientId, relationshipName); //TODO(Igor) if (relationship) { relationship.adapterDidUpdate(); } }, /** This allows an adapter to acknowledge all relationship changes for a given record. Like `didUpdateAttributes`, this is intended as a middle ground between `didSaveRecord` and fine-grained control via the `didUpdateRelationship` API. */ didUpdateRelationships: function(record) { var changes = this.relationshipChangesFor(get(record, '_reference')); for (var name in changes) { if (!changes.hasOwnProperty(name)) { continue; } changes[name].adapterDidUpdate(); } }, /** When acknowledging the creation of a locally created record, adapters must supply an id (if they did not implement `generateIdForRecord` to generate an id locally). If an adapter does not use `didSaveRecord` and supply a hash (for example, if it needs to make multiple HTTP requests to create and then update the record), it will need to invoke `didReceiveId` with the backend-supplied id. When not using `didSaveRecord`, an adapter will need to invoke: * didReceiveId (unless the id was generated locally) * didCreateRecord * didUpdateAttribute(s) * didUpdateRelationship(s) @param {DS.Model} record @param {Number|String} id */ didReceiveId: function(record, id) { var typeMap = this.typeMapFor(record.constructor), clientId = get(record, 'clientId'), oldId = get(record, 'id'); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === undefined || id === oldId); typeMap.idToCid[id] = clientId; this.clientIdToId[clientId] = id; }, /** @private This method re-indexes the data by its clientId in the store and then notifies the record that it should rematerialize itself. @param {DS.Model} record @param {Object} data */ updateRecordData: function(record, data) { get(record, '_reference').data = data; record.didChangeData(); }, /** @private If an adapter invokes `didSaveRecord` with data, this method extracts the id from the supplied data (using the adapter's `extractId()` method) and indexes the clientId with that id. @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var type = record.constructor, typeMap = this.typeMapFor(type), reference = get(record, '_reference'), oldId = get(record, 'id'), id = this.preprocessData(type, data); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); typeMap.idToReference[id] = reference; reference.id = id; }, /** @private This method receives opaque data provided by the adapter and preprocesses it, returning an ID. The actual preprocessing takes place in the adapter. If you would like to change the default behavior, you should override the appropriate hooks in `DS.Serializer`. @see {DS.Serializer} @return {String} id the id represented by the data */ preprocessData: function(type, data) { return this.adapterForType(type).extractId(type, data); }, /** @private Returns a map of IDs to client IDs for a given type. */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToReference: {}, references: [], metadata: {} }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** Load new data into the store for a given id and type combination. If data for that record had been loaded previously, the new information overwrites the old. If the record you are loading data for has outstanding changes that have not yet been saved, an exception will be thrown. @param {DS.Model} type @param {String|Number} id @param {Object} data the data to load */ load: function(type, data, prematerialized) { var id; if (typeof data === 'number' || typeof data === 'string') { id = data; data = prematerialized; prematerialized = null; } if (prematerialized && prematerialized.id) { id = prematerialized.id; } else if (id === undefined) { id = this.preprocessData(type, data); } id = coerceId(id); var reference = this.referenceForId(type, id); if (reference.record) { once(reference.record, 'loadedData'); } reference.data = data; reference.prematerialized = prematerialized; this.recordArrayManager.referenceDidChange(reference); return reference; }, loadMany: function(type, ids, dataList) { if (dataList === undefined) { dataList = ids; ids = map(dataList, function(data) { return this.preprocessData(type, data); }, this); } return map(ids, function(id, i) { return this.load(type, id, dataList[i]); }, this); }, loadHasMany: function(record, key, ids) { //It looks sad to have to do the conversion in the store var type = record.get(key + '.type'), tuples = map(ids, function(id) { return {id: id, type: type}; }); record.materializeHasMany(key, tuples); // Update any existing many arrays that use the previous IDs, // if necessary. record.hasManyDidChange(key); var relationship = record.cacheFor(key); // TODO (tomdale) this assumes that loadHasMany *always* means // that the records for the provided IDs are loaded. if (relationship) { set(relationship, 'isLoaded', true); relationship.trigger('didLoad'); } }, /** @private Creates a new reference for a given type & ID pair. Metadata about the record can be stored in the reference without having to create a full-blown DS.Model instance. @param {DS.Model} type @param {String|Number} id @returns {Reference} */ createReference: function(type, id) { var typeMap = this.typeMapFor(type), idToReference = typeMap.idToReference; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToReference[id]); var reference = { id: id, clientId: this.clientIdCounter++, type: type }; // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToReference[id] = reference; } typeMap.references.push(reference); return reference; }, // .......................... // . RECORD MATERIALIZATION . // .......................... materializeRecord: function(reference) { var record = reference.type._create({ id: reference.id, store: this, _reference: reference }); reference.record = record; get(this, 'defaultTransaction').adoptRecord(record); record.loadingData(); if (typeof reference.data === 'object') { record.loadedData(); } return record; }, dematerializeRecord: function(record) { var reference = get(record, '_reference'), type = reference.type, id = reference.id, typeMap = this.typeMapFor(type); record.updateRecordArrays(); if (id) { delete typeMap.idToReference[id]; } var loc = typeMap.references.indexOf(reference); typeMap.references.splice(loc, 1); }, willDestroy: function() { if (get(DS, 'defaultStore') === this) { set(DS, 'defaultStore', null); } }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, change) { var clientId = clientReference.clientId, parentClientId = parentReference ? parentReference.clientId : parentReference; var key = childKey + parentKey; var changes = this.relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, type) { var clientId = clientReference.clientId, parentClientId = parentReference ? parentReference.clientId : parentReference; var changes = this.relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, type) { var clientId = clientReference.clientId, parentClientId = parentReference ? parentReference.clientId : parentReference; var changes = this.relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId])){ return; } if(type){ return changes[clientId][parentClientId][key][type]; } else{ //TODO(Igor) what if both present return changes[clientId][parentClientId][key]["add"] || changes[clientId][parentClientId][key]["remove"]; } }, relationshipChangePairsFor: function(reference){ var toReturn = []; if( !reference ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this.relationshipChanges[reference.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, relationshipChangesFor: function(reference) { var toReturn = []; if( !reference ) { return toReturn; } var relationshipPairs = this.relationshipChangePairsFor(reference); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange){ toReturn.push(addedChange); } if(removedChange){ toReturn.push(removedChange); } }); return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... adapterForType: function(type) { this._adaptersMap = this.createInstanceMapFor('adapters'); var adapter = this._adaptersMap.get(type); if (adapter) { return adapter; } return this.get('_adapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. recordAttributeDidChange: function(reference, attributeName, newValue, oldValue) { var record = reference.record, dirtySet = new Ember.OrderedSet(), adapter = this.adapterForType(record.constructor); if (adapter.dirtyRecordsForAttributeChange) { adapter.dirtyRecordsForAttributeChange(dirtySet, record, attributeName, newValue, oldValue); } dirtySet.forEach(function(record) { record.adapterDidDirty(); }); }, recordBelongsToDidChange: function(dirtySet, child, relationship) { var adapter = this.adapterForType(child.constructor); if (adapter.dirtyRecordsForBelongsToChange) { adapter.dirtyRecordsForBelongsToChange(dirtySet, child, relationship); } // adapterDidDirty is called by the RelationshipChange that created // the dirtySet. }, recordHasManyDidChange: function(dirtySet, parent, relationship) { var adapter = this.adapterForType(parent.constructor); if (adapter.dirtyRecordsForHasManyChange) { adapter.dirtyRecordsForHasManyChange(dirtySet, parent, relationship); } // adapterDidDirty is called by the RelationshipChange that created // the dirtySet. } }); DS.Store.reopenClass({ registerAdapter: DS._Mappable.generateMapFunctionFor('adapters', function(type, adapter, map) { map.set(type, adapter); }), transformMapKey: function(key) { if (typeof key === 'string') { var transformedKey; transformedKey = get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, transformedKey); return transformedKey; } else { return key; } }, transformMapValue: function(key, value) { if (Ember.Object.detect(value)) { return value.create(); } return value; } }); })(); (function() { /** @module data @submodule data-model */ var get = Ember.get, set = Ember.set, once = Ember.run.once, arrayMap = Ember.ArrayPolyfills.map; /** This file encapsulates the various states that a record can transition through during its lifecycle. ### State Manager A record's state manager explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's state manager. How the state manager reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical. For example, a record can be in the `deleted.start` state, then transition into the `deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting its manager's current state path: record.get('stateManager.currentPath'); //=> "created.uncommitted" The `DS.Model` states are themselves stateless. What we mean is that, though each instance of a record also has a unique instance of a `DS.StateManager`, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each state manager points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass a reference to the current state manager as the first parameter to every method invoked on a state. The state manager passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. If you need access to the record being acted on, you can retrieve the state manager's `record` property. For example, if you had an event handler `myEvent`: myEvent: function(manager) { var record = manager.get('record'); record.doSomething(); } For more information about state managers in general, see the Ember.js documentation on `Ember.StateManager`. ### Events, Flags, and Transitions A state may implement zero or more events, flags, or transitions. #### Events Events are named functions that are invoked when sent to a record. The state manager will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with "+param); } }) To trigger this event: record.send('myEvent', 'foo'); //=> "Received myEvent with foo" Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the state manager's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * start <-- currentState * inFlight * updated * inFlight If we are currently in the `start` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } You can say: if (record.get('isNew') && record.get('isSaving')) { doSomething(); } If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. #### Transitions Transitions are like event handlers but are called automatically upon entering or exiting a state. To implement a transition, just call a method either `enter` or `exit`: myState: DS.State.create({ // Gets called automatically when entering // this state. enter: function(manager) { console.log("Entered myState"); } }) Note that enter and exit events are called once per transition. If the current state changes, but changes to another child state of the parent, the transition event on the parent will not be triggered. @class States @namespace DS @extends Ember.State */ var stateProperty = Ember.computed(function(key) { var parent = get(this, 'parentState'); if (parent) { return get(parent, key); } }).property(); var hasDefinedProperties = function(object) { for (var name in object) { if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didChangeData = function(manager) { var record = get(manager, 'record'); record.materializeData(); }; var willSetProperty = function(manager, context) { context.oldValue = get(get(manager, 'record'), context.name); var change = DS.AttributeChange.createChange(context); get(manager, 'record')._changesToSync[context.name] = change; }; var didSetProperty = function(manager, context) { var change = get(manager, 'record')._changesToSync[context.name]; change.value = get(get(manager, 'record'), context.name); change.sync(); }; DS.State = Ember.State.extend({ isLoading: stateProperty, isLoaded: stateProperty, isReloading: stateProperty, isDirty: stateProperty, isSaving: stateProperty, isDeleted: stateProperty, isError: stateProperty, isNew: stateProperty, isValid: stateProperty, // For states that are substates of a // DirtyState (updated or created), it is // useful to be able to determine which // type of dirty state it is. dirtyType: stateProperty }); // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record's transaction has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = DS.State.extend({ initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: DS.State.extend({ // EVENTS willSetProperty: willSetProperty, didSetProperty: didSetProperty, becomeDirty: Ember.K, willCommit: function(manager) { manager.transitionTo('inFlight'); }, becameClean: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.remove(record); }); manager.transitionTo('loaded.materializing'); }, becameInvalid: function(manager) { manager.transitionTo('invalid'); }, rollback: function(manager) { get(manager, 'record').rollback(); } }), // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: DS.State.extend({ // FLAGS isSaving: true, // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'); record.becameInFlight(); }, // EVENTS materializingData: function(manager) { set(manager, 'lastDirtyType', get(this, 'dirtyType')); manager.transitionTo('materializing'); }, didCommit: function(manager) { var dirtyType = get(this, 'dirtyType'), record = get(manager, 'record'); record.withTransaction(function(t) { t.remove(record); }); manager.transitionTo('saved'); manager.send('invokeLifecycleCallbacks', dirtyType); }, didChangeData: didChangeData, becameInvalid: function(manager, errors) { var record = get(manager, 'record'); set(record, 'errors', errors); manager.transitionTo('invalid'); manager.send('invokeLifecycleCallbacks'); }, becameError: function(manager) { manager.transitionTo('error'); manager.send('invokeLifecycleCallbacks'); } }), // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: DS.State.extend({ // FLAGS isValid: false, exit: function(manager) { var record = get(manager, 'record'); record.withTransaction(function (t) { t.remove(record); }); }, // EVENTS deleteRecord: function(manager) { manager.transitionTo('deleted'); get(manager, 'record').clearRelationships(); }, willSetProperty: willSetProperty, didSetProperty: function(manager, context) { var record = get(manager, 'record'), errors = get(record, 'errors'), key = context.name; set(errors, key, null); if (!hasDefinedProperties(errors)) { manager.send('becameValid'); } didSetProperty(manager, context); }, becomeDirty: Ember.K, rollback: function(manager) { manager.send('becameValid'); manager.send('rollback'); }, becameValid: function(manager) { manager.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('becameInvalid', record); } }) }); // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. var createdState = DirtyState.create({ dirtyType: 'created', // FLAGS isNew: true }); var updatedState = DirtyState.create({ dirtyType: 'updated' }); createdState.states.uncommitted.reopen({ deleteRecord: function(manager) { var record = get(manager, 'record'); record.clearRelationships(); manager.transitionTo('deleted.saved'); } }); createdState.states.uncommitted.reopen({ rollback: function(manager) { this._super(manager); manager.transitionTo('deleted.saved'); } }); updatedState.states.uncommitted.reopen({ deleteRecord: function(manager) { var record = get(manager, 'record'); manager.transitionTo('deleted'); record.clearRelationships(); } }); var states = { rootState: Ember.State.create({ // FLAGS isLoading: false, isLoaded: false, isReloading: false, isDirty: false, isSaving: false, isDeleted: false, isError: false, isNew: false, isValid: true, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: DS.State.create({ // EVENTS loadingData: function(manager) { manager.transitionTo('loading'); }, loadedData: function(manager) { manager.transitionTo('loaded.created'); } }), // A record enters this state when the store askes // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: DS.State.create({ // FLAGS isLoading: true, // EVENTS loadedData: didChangeData, materializingData: function(manager) { manager.transitionTo('loaded.materializing.firstTime'); }, becameError: function(manager) { manager.transitionTo('error'); manager.send('invokeLifecycleCallbacks'); } }), // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: DS.State.create({ initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES materializing: DS.State.create({ // EVENTS willSetProperty: Ember.K, didSetProperty: Ember.K, didChangeData: didChangeData, finishedMaterializing: function(manager) { manager.transitionTo('loaded.saved'); }, // SUBSTATES firstTime: DS.State.create({ // FLAGS isLoaded: false, exit: function(manager) { var record = get(manager, 'record'); once(function() { record.trigger('didLoad'); }); } }) }), reloading: DS.State.create({ // FLAGS isReloading: true, // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.reloadRecord(record); }, exit: function(manager) { var record = get(manager, 'record'); once(record, 'trigger', 'didReload'); }, // EVENTS loadedData: didChangeData, materializingData: function(manager) { manager.transitionTo('loaded.materializing'); } }), // If there are no local changes to a record, it remains // in the `saved` state. saved: DS.State.create({ // EVENTS willSetProperty: willSetProperty, didSetProperty: didSetProperty, didChangeData: didChangeData, loadedData: didChangeData, reloadRecord: function(manager) { manager.transitionTo('loaded.reloading'); }, materializingData: function(manager) { manager.transitionTo('loaded.materializing'); }, becomeDirty: function(manager) { manager.transitionTo('updated'); }, deleteRecord: function(manager) { manager.transitionTo('deleted'); get(manager, 'record').clearRelationships(); }, unloadRecord: function(manager) { var record = get(manager, 'record'); // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); manager.transitionTo('deleted.saved'); }, didCommit: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.remove(record); }); manager.send('invokeLifecycleCallbacks', get(manager, 'lastDirtyType')); }, invokeLifecycleCallbacks: function(manager, dirtyType) { var record = get(manager, 'record'); if (dirtyType === 'created') { record.trigger('didCreate', record); } else { record.trigger('didUpdate', record); } record.trigger('didCommit', record); } }), // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }), // A record is in this state if it was deleted from the store. deleted: DS.State.create({ initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.recordArrayManager.remove(record); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record's // transaction starts to commit. uncommitted: DS.State.create({ // EVENTS willCommit: function(manager) { manager.transitionTo('inFlight'); }, rollback: function(manager) { get(manager, 'record').rollback(); }, becomeDirty: Ember.K, becameClean: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.remove(record); }); manager.transitionTo('loaded.materializing'); } }), // After a record's transaction is committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: DS.State.create({ // FLAGS isSaving: true, // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'); record.becameInFlight(); }, // EVENTS didCommit: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.remove(record); }); manager.transitionTo('saved'); manager.send('invokeLifecycleCallbacks'); } }), // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: DS.State.create({ // FLAGS isDirty: false, setup: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('didDelete', record); record.trigger('didCommit', record); } }) }), // If the adapter indicates that there was an unknown // error saving a record, the record enters the `error` // state. error: DS.State.create({ isError: true, // EVENTS invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('becameError', record); } }) }) }; DS.StateManager = Ember.StateManager.extend({ record: null, initialState: 'rootState', states: states, unhandledEvent: function(manager, originalEvent) { var record = manager.get('record'), contexts = [].slice.call(arguments, 2), errorMessage; errorMessage = "Attempted to handle event `" + originalEvent + "` "; errorMessage += "on " + record.toString() + " while in state "; errorMessage += get(manager, 'currentState.path') + ". Called with "; errorMessage += arrayMap.call(contexts, function(context){ return Ember.inspect(context); }).join(', '); throw new Ember.Error(errorMessage); } }); })(); (function() { var LoadPromise = DS.LoadPromise; // system/mixins/load_promise var get = Ember.get, set = Ember.set, map = Ember.EnumerableUtils.map; var retrieveFromCurrentState = Ember.computed(function(key, value) { return get(get(this, 'stateManager.currentState'), key); }).property('stateManager.currentState').readOnly(); /** The model class that all Ember Data records descend from. @module data @submodule data-model @main data-model @class Model @namespace DS @extends Ember.Object @constructor */ DS.Model = Ember.Object.extend(Ember.Evented, LoadPromise, { isLoading: retrieveFromCurrentState, isLoaded: retrieveFromCurrentState, isReloading: retrieveFromCurrentState, isDirty: retrieveFromCurrentState, isSaving: retrieveFromCurrentState, isDeleted: retrieveFromCurrentState, isError: retrieveFromCurrentState, isNew: retrieveFromCurrentState, isValid: retrieveFromCurrentState, dirtyType: retrieveFromCurrentState, clientId: null, id: null, transaction: null, stateManager: null, errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. @method serialize @param {Object} options Available options: * `includeId`: `true` if the record's ID should be included in the JSON representation. @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use {{#crossLink "DS.JSONSerializer"}}DS.JSONSerializer{{/crossLink}} to get the JSON representation of a record. @method toJSON @param {Object} options Available options: * `includeId`: `true` if the record's ID should be included in the JSON representation. @returns {Object} A JSON representation of the object. */ toJSON: function(options) { var serializer = DS.JSONSerializer.create(); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is reloaded from the server. @event didReload */ didReload: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, data: Ember.computed(function() { if (!this._data) { this.setupData(); } return this._data; }).property(), materializeData: function() { this.send('materializingData'); get(this, 'store').materializeData(this); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, _data: null, init: function() { this._super(); var stateManager = DS.StateManager.create({ record: this }); set(this, 'stateManager', stateManager); this._setup(); stateManager.goToState('empty'); }, _setup: function() { this._changesToSync = {}; }, send: function(name, context) { return get(this, 'stateManager').send(name, context); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, loadingData: function() { this.send('loadingData'); }, loadedData: function() { this.send('loadedData'); }, didChangeData: function() { this.send('didChangeData'); }, deleteRecord: function() { this.send('deleteRecord'); }, unloadRecord: function() { Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty')); this.send('unloadRecord'); }, clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { this.clearHasMany(relationship); } }, this); }, updateRecordArrays: function() { var store = get(this, 'store'); if (store) { store.dataWasUpdated(this.constructor, get(this, '_reference'), this); } }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. */ adapterDidCommit: function() { var attributes = get(this, 'data').attributes; get(this.constructor, 'attributes').forEach(function(name, meta) { attributes[name] = get(this, name); }, this); this.send('didCommit'); this.updateRecordArraysLater(); }, adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); this.send('finishedMaterializing'); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var cachedValue = this.cacheFor(key); if (cachedValue) { var type = get(this.constructor, 'relationshipsByName').get(key).type; var store = get(this, 'store'); var ids = this._data.hasMany[key] || []; var references = map(ids, function(id) { if (typeof id === 'object') { if( id.clientId ) { // if it was already a reference, return the reference return id; } else { // <id, type> tuple for a polymorphic association. return store.referenceForId(id.type, id.id); } } return store.referenceForId(type, id); }); set(cachedValue, 'content', Ember.A(references)); } }, updateRecordArraysLater: function() { Ember.run.once(this, this.updateRecordArrays); }, setupData: function() { this._data = { attributes: {}, belongsTo: {}, hasMany: {}, id: null }; }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); this._data.attributes = attributes; }, materializeAttribute: function(name, value) { this._data.attributes[name] = value; }, materializeHasMany: function(name, tuplesOrReferencesOrOpaque) { var tuplesOrReferencesOrOpaqueType = typeof tuplesOrReferencesOrOpaque; if (tuplesOrReferencesOrOpaque && tuplesOrReferencesOrOpaqueType !== 'string' && tuplesOrReferencesOrOpaque.length > 1) { Ember.assert('materializeHasMany expects tuples, references or opaque token, not ' + tuplesOrReferencesOrOpaque[0], tuplesOrReferencesOrOpaque[0].hasOwnProperty('id') && tuplesOrReferencesOrOpaque[0].type); } if( tuplesOrReferencesOrOpaqueType === "string" ) { this._data.hasMany[name] = tuplesOrReferencesOrOpaque; } else { var references = tuplesOrReferencesOrOpaque; if (tuplesOrReferencesOrOpaque && Ember.isArray(tuplesOrReferencesOrOpaque)) { references = this._convertTuplesToReferences(tuplesOrReferencesOrOpaque); } this._data.hasMany[name] = references; } }, materializeBelongsTo: function(name, tupleOrReference) { if (tupleOrReference) { Ember.assert('materializeBelongsTo expects a tuple or a reference, not a ' + tupleOrReference, !tupleOrReference || (tupleOrReference.hasOwnProperty('id') && tupleOrReference.hasOwnProperty('type'))); } this._data.belongsTo[name] = tupleOrReference; }, _convertTuplesToReferences: function(tuplesOrReferences) { return map(tuplesOrReferences, function(tupleOrReference) { return this._convertTupleToReference(tupleOrReference); }, this); }, _convertTupleToReference: function(tupleOrReference) { var store = get(this, 'store'); if(tupleOrReference.clientId) { return tupleOrReference; } else { return store.referenceForId(tupleOrReference.type, tupleOrReference.id); } }, rollback: function() { this._setup(); this.send('becameClean'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** @private The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, becameInFlight: function() { }, /** @private */ resolveOn: function(successEvent) { var model = this; return new Ember.RSVP.Promise(function(resolve, reject) { function success() { this.off('becameError', error); this.off('becameInvalid', error); resolve(this); } function error() { this.off(successEvent, success); reject(this); } model.one(successEvent, success); model.one('becameError', error); model.one('becameInvalid', error); }); }, /** Save the record. @method save */ save: function() { this.get('store').scheduleSave(this); return this.resolveOn('didCommit'); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). @method reload */ reload: function() { this.send('reloadRecord'); return this.resolveOn('didReload'); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { get(this, 'data.attributes')[attributeName] = value; this.notifyPropertyChange(attributeName); } else { value = get(this, attributeName); get(this, 'data.attributes')[attributeName] = value; } this.updateRecordArraysLater(); }, adapterDidInvalidate: function(errors) { this.send('becameInvalid', errors); }, adapterDidError: function() { this.send('becameError'); }, /** @private Override the default event firing from Ember.Evented to also call methods with the given name. */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); } }); // Helper function to generate store aliases. // This returns a function that invokes the named alias // on the default store, but injects the class as the // first parameter. var storeAlias = function(methodName) { return function() { var store = get(DS, 'defaultStore'), args = [].slice.call(arguments); args.unshift(this); Ember.assert("Your application does not have a 'Store' property defined. Attempts to call '" + methodName + "' on model classes will fail. Please provide one as with 'YourAppName.Store = DS.Store.extend()'", !!store); return store[methodName].apply(store, args); }; }; DS.Model.reopenClass({ /** @private Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. */ _create: DS.Model.create, /** @private Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set."); }, /** See {{#crossLink "DS.Store/find:method"}}`DS.Store.find()`{{/crossLink}}. @method find @param {Object|String|Array|null} query A query to find records by. */ find: storeAlias('find'), /** See {{#crossLink "DS.Store/all:method"}}`DS.Store.all()`{{/crossLink}}. @method all @return {DS.RecordArray} */ all: storeAlias('all'), /** See {{#crossLink "DS.Store/findQuery:method"}}`DS.Store.findQuery()`{{/crossLink}}. @method query @param {Object} query an opaque query to be used by the adapter @return {DS.AdapterPopulatedRecordArray} */ query: storeAlias('findQuery'), /** See {{#crossLink "DS.Store/filter:method"}}`DS.Store.filter()`{{/crossLink}}. @method filter @param {Function} filter @return {DS.FilteredRecordArray} */ filter: storeAlias('filter'), /** See {{#crossLink "DS.Store/createRecord:method"}}`DS.Store.createRecord()`{{/crossLink}}. @method createRecord @param {Object} properties a hash of properties to set on the newly created record. @returns DS.Model */ createRecord: storeAlias('createRecord') }); })(); (function() { /** @module data @submodule data-model */ var get = Ember.get; DS.Model.reopenClass({ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }) }); DS.Model.reopen({ eachAttribute: function(callback, binding) { get(this.constructor, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, attributeWillChange: Ember.beforeObserver(function(record, key) { var reference = get(record, '_reference'), store = get(record, 'store'); record.send('willSetProperty', { reference: reference, store: store, name: key }); }), attributeDidChange: Ember.observer(function(record, key) { record.send('didSetProperty', { name: key }); }) }); function getAttr(record, options, key) { var attributes = get(record, 'data').attributes; var value = attributes[key]; if (value === undefined) { if (typeof options.defaultValue === "function") { value = options.defaultValue(); } else { value = options.defaultValue; } } return value; } DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value, oldValue) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); } else { value = getAttr(this, options, key); } return value; // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { /** @module data @submodule data-model */ })(); (function() { /** An AttributeChange object is created whenever a record's attribute changes value. It is used to track changes to a record between transaction commits. */ var AttributeChange = DS.AttributeChange = function(options) { this.reference = options.reference; this.store = options.store; this.name = options.name; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { this.store.recordAttributeDidChange(this.reference, this.name, this.value, this.oldValue); // TODO: Use this object in the commit process this.destroy(); }, /** If the AttributeChange is destroyed (either by being rolled back or being committed), remove it from the list of pending changes on the record. */ destroy: function() { var record = this.reference.record; delete record._changesToSync[this.name]; } }; })(); (function() { var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; DS.RelationshipChange = function(options) { this.parentReference = options.parentReference; this.childReference = options.childReference; this.firstRecordReference = options.firstRecordReference; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecordReference = options.secondRecordReference; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; /** @private */ DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; /** @private */ DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; /** @private */ DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecordReference, secondRecordReference, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecordReference.type, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecordReference, firstRecordReference, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); } }; /** @private */ DS.OneToNoneChange.createChange = function(childReference, parentReference, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.ManyToNoneChange.createChange = function(childReference, parentReference, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: childReference, childReference: parentReference, secondRecordReference: childReference, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.ManyToManyChange.createChange = function(childReference, parentReference, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.OneToOneChange.createChange = function(childReference, parentReference, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childReference, key){ if (options.changeType === "add" && store.recordIsMaterialized(childReference)) { var child = store.recordForReference(childReference); var oldParent = get(child, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childReference, oldParent.get('_reference'), store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childReference, key, options.parentReference , null, correspondingChange); correspondingChange.sync(); } } }; /** @private */ DS.OneToManyChange.createChange = function(childReference, parentReference, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childReference, key ); } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, change.getSecondRecordName(), change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childReference, key){ var child = childReference.record; if (options.changeType === "add" && child) { var oldParent = get(child, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childReference, oldParent.get('_reference'), store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childReference, key, options.parentReference, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.ensureSameTransaction = function(changes){ var records = Ember.A(); forEach(changes, function(change){ records.addObject(change.getSecondRecord()); records.addObject(change.getFirstRecord()); }); return DS.Transaction.ensureSameTransaction(records); }; DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecordReference; if (!parent) { return; } var childType = this.firstRecordReference.type; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @private */ destroy: function() { var childReference = this.childReference, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childReference, belongsToName, this.parentReference, hasManyName, this.changeType); }, /** @private */ getByReference: function(reference) { // return null or undefined if the original reference was null or undefined if (!reference) { return reference; } if (reference.record) { return reference.record; } }, getSecondRecord: function(){ return this.getByReference(this.secondRecordReference); }, /** @private */ getFirstRecord: function() { return this.getByReference(this.firstRecordReference); }, /** @private Make sure that all three parts of the relationship change are part of the same transaction. If any of the three records is clean and in the default transaction, and the rest are in a different transaction, move them all into that transaction. */ ensureSameTransaction: function() { var child = this.getFirstRecord(), parentRecord = this.getSecondRecord(); var transaction = DS.Transaction.ensureSameTransaction([child, parentRecord]); this.transaction = transaction; return transaction; }, callChangeEvents: function(){ var child = this.getFirstRecord(), parentRecord = this.getSecondRecord(); var dirtySet = new Ember.OrderedSet(); // TODO: This implementation causes a race condition in key-value // stores. The fix involves buffering changes that happen while // a record is loading. A similar fix is required for other parts // of ember-data, and should be done as new infrastructure, not // a one-off hack. [tomhuda] if (parentRecord && get(parentRecord, 'isLoaded')) { this.store.recordHasManyDidChange(dirtySet, parentRecord, this); } if (child) { this.store.recordBelongsToDidChange(dirtySet, child, this); } dirtySet.forEach(function(record) { record.adapterDidDirty(); }); }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecordReference); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); this.ensureSameTransaction(); this.callChangeEvents(); if (secondRecord && firstRecord) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ get(secondRecord, secondRecordName).addObject(firstRecord); }); } } if (firstRecord && secondRecord && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ get(firstRecord, firstRecordName).addObject(secondRecord); }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); this.ensureSameTransaction(firstRecord, secondRecord, secondRecordName, firstRecordName); this.callChangeEvents(); if (secondRecord && firstRecord) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ get(secondRecord, secondRecordName).removeObject(firstRecord); }); } } if (firstRecord && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ get(firstRecord, firstRecordName).removeObject(secondRecord); }); } } this.coalesce(); }; })(); (function() { /** @module data @submodule data-changes */ })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; DS.belongsTo = function(type, options) { Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; return Ember.computed(function(key, value) { if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } if (arguments.length === 2) { Ember.assert("You can only add a record of " + type.toString() + " to this relationship", !value || type.detectInstance(value)); return value === undefined ? null : value; } var data = get(this, 'data').belongsTo, store = get(this, 'store'), belongsTo; belongsTo = data[key]; // TODO (tomdale) The value of the belongsTo in the data hash can be // one of: // 1. null/undefined // 2. a record reference // 3. a tuple returned by the serializer's polymorphism code // // We should really normalize #3 to be the same as #2 to reduce the // complexity here. if (isNone(belongsTo)) { return null; } // The data has been normalized to a record reference, so // just ask the store for the record for that reference, // materializing it if necessary. if (belongsTo.clientId) { return store.recordForReference(belongsTo); } // The data has been normalized into a type/id pair by the // serializer's polymorphism code. return store.findById(belongsTo.type, belongsTo.id); }).property('data').meta(meta); }; /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ DS.Model.reopen({ /** @private */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); var childReference = get(record, '_reference'), store = get(record, 'store'); if (oldParent){ var change = DS.RelationshipChange.createChange(childReference, get(oldParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @private */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if(newParent){ var childReference = get(record, '_reference'), store = get(record, 'store'); var change = DS.RelationshipChange.createChange(childReference, get(newParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "add" }); change.sync(); if(this._changesToSync[key]){ DS.OneToManyChange.ensureSameTransaction([change, this._changesToSync[key]], store); } } } delete this._changesToSync[key]; }) }); })(); (function() { var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; var hasRelationship = function(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; return Ember.computed(function(key, value) { var data = get(this, 'data').hasMany, store = get(this, 'store'), ids, relationship; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } //ids can be references or opaque token //(e.g. `{url: '/relationship'}`) that will be passed to the adapter ids = data[key]; relationship = store.findMany(type, ids, this, meta); set(relationship, 'owner', this); set(relationship, 'name', key); set(relationship, 'isPolymorphic', options.polymorphic); return relationship; }).property().meta(meta); }; DS.hasMany = function(type, options) { Ember.assert("The type passed to DS.hasMany must be defined", !!type); return hasRelationship(type, options); }; function clearUnmaterializedHasMany(record, relationship) { var data = get(record, 'data').hasMany; var references = data[relationship.key]; if (!references) { return; } var inverse = record.constructor.inverseFor(relationship.key); if (inverse) { forEach(references, function(reference) { var childRecord; if (childRecord = reference.record) { record.suspendRelationshipObservers(function() { set(childRecord, inverse.name, null); }); } }); } } DS.Model.reopen({ clearHasMany: function(relationship) { var hasMany = this.cacheFor(relationship.name); if (hasMany) { hasMany.clear(); } else { clearUnmaterializedHasMany(this, relationship); } } }); })(); (function() { var get = Ember.get, set = Ember.set; /** @private This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ DS.Model.reopen({ // This Ember.js hook allows an object to be notified when a property // is defined. // // In this case, we use it to be notified when an Ember Data user defines a // belongs-to relationship. In that case, we need to set up observers for // each one, allowing us to track relationship changes and automatically // reflect changes in the inverse has-many array. // // This hook passes the class being set up, as well as the key and value // being defined. So, for example, when the user does this: // // DS.Model.extend({ // parent: DS.belongsTo(App.User) // }); // // This hook would be called with "parent" as the key and the computed // property returned by `DS.belongsTo` as the value. didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } if (meta.isAttribute) { Ember.addObserver(proto, key, null, 'attributeDidChange'); Ember.addBeforeObserver(proto, key, null, 'attributeWillChange'); } meta.parentType = proto.constructor; } } }); /** These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: App.Post = DS.Model.extend({ comments: DS.hasMany(App.Comment) }); Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ".", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This computed property would return a map describing these relationships, like this: var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = Ember.get(Ember.lookup, meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A([]); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); meta.type = type; } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { /** @module data @submodule data-relationships */ })(); (function() { var get = Ember.get, set = Ember.set; var once = Ember.run.once; var forEach = Ember.EnumerableUtils.forEach; DS.RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedReferences = []; }, referenceDidChange: function(reference) { this.changedReferences.push(reference); once(this, this.updateRecordArrays); }, recordArraysForReference: function(reference) { reference.recordArrays = reference.recordArrays || Ember.OrderedSet.create(); return reference.recordArrays; }, /** @private This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when an attribute changes on a record. It updates all filters that a record belongs to. To avoid thrashing, it only runs once per run loop per record. @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedReferences, function(reference) { var type = reference.type, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, reference); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = reference.loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } reference.loadingRecordArrays = []; } }, this); this.changedReferences = []; }, /** @private Update an individual filter. @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, reference) { var shouldBeInArray, record; if (!filter) { shouldBeInArray = true; } else { record = this.store.recordForReference(reference); shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForReference(reference); if (shouldBeInArray) { recordArrays.add(array); array.addReference(reference); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeReference(reference); } }, /** @private When a record is deleted, it is removed from all its record arrays. @param {DS.Model} record */ remove: function(record) { var reference = get(record, '_reference'); var recordArrays = reference.recordArrays || []; recordArrays.forEach(function(array) { array.removeReference(reference); }); }, /** @private This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), references = typeMap.references, reference, data, shouldFilter, record; for (var i=0, l=references.length; i<l; i++) { reference = references[i]; shouldFilter = false; data = reference.data; if (typeof data === 'object') { if (record = reference.record) { if (!get(record, 'isDeleted')) { shouldFilter = true; } } else { shouldFilter = true; } if (shouldFilter) { this.updateRecordArray(array, filter, type, reference); } } } }, /** @private Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, references) { var manyArray = DS.ManyArray.create({ type: type, content: references, store: this.store }); references.forEach(function(reference) { var arrays = this.recordArraysForReference(reference); arrays.add(manyArray); }, this); return manyArray; }, /** @private Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(array, reference) { var loadingRecordArrays = reference.loadingRecordArrays || []; loadingRecordArrays.push(array); reference.loadingRecordArrays = loadingRecordArrays; } }); })(); (function() { var get = Ember.get, set = Ember.set, map = Ember.ArrayPolyfills.map, isNone = Ember.isNone; function mustImplement(name) { return function() { throw new Ember.Error("Your serializer " + this.toString() + " does not implement the required method " + name); }; } /** A serializer is responsible for serializing and deserializing a group of records. `DS.Serializer` is an abstract base class designed to help you build a serializer that can read to and write from any serialized form. While most applications will use `DS.JSONSerializer`, which reads and writes JSON, the serializer architecture allows your adapter to transmit things like XML, strings, or custom binary data. Typically, your application's `DS.Adapter` is responsible for both creating a serializer as well as calling the appropriate methods when it needs to materialize data or serialize a record. The serializer API is designed as a series of layered hooks that you can override to customize any of the individual steps of serialization and deserialization. The hooks are organized by the three responsibilities of the serializer: 1. Determining naming conventions 2. Serializing records into a serialized form 3. Deserializing records from a serialized form Because Ember Data lazily materializes records, the deserialization step, and therefore the hooks you implement, are split into two phases: 1. Extraction, where the serialized forms for multiple records are extracted from a single payload. The IDs of each record are also extracted for indexing. 2. Materialization, where a newly-created record has its attributes and relationships initialized based on the serialized form loaded by the adapter. Additionally, a serializer can convert values from their JavaScript versions into their serialized versions via a declarative API. ## Naming Conventions One of the most common uses of the serializer is to map attribute names from the serialized form to your `DS.Model`. For example, in your model, you may have an attribute called `firstName`: ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string') }); ``` However, because the web API your adapter is communicating with is legacy, it calls this attribute `FIRST_NAME`. You can determine the attribute name used in the serialized form by implementing `keyForAttributeName`: ```javascript keyForAttributeName: function(type, name) { return name.underscore.toUpperCase(); } ``` If your attribute names are not predictable, you can re-map them one-by-one using the adapter's `map` API: ```javascript App.Adapter.map('App.Person', { firstName: { key: '*API_USER_FIRST_NAME*' } }); ``` This API will also work for relationships and primary keys. For example: ```javascript App.Adapter.map('App.Person', { primaryKey: '_id' }); ``` ## Serialization During the serialization process, a record or records are converted from Ember.js objects into their serialized form. These methods are designed in layers, like a delicious 7-layer cake (but with fewer layers). The main entry point for serialization is the `serialize` method, which takes the record and options. The `serialize` method is responsible for: * turning the record's attributes (`DS.attr`) into attributes on the JSON object. * optionally adding the record's ID onto the hash * adding relationships (`DS.hasMany` and `DS.belongsTo`) to the JSON object. Depending on the backend, the serializer can choose whether to include the `hasMany` or `belongsTo` relationships on the JSON hash. For very custom serialization, you can implement your own `serialize` method. In general, however, you will want to override the hooks described below. ### Adding the ID The default `serialize` will optionally call your serializer's `addId` method with the JSON hash it is creating, the record's type, and the record's ID. The `serialize` method will not call `addId` if the record's ID is undefined. Your adapter must specifically request ID inclusion by passing `{ includeId: true }` as an option to `serialize`. NOTE: You may not want to include the ID when updating an existing record, because your server will likely disallow changing an ID after it is created, and the PUT request itself will include the record's identification. By default, `addId` will: 1. Get the primary key name for the record by calling the serializer's `primaryKey` with the record's type. Unless you override the `primaryKey` method, this will be `'id'`. 2. Assign the record's ID to the primary key in the JSON hash being built. If your backend expects a JSON object with the primary key at the root, you can just override the `primaryKey` method on your serializer subclass. Otherwise, you can override the `addId` method for more specialized handling. ### Adding Attributes By default, the serializer's `serialize` method will call `addAttributes` with the JSON object it is creating and the record to serialize. The `addAttributes` method will then call `addAttribute` in turn, with the JSON object, the record to serialize, the attribute's name and its type. Finally, the `addAttribute` method will serialize the attribute: 1. It will call `keyForAttributeName` to determine the key to use in the JSON hash. 2. It will get the value from the record. 3. It will call `serializeValue` with the attribute's value and attribute type to convert it into a JSON-compatible value. For example, it will convert a Date into a String. If your backend expects a JSON object with attributes as keys at the root, you can just override the `serializeValue` and `keyForAttributeName` methods in your serializer subclass and let the base class do the heavy lifting. If you need something more specialized, you can probably override `addAttribute` and let the default `addAttributes` handle the nitty gritty. ### Adding Relationships By default, `serialize` will call your serializer's `addRelationships` method with the JSON object that is being built and the record being serialized. The default implementation of this method is to loop over all of the relationships defined on your record type and: * If the relationship is a `DS.hasMany` relationship, call `addHasMany` with the JSON object, the record and a description of the relationship. * If the relationship is a `DS.belongsTo` relationship, call `addBelongsTo` with the JSON object, the record and a description of the relationship. The relationship description has the following keys: * `type`: the class of the associated information (the first parameter to `DS.hasMany` or `DS.belongsTo`) * `kind`: either `hasMany` or `belongsTo` The relationship description may get additional information in the future if more capabilities or relationship types are added. However, it will remain backwards-compatible, so the mere existence of new features should not break existing adapters. @module data @submodule data-serializer @main data-serializer @class Serializer @namespace DS @extends Ember.Object @constructor */ DS.Serializer = Ember.Object.extend({ init: function() { this.mappings = Ember.Map.create(); this.aliases = Ember.Map.create(); this.configurations = Ember.Map.create(); this.globalConfigurations = {}; }, extract: mustImplement('extract'), extractMany: mustImplement('extractMany'), extractId: mustImplement('extractId'), extractAttribute: mustImplement('extractAttribute'), extractHasMany: mustImplement('extractHasMany'), extractBelongsTo: mustImplement('extractBelongsTo'), extractRecordRepresentation: function(loader, type, data, shouldSideload) { var prematerialized = {}, reference; if (shouldSideload) { reference = loader.sideload(type, data); } else { reference = loader.load(type, data); } this.eachEmbeddedHasMany(type, function(name, relationship) { var embeddedData = this.extractEmbeddedData(data, this.keyFor(relationship)); if (!isNone(embeddedData)) { this.extractEmbeddedHasMany(loader, relationship, embeddedData, reference, prematerialized); } }, this); this.eachEmbeddedBelongsTo(type, function(name, relationship) { var embeddedData = this.extractEmbeddedData(data, this.keyFor(relationship)); if (!isNone(embeddedData)) { this.extractEmbeddedBelongsTo(loader, relationship, embeddedData, reference, prematerialized); } }, this); loader.prematerialize(reference, prematerialized); return reference; }, extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) { var references = map.call(array, function(item) { if (!item) { return; } var foundType = this.extractEmbeddedType(relationship, item), reference = this.extractRecordRepresentation(loader, foundType, item, true); // If the embedded record should also be saved back when serializing the parent, // make sure we set its parent since it will not have an ID. var embeddedType = this.embeddedType(parent.type, relationship.key); if (embeddedType === 'always') { reference.parent = parent; } // If the embedded children have an inverse belongs-to, set the // inverse to the current record in their prematerialized data. var parentType = relationship.parentType, inverse = parentType.inverseFor(relationship.key); if (inverse) { var inverseName = inverse.name; reference.prematerialized[inverseName] = parent; } return reference; }, this); prematerialized[relationship.key] = references; }, extractEmbeddedBelongsTo: function(loader, relationship, data, parent, prematerialized) { var foundType = this.extractEmbeddedType(relationship, data), reference = this.extractRecordRepresentation(loader, foundType, data, true); prematerialized[relationship.key] = reference; // If the embedded record should also be saved back when serializing the parent, // make sure we set its parent since it will not have an ID. var embeddedType = this.embeddedType(parent.type, relationship.key); if (embeddedType === 'always') { reference.parent = parent; } }, /** A hook you can use to customize how the record's type is extracted from the serialized data. The `extractEmbeddedType` hook is called with: * the relationship * the serialized representation of the record By default, it returns the type of the relationship. @method extractEmbeddedType @param {Object} relationship an object representing the relationship @param {any} data the serialized representation of the record */ extractEmbeddedType: function(relationship, data) { return relationship.type; }, /** A hook you need to implement in order to extract the data associated with an embedded record. @param {any} data the serialized representation of the record @param {String} key the key that represents the embedded record */ extractEmbeddedData: mustImplement(), //....................... //. SERIALIZATION HOOKS //....................... /** The main entry point for serializing a record. While you can consider this a hook that can be overridden in your serializer, you will have to manually handle serialization. For most cases, there are more granular hooks that you can override. If overriding this method, these are the responsibilities that you will need to implement yourself: * If the option hash contains `includeId`, add the record's ID to the serialized form. By default, `serialize` calls `addId` if appropriate. * If the option hash contains `includeType`, add the record's type to the serialized form. * Add the record's attributes to the serialized form. By default, `serialize` calls `addAttributes`. * Add the record's relationships to the serialized form. By default, `serialize` calls `addRelationships`. @method serialize @param {DS.Model} record the record to serialize @param {Object} [options] a hash of options @returns {any} the serialized form of the record */ serialize: function(record, options) { options = options || {}; var serialized = this.createSerializedForm(), id; if (options.includeId) { if (id = get(record, 'id')) { this._addId(serialized, record.constructor, id); } } if (options.includeType) { this.addType(serialized, record.constructor); } this.addAttributes(serialized, record); this.addRelationships(serialized, record); return serialized; }, /** @private Given an attribute type and value, convert the value into the serialized form using the transform registered for that type. @method serializeValue @param {any} value the value to convert to the serialized form @param {String} attributeType the registered type (e.g. `string` or `boolean`) @returns {any} the serialized form of the value */ serializeValue: function(value, attributeType) { var transform = this.transforms ? this.transforms[attributeType] : null; Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform); return transform.serialize(value); }, /** A hook you can use to normalize IDs before adding them to the serialized representation. Because the store coerces all IDs to strings for consistency, this is the opportunity for the serializer to, for example, convert numerical IDs back into number form. @param {String} id the id from the record @returns {any} the serialized representation of the id */ serializeId: function(id) { if (isNaN(id)) { return id; } return +id; }, /** A hook you can use to change how attributes are added to the serialized representation of a record. By default, `addAttributes` simply loops over all of the attributes of the passed record, maps the attribute name to the key for the serialized form, and invokes any registered transforms on the value. It then invokes the more granular `addAttribute` with the key and transformed value. Since you can override `keyForAttributeName`, `addAttribute`, and register custom transforms, you should rarely need to override this hook. @method addAttributes @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize */ addAttributes: function(data, record) { record.eachAttribute(function(name, attribute) { this._addAttribute(data, record, name, attribute.type); }, this); }, /** A hook you can use to customize how the key/value pair is added to the serialized data. @method addAttribute @param {any} serialized the serialized form being built @param {String} key the key to add to the serialized data @param {any} value the value to add to the serialized data */ addAttribute: mustImplement('addAttribute'), /** A hook you can use to customize how the record's id is added to the serialized data. The `addId` hook is called with: * the serialized representation being built * the resolved primary key (taking configurations and the `primaryKey` hook into consideration) * the serialized id (after calling the `serializeId` hook) @method addId @param {any} data the serialized representation that is being built @param {String} key the resolved primary key @param {id} id the serialized id */ addId: mustImplement('addId'), /** A hook you can use to customize how the record's type is added to the serialized data. The `addType` hook is called with: * the serialized representation being built * the serialized id (after calling the `serializeId` hook) @method addType @param {any} data the serialized representation that is being built @param {DS.Model subclass} type the type of the record */ addType: Ember.K, /** Creates an empty hash that will be filled in by the hooks called from the `serialize()` method. @method createSerializedForm @return {Object} */ createSerializedForm: function() { return {}; }, /** A hook you can use to change how relationships are added to the serialized representation of a record. By default, `addRelationships` loops over all of the relationships of the passed record, maps the relationship names to the key for the serialized form, and then invokes the public `addBelongsTo` and `addHasMany` hooks. Since you can override `keyForBelongsTo`, `keyForHasMany`, `addBelongsTo`, `addHasMany`, and register mappings, you should rarely need to override this hook. @method addRelationships @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize */ addRelationships: function(data, record) { record.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { this._addBelongsTo(data, record, name, relationship); } else if (relationship.kind === 'hasMany') { this._addHasMany(data, record, name, relationship); } }, this); }, /** A hook you can use to add a `belongsTo` relationship to the serialized representation. The specifics of this hook are very adapter-specific, so there is no default implementation. You can see `DS.JSONSerializer` for an example of an implementation of the `addBelongsTo` hook. The `belongsTo` relationship object has the following properties: * **type** a subclass of DS.Model that is the type of the relationship. This is the first parameter to DS.belongsTo * **options** the options passed to the call to DS.belongsTo * **kind** always `belongsTo` Additional properties may be added in the future. @method addBelongsTo @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} key the key for the serialized object @param {Object} relationship an object representing the relationship */ addBelongsTo: mustImplement('addBelongsTo'), /** A hook you can use to add a `hasMany` relationship to the serialized representation. The specifics of this hook are very adapter-specific, so there is no default implementation. You may not need to implement this, for example, if your backend only expects relationships on the child of a one to many relationship. The `hasMany` relationship object has the following properties: * **type** a subclass of DS.Model that is the type of the relationship. This is the first parameter to DS.hasMany * **options** the options passed to the call to DS.hasMany * **kind** always `hasMany` Additional properties may be added in the future. @method addHasMany @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} key the key for the serialized object @param {Object} relationship an object representing the relationship */ addHasMany: mustImplement('addHasMany'), /** NAMING CONVENTIONS The most commonly overridden APIs of the serializer are the naming convention methods: * `keyForAttributeName`: converts a camelized attribute name into a key in the adapter-provided data hash. For example, if the model's attribute name was `firstName`, and the server used underscored names, you would return `first_name`. * `primaryKey`: returns the key that should be used to extract the id from the adapter-provided data hash. It is also used when serializing a record. */ /** A hook you can use in your serializer subclass to customize how an unmapped attribute name is converted into a key. By default, this method returns the `name` parameter. For example, if the attribute names in your JSON are underscored, you will want to convert them into JavaScript conventional camelcase: ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForAttributeName: function(type, name) { return name.camelize(); } }); ``` @method keyForAttributeName @param {DS.Model subclass} type the type of the record with the attribute name `name` @param {String} name the attribute name to convert into a key @returns {String} the key */ keyForAttributeName: function(type, name) { return name; }, /** A hook you can use in your serializer to specify a conventional primary key. By default, this method will return the string `id`. In general, you should not override this hook to specify a special primary key for an individual type; use `configure` instead. For example, if your primary key is always `__id__`: ```javascript App.MySerializer = DS.Serializer.extend({ // ... primaryKey: function(type) { return '__id__'; } }); ``` In another example, if the primary key always includes the underscored version of the type before the string `id`: ```javascript App.MySerializer = DS.Serializer.extend({ // ... primaryKey: function(type) { // If the type is `BlogPost`, this will return // `blog_post_id`. var typeString = type.toString().split(".")[1].underscore(); return typeString + "_id"; } }); ``` @method primaryKey @param {DS.Model subclass} type @returns {String} the primary key for the type */ primaryKey: function(type) { return "id"; }, /** A hook you can use in your serializer subclass to customize how an unmapped `belongsTo` relationship is converted into a key. By default, this method calls `keyForAttributeName`, so if your naming convention is uniform across attributes and relationships, you can use the default here and override just `keyForAttributeName` as needed. For example, if the `belongsTo` names in your JSON always begin with `BT_` (e.g. `BT_posts`), you can strip out the `BT_` prefix:" ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForBelongsTo: function(type, name) { return name.match(/^BT_(.*)$/)[1].camelize(); } }); ``` @method keyForBelongsTo @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ keyForBelongsTo: function(type, name) { return this.keyForAttributeName(type, name); }, /** A hook you can use in your serializer subclass to customize how an unmapped `hasMany` relationship is converted into a key. By default, this method calls `keyForAttributeName`, so if your naming convention is uniform across attributes and relationships, you can use the default here and override just `keyForAttributeName` as needed. For example, if the `hasMany` names in your JSON always begin with the "table name" for the current type (e.g. `post_comments`), you can strip out the prefix:" ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForHasMany: function(type, name) { // if your App.BlogPost has many App.BlogComment, the key from // the server would look like: `blog_post_blog_comments` // // 1. Convert the type into a string and underscore the // second part (App.BlogPost -> blog_post) // 2. Extract the part after `blog_post_` (`blog_comments`) // 3. Underscore it, to become `blogComments` var typeString = type.toString().split(".")[1].underscore(); return name.match(new RegExp("^" + typeString + "_(.*)$"))[1].camelize(); } }); ``` @method keyForHasMany @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ keyForHasMany: function(type, name) { return this.keyForAttributeName(type, name); }, //......................... //. MATERIALIZATION HOOKS //......................... materialize: function(record, serialized, prematerialized) { var id; if (Ember.isNone(get(record, 'id'))) { if (prematerialized && prematerialized.hasOwnProperty('id')) { id = prematerialized.id; } else { id = this.extractId(record.constructor, serialized); } record.materializeId(id); } this.materializeAttributes(record, serialized, prematerialized); this.materializeRelationships(record, serialized, prematerialized); }, deserializeValue: function(value, attributeType) { var transform = this.transforms ? this.transforms[attributeType] : null; Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform); return transform.deserialize(value); }, materializeAttributes: function(record, serialized, prematerialized) { record.eachAttribute(function(name, attribute) { if (prematerialized && prematerialized.hasOwnProperty(name)) { record.materializeAttribute(name, prematerialized[name]); } else { this.materializeAttribute(record, serialized, name, attribute.type); } }, this); }, materializeAttribute: function(record, serialized, attributeName, attributeType) { var value = this.extractAttribute(record.constructor, serialized, attributeName); value = this.deserializeValue(value, attributeType); record.materializeAttribute(attributeName, value); }, materializeRelationships: function(record, serialized, prematerialized) { record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { if (prematerialized && prematerialized.hasOwnProperty(name)) { var tuplesOrReferencesOrOpaque = this._convertPrematerializedHasMany(relationship.type, prematerialized[name]); record.materializeHasMany(name, tuplesOrReferencesOrOpaque); } else { this.materializeHasMany(name, record, serialized, relationship, prematerialized); } } else if (relationship.kind === 'belongsTo') { if (prematerialized && prematerialized.hasOwnProperty(name)) { var tupleOrReference = this._convertTuple(relationship.type, prematerialized[name]); record.materializeBelongsTo(name, tupleOrReference); } else { this.materializeBelongsTo(name, record, serialized, relationship, prematerialized); } } }, this); }, materializeHasMany: function(name, record, hash, relationship) { var type = record.constructor, key = this._keyForHasMany(type, relationship.key), idsOrTuples = this.extractHasMany(type, hash, key), tuples = idsOrTuples; if(idsOrTuples && Ember.isArray(idsOrTuples)) { tuples = this._convertTuples(relationship.type, idsOrTuples); } record.materializeHasMany(name, tuples); }, materializeBelongsTo: function(name, record, hash, relationship) { var type = record.constructor, key = this._keyForBelongsTo(type, relationship.key), idOrTuple, tuple = null; if(relationship.options && relationship.options.polymorphic) { idOrTuple = this.extractBelongsToPolymorphic(type, hash, key); } else { idOrTuple = this.extractBelongsTo(type, hash, key); } if(!isNone(idOrTuple)) { tuple = this._convertTuple(relationship.type, idOrTuple); } record.materializeBelongsTo(name, tuple); }, _convertPrematerializedHasMany: function(type, prematerializedHasMany) { var tuplesOrReferencesOrOpaque; if( typeof prematerializedHasMany === 'string' ) { tuplesOrReferencesOrOpaque = prematerializedHasMany; } else { tuplesOrReferencesOrOpaque = this._convertTuples(type, prematerializedHasMany); } return tuplesOrReferencesOrOpaque; }, _convertTuples: function(type, idsOrTuples) { return map.call(idsOrTuples, function(idOrTuple) { return this._convertTuple(type, idOrTuple); }, this); }, _convertTuple: function(type, idOrTuple) { var foundType; if (typeof idOrTuple === 'object') { if (DS.Model.detect(idOrTuple.type)) { return idOrTuple; } else { foundType = this.typeFromAlias(idOrTuple.type); Ember.assert("Unable to resolve type " + idOrTuple.type + ". You may need to configure your serializer aliases.", !!foundType); return {id: idOrTuple.id, type: foundType}; } } return {id: idOrTuple, type: type}; }, /** @private This method is called to get the primary key for a given type. If a primary key configuration exists for this type, this method will return the configured value. Otherwise, it will call the public `primaryKey` hook. @method _primaryKey @param {DS.Model subclass} type @returns {String} the primary key for the type */ _primaryKey: function(type) { var config = this.configurationForType(type), primaryKey = config && config.primaryKey; if (primaryKey) { return primaryKey; } else { return this.primaryKey(type); } }, /** @private This method looks up the key for the attribute name and transforms the attribute's value using registered transforms. Specifically: 1. Look up the key for the attribute name. If available, this will use any registered mappings. Otherwise, it will invoke the public `keyForAttributeName` hook. 2. Get the value from the record using the `attributeName`. 3. Transform the value using registered transforms for the `attributeType`. 4. Invoke the public `addAttribute` hook with the hash, key, and transformed value. @method _addAttribute @param {any} data the serialized representation being built @param {DS.Model} record the record to serialize @param {String} attributeName the name of the attribute on the record @param {String} attributeType the type of the attribute (e.g. `string` or `boolean`) */ _addAttribute: function(data, record, attributeName, attributeType) { var key = this._keyForAttributeName(record.constructor, attributeName); var value = get(record, attributeName); this.addAttribute(data, key, this.serializeValue(value, attributeType)); }, /** @private This method looks up the primary key for the `type` and invokes `serializeId` on the `id`. It then invokes the public `addId` hook with the primary key and the serialized id. @method _addId @param {any} data the serialized representation that is being built @param {Ember.Model subclass} type @param {any} id the materialized id from the record */ _addId: function(hash, type, id) { var primaryKey = this._primaryKey(type); this.addId(hash, primaryKey, this.serializeId(id)); }, /** @private This method is called to get a key used in the data from an attribute name. It first checks for any mappings before calling the public hook `keyForAttributeName`. @method _keyForAttributeName @param {DS.Model subclass} type the type of the record with the attribute name `name` @param {String} name the attribute name to convert into a key @returns {String} the key */ _keyForAttributeName: function(type, name) { return this._keyFromMappingOrHook('keyForAttributeName', type, name); }, /** @private This method is called to get a key used in the data from a belongsTo relationship. It first checks for any mappings before calling the public hook `keyForBelongsTo`. @method _keyForBelongsTo @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ _keyForBelongsTo: function(type, name) { return this._keyFromMappingOrHook('keyForBelongsTo', type, name); }, keyFor: function(description) { var type = description.parentType, name = description.key; switch (description.kind) { case 'belongsTo': return this._keyForBelongsTo(type, name); case 'hasMany': return this._keyForHasMany(type, name); } }, /** @private This method is called to get a key used in the data from a hasMany relationship. It first checks for any mappings before calling the public hook `keyForHasMany`. @method _keyForHasMany @param {DS.Model subclass} type the type of the record with the `hasMany` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ _keyForHasMany: function(type, name) { return this._keyFromMappingOrHook('keyForHasMany', type, name); }, /** @private This method converts the relationship name to a key for serialization, and then invokes the public `addBelongsTo` hook. @method _addBelongsTo @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} name the relationship name @param {Object} relationship an object representing the relationship */ _addBelongsTo: function(data, record, name, relationship) { var key = this._keyForBelongsTo(record.constructor, name); this.addBelongsTo(data, record, key, relationship); }, /** @private This method converts the relationship name to a key for serialization, and then invokes the public `addHasMany` hook. @method _addHasMany @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} name the relationship name @param {Object} relationship an object representing the relationship */ _addHasMany: function(data, record, name, relationship) { var key = this._keyForHasMany(record.constructor, name); this.addHasMany(data, record, key, relationship); }, /** @private An internal method that handles checking whether a mapping exists for a particular attribute or relationship name before calling the public hooks. If a mapping is found, and the mapping has a key defined, use that instead of invoking the hook. @method _keyFromMappingOrHook @param {String} publicMethod the public hook to invoke if a mapping is not found (e.g. `keyForAttributeName`) @param {DS.Model subclass} type the type of the record with the attribute or relationship name. @param {String} name the attribute or relationship name to convert into a key */ _keyFromMappingOrHook: function(publicMethod, type, name) { var key = this.mappingOption(type, name, 'key'); if (key) { return key; } else { return this[publicMethod](type, name); } }, /** TRANSFORMS */ registerTransform: function(type, transform) { this.transforms[type] = transform; }, registerEnumTransform: function(type, objects) { var transform = { deserialize: function(serialized) { return Ember.A(objects).objectAt(serialized); }, serialize: function(deserialized) { return Ember.EnumerableUtils.indexOf(objects, deserialized); }, values: objects }; this.registerTransform(type, transform); }, /** MAPPING CONVENIENCE */ map: function(type, mappings) { this.mappings.set(type, mappings); }, configure: function(type, configuration) { if (type && !configuration) { Ember.merge(this.globalConfigurations, type); return; } var config, alias; if (configuration.alias) { alias = configuration.alias; this.aliases.set(alias, type); delete configuration.alias; } config = Ember.create(this.globalConfigurations); Ember.merge(config, configuration); this.configurations.set(type, config); }, typeFromAlias: function(alias) { this._completeAliases(); return this.aliases.get(alias); }, mappingForType: function(type) { this._reifyMappings(); return this.mappings.get(type) || {}; }, configurationForType: function(type) { this._reifyConfigurations(); return this.configurations.get(type) || this.globalConfigurations; }, _completeAliases: function() { this._pluralizeAliases(); this._reifyAliases(); }, _pluralizeAliases: function() { if (this._didPluralizeAliases) { return; } var aliases = this.aliases, sideloadMapping = this.aliases.sideloadMapping, plural, self = this; aliases.forEach(function(key, type) { plural = self.pluralize(key); Ember.assert("The '" + key + "' alias has already been defined", !aliases.get(plural)); aliases.set(plural, type); }); // This map is only for backward compatibility with the `sideloadAs` option. if (sideloadMapping) { sideloadMapping.forEach(function(key, type) { Ember.assert("The '" + key + "' alias has already been defined", !aliases.get(key) || (aliases.get(key)===type) ); aliases.set(key, type); }); delete this.aliases.sideloadMapping; } this._didPluralizeAliases = true; }, _reifyAliases: function() { if (this._didReifyAliases) { return; } var aliases = this.aliases, reifiedAliases = Ember.Map.create(), foundType; aliases.forEach(function(key, type) { if (typeof type === 'string') { foundType = Ember.get(Ember.lookup, type); Ember.assert("Could not find model at path " + key, type); reifiedAliases.set(key, foundType); } else { reifiedAliases.set(key, type); } }); this.aliases = reifiedAliases; this._didReifyAliases = true; }, _reifyMappings: function() { if (this._didReifyMappings) { return; } var mappings = this.mappings, reifiedMappings = Ember.Map.create(); mappings.forEach(function(key, mapping) { if (typeof key === 'string') { var type = Ember.get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, type); reifiedMappings.set(type, mapping); } else { reifiedMappings.set(key, mapping); } }); this.mappings = reifiedMappings; this._didReifyMappings = true; }, _reifyConfigurations: function() { if (this._didReifyConfigurations) { return; } var configurations = this.configurations, reifiedConfigurations = Ember.Map.create(); configurations.forEach(function(key, mapping) { if (typeof key === 'string' && key !== 'plurals') { var type = Ember.get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, type); reifiedConfigurations.set(type, mapping); } else { reifiedConfigurations.set(key, mapping); } }); this.configurations = reifiedConfigurations; this._didReifyConfigurations = true; }, mappingOption: function(type, name, option) { var mapping = this.mappingForType(type)[name]; return mapping && mapping[option]; }, configOption: function(type, option) { var config = this.configurationForType(type); return config[option]; }, // EMBEDDED HELPERS embeddedType: function(type, name) { return this.mappingOption(type, name, 'embedded'); }, eachEmbeddedRecord: function(record, callback, binding) { this.eachEmbeddedBelongsToRecord(record, callback, binding); this.eachEmbeddedHasManyRecord(record, callback, binding); }, eachEmbeddedBelongsToRecord: function(record, callback, binding) { this.eachEmbeddedBelongsTo(record.constructor, function(name, relationship, embeddedType) { var embeddedRecord = get(record, name); if (embeddedRecord) { callback.call(binding, embeddedRecord, embeddedType); } }); }, eachEmbeddedHasManyRecord: function(record, callback, binding) { this.eachEmbeddedHasMany(record.constructor, function(name, relationship, embeddedType) { var array = get(record, name); for (var i=0, l=get(array, 'length'); i<l; i++) { callback.call(binding, array.objectAt(i), embeddedType); } }); }, eachEmbeddedHasMany: function(type, callback, binding) { this.eachEmbeddedRelationship(type, 'hasMany', callback, binding); }, eachEmbeddedBelongsTo: function(type, callback, binding) { this.eachEmbeddedRelationship(type, 'belongsTo', callback, binding); }, eachEmbeddedRelationship: function(type, kind, callback, binding) { type.eachRelationship(function(name, relationship) { var embeddedType = this.embeddedType(type, name); if (embeddedType) { if (relationship.kind === kind) { callback.call(binding, name, relationship, embeddedType); } } }, this); }, // HELPERS // define a plurals hash in your subclass to define // special-case pluralization pluralize: function(name) { var plurals = this.configurations.get('plurals'); return (plurals && plurals[name]) || name + "s"; }, // use the same plurals hash to determine // special-case singularization singularize: function(name) { var plurals = this.configurations.get('plurals'); if (plurals) { for (var i in plurals) { if (plurals[i] === name) { return i; } } } if (name.lastIndexOf('s') === name.length - 1) { return name.substring(0, name.length - 1); } else { return name; } } }); })(); (function() { var isNone = Ember.isNone, isEmpty = Ember.isEmpty; /** @module data @submodule data-transforms */ /** DS.Transforms is a hash of transforms used by DS.Serializer. @class JSONTransforms @static @namespace DS */ DS.JSONTransforms = { string: { deserialize: function(serialized) { return isNone(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return isNone(deserialized) ? null : String(deserialized); } }, number: { deserialize: function(serialized) { return isEmpty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return isEmpty(deserialized) ? null : Number(deserialized); } }, // Handles the following boolean inputs: // "TrUe", "t", "f", "FALSE", 0, (non-zero), or boolean true/false 'boolean': { deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }, date: { deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } } }; })(); (function() { /** @module data @submodule data-serializers */ /** @class JSONSerializer @constructor @namespace DS @extends DS.Serializer */ var get = Ember.get, set = Ember.set; DS.JSONSerializer = DS.Serializer.extend({ init: function() { this._super(); if (!get(this, 'transforms')) { this.set('transforms', DS.JSONTransforms); } this.sideloadMapping = Ember.Map.create(); this.metadataMapping = Ember.Map.create(); this.configure({ meta: 'meta', since: 'since' }); }, configure: function(type, configuration) { var key; if (type && !configuration) { for(key in type){ this.metadataMapping.set(get(type, key), key); } return this._super(type); } var sideloadAs = configuration.sideloadAs, sideloadMapping; if (sideloadAs) { sideloadMapping = this.aliases.sideloadMapping || Ember.Map.create(); sideloadMapping.set(sideloadAs, type); this.aliases.sideloadMapping = sideloadMapping; delete configuration.sideloadAs; } this._super.apply(this, arguments); }, addId: function(data, key, id) { data[key] = id; }, /** A hook you can use to customize how the key/value pair is added to the serialized data. @param {any} hash the JSON hash being built @param {String} key the key to add to the serialized data @param {any} value the value to add to the serialized data */ addAttribute: function(hash, key, value) { hash[key] = value; }, extractAttribute: function(type, hash, attributeName) { var key = this._keyForAttributeName(type, attributeName); return hash[key]; }, extractId: function(type, hash) { var primaryKey = this._primaryKey(type); if (hash.hasOwnProperty(primaryKey)) { // Ensure that we coerce IDs to strings so that record // IDs remain consistent between application runs; especially // if the ID is serialized and later deserialized from the URL, // when type information will have been lost. return hash[primaryKey]+''; } else { return null; } }, extractEmbeddedData: function(hash, key) { return hash[key]; }, extractHasMany: function(type, hash, key) { return hash[key]; }, extractBelongsTo: function(type, hash, key) { return hash[key]; }, extractBelongsToPolymorphic: function(type, hash, key) { var keyForId = this.keyForPolymorphicId(key), keyForType, id = hash[keyForId]; if (id) { keyForType = this.keyForPolymorphicType(key); return {id: id, type: hash[keyForType]}; } return null; }, addBelongsTo: function(hash, record, key, relationship) { var type = record.constructor, name = relationship.key, value = null, includeType = (relationship.options && relationship.options.polymorphic), embeddedChild, child, id; if (this.embeddedType(type, name)) { if (embeddedChild = get(record, name)) { value = this.serialize(embeddedChild, { includeId: true, includeType: includeType }); } hash[key] = value; } else { child = get(record, relationship.key); id = get(child, 'id'); if (relationship.options && relationship.options.polymorphic && !Ember.isNone(id)) { this.addBelongsToPolymorphic(hash, key, id, child.constructor); } else { hash[key] = id === undefined ? null : this.serializeId(id); } } }, addBelongsToPolymorphic: function(hash, key, id, type) { var keyForId = this.keyForPolymorphicId(key), keyForType = this.keyForPolymorphicType(key); hash[keyForId] = id; hash[keyForType] = this.rootForType(type); }, /** Adds a has-many relationship to the JSON hash being built. The default REST semantics are to only add a has-many relationship if it is embedded. If the relationship was initially loaded by ID, we assume that that was done as a performance optimization, and that changes to the has-many should be saved as foreign key changes on the child's belongs-to relationship. @param {Object} hash the JSON being built @param {DS.Model} record the record being serialized @param {String} key the JSON key into which the serialized relationship should be saved @param {Object} relationship metadata about the relationship being serialized */ addHasMany: function(hash, record, key, relationship) { var type = record.constructor, name = relationship.key, serializedHasMany = [], includeType = (relationship.options && relationship.options.polymorphic), manyArray, embeddedType; // If the has-many is not embedded, there is nothing to do. embeddedType = this.embeddedType(type, name); if (embeddedType !== 'always') { return; } // Get the DS.ManyArray for the relationship off the record manyArray = get(record, name); // Build up the array of serialized records manyArray.forEach(function (record) { serializedHasMany.push(this.serialize(record, { includeId: true, includeType: includeType })); }, this); // Set the appropriate property of the serialized JSON to the // array of serialized embedded records hash[key] = serializedHasMany; }, addType: function(hash, type) { var keyForType = this.keyForEmbeddedType(); hash[keyForType] = this.rootForType(type); }, // EXTRACTION extract: function(loader, json, type, record) { var root = this.rootForType(type); this.sideload(loader, type, json, root); this.extractMeta(loader, type, json); if (json[root]) { if (record) { loader.updateId(record, json[root]); } this.extractRecordRepresentation(loader, type, json[root]); } else { Ember.Logger.warn("Extract requested, but no data given for " + type + ". This may cause weird problems."); } }, extractMany: function(loader, json, type, records) { var root = this.rootForType(type); root = this.pluralize(root); this.sideload(loader, type, json, root); this.extractMeta(loader, type, json); if (json[root]) { var objects = json[root], references = []; if (records) { records = records.toArray(); } for (var i = 0; i < objects.length; i++) { if (records) { loader.updateId(records[i], objects[i]); } var reference = this.extractRecordRepresentation(loader, type, objects[i]); references.push(reference); } loader.populateArray(references); } }, extractMeta: function(loader, type, json) { var meta = this.configOption(type, 'meta'), data = json, value; if(meta && json[meta]){ data = json[meta]; } this.metadataMapping.forEach(function(property, key){ value = data[property]; if(!Ember.isNone(value)){ loader.metaForType(type, key, value); } }); }, extractEmbeddedType: function(relationship, data) { var foundType = relationship.type; if(relationship.options && relationship.options.polymorphic) { var key = this.keyFor(relationship), keyForEmbeddedType = this.keyForEmbeddedType(key); foundType = this.typeFromAlias(data[keyForEmbeddedType]); delete data[keyForEmbeddedType]; } return foundType; }, /** @private Iterates over the `json` payload and attempts to load any data included alongside `root`. The keys expected for sideloaded data are based upon the types related to the root model. Recursion is used to ensure that types related to related types can be loaded as well. Any custom keys specified by `sideloadAs` mappings will also be respected. @param {DS.Store subclass} loader @param {DS.Model subclass} type @param {Object} json @param {String} root */ sideload: function(loader, type, json, root) { var sideloadedType; this.configureSideloadMappingForType(type); for (var prop in json) { if (!json.hasOwnProperty(prop) || prop === root || !!this.metadataMapping.get(prop)) { continue; } sideloadedType = this.typeFromAlias(prop); Ember.assert("Your server returned a hash with the key " + prop + " but you have no mapping for it", !!sideloadedType); this.loadValue(loader, sideloadedType, json[prop]); } }, /** @private Configures possible sideload mappings for the types related to a particular model. This recursive method ensures that sideloading works for related models as well. @param {DS.Model subclass} type @param {Ember.A} configured an array of types that have already been configured */ configureSideloadMappingForType: function(type, configured) { if (!configured) {configured = Ember.A([]);} configured.pushObject(type); type.eachRelatedType(function(relatedType) { if (!configured.contains(relatedType)) { var root = this.defaultSideloadRootForType(relatedType); this.aliases.set(root, relatedType); this.configureSideloadMappingForType(relatedType, configured); } }, this); }, loadValue: function(loader, type, value) { if (value instanceof Array) { for (var i=0; i < value.length; i++) { loader.sideload(type, value[i]); } } else { loader.sideload(type, value); } }, /** A hook you can use in your serializer subclass to customize how a polymorphic association's name is converted into a key for the id. @param {String} name the association name to convert into a key @return {String} the key */ keyForPolymorphicId: function(key){ return key; }, /** A hook you can use in your serializer subclass to customize how a polymorphic association's name is converted into a key for the type. @param {String} name the association name to convert into a key @return {String} the key */ keyForPolymorphicType: function(key){ return this.keyForPolymorphicId(key) + '_type'; }, /** A hook you can use in your serializer subclass to customize the key used to store the type of a record of an embedded polymorphic association. By default, this method return 'type'. @return {String} the key */ keyForEmbeddedType: function() { return 'type'; }, // HELPERS /** @private Determines the singular root name for a particular type. This is an underscored, lowercase version of the model name. For example, the type `App.UserGroup` will have the root `user_group`. @param {DS.Model subclass} type @return {String} name of the root element */ rootForType: function(type) { var typeString = type.toString(); Ember.assert("Your model must not be anonymous. It was " + type, typeString.charAt(0) !== '('); // use the last part of the name as the URL var parts = typeString.split("."); var name = parts[parts.length - 1]; return name.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1); }, /** @private The default root name for a particular sideloaded type. @param {DS.Model subclass} type @return {String} name of the root element */ defaultSideloadRootForType: function(type) { return this.pluralize(this.rootForType(type)); } }); })(); (function() { /** @module data @submodule data-adapter */ var get = Ember.get, set = Ember.set, merge = Ember.merge; function loaderFor(store) { return { load: function(type, data, prematerialized) { return store.load(type, data, prematerialized); }, loadMany: function(type, array) { return store.loadMany(type, array); }, updateId: function(record, data) { return store.updateId(record, data); }, populateArray: Ember.K, sideload: function(type, data) { return store.adapterForType(type).load(store, type, data); }, sideloadMany: function(type, array) { return store.loadMany(type, array); }, prematerialize: function(reference, prematerialized) { reference.prematerialized = prematerialized; }, metaForType: function(type, property, data) { store.metaForType(type, property, data); } }; } DS.loaderFor = loaderFor; /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: App.MyAdapter = DS.Adapter.extend({ // ...your code here }); To tell your store which adapter to use, set its `adapter` property: App.store = DS.Store.create({ adapter: App.MyAdapter.create() }); `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` * `createRecords()` * `updateRecords()` * `deleteRecords()` * `commit()` For an example implementation, see {{#crossLink "DS.RestAdapter"}} the included REST adapter.{{/crossLink}}. @class Adapter @namespace DS @extends Ember.Object */ DS.Adapter = Ember.Object.extend(DS._Mappable, { init: function() { var serializer = get(this, 'serializer'); if (Ember.Object.detect(serializer)) { serializer = serializer.create(); set(this, 'serializer', serializer); } this._attributesMap = this.createInstanceMapFor('attributes'); this._configurationsMap = this.createInstanceMapFor('configurations'); this._outstandingOperations = new Ember.MapWithDefault({ defaultValue: function() { return 0; } }); this._dependencies = new Ember.MapWithDefault({ defaultValue: function() { return new Ember.OrderedSet(); } }); this.registerSerializerTransforms(this.constructor, serializer, {}); this.registerSerializerMappings(serializer); }, /** Loads a payload for a record into the store. This method asks the serializer to break the payload into constituent parts, and then loads them into the store. For example, if you have a payload that contains embedded records, they will be extracted by the serializer and loaded into the store. For example: adapter.load(store, App.Person, { id: 123, firstName: "Yehuda", lastName: "Katz", occupations: [{ id: 345, title: "Tricycle Mechanic" }] }); This will load the payload for the `App.Person` with ID `123` and the embedded `App.Occupation` with ID `345`. @method load @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ load: function(store, type, payload) { var loader = loaderFor(store); return get(this, 'serializer').extractRecordRepresentation(loader, type, payload); }, /** Acknowledges that the adapter has finished creating a record. Your adapter should call this method from `createRecord` when it has saved a new record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the creation, and you want to update the existing record with the new information, pass the payload as the fourth parameter. For example, the `RESTAdapter` saves newly created records by making an Ajax request. When the server returns, the adapter calls didCreateRecord. If the server returns a response body, it is passed as the payload. @method didCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didCreateRecord: function(store, type, record, payload) { store.didSaveRecord(record); if (payload) { var loader = DS.loaderFor(store); loader.load = function(type, data, prematerialized) { store.updateId(record, data); return store.load(type, data, prematerialized); }; get(this, 'serializer').extract(loader, payload, type); } }, /** Acknowledges that the adapter has finished creating several records. Your adapter should call this method from `createRecords` when it has saved multiple created records to its persistent storage received an acknowledgement. If the persistent storage returns a new payload in response to the creation, and you want to update the existing record with the new information, pass the payload as the fourth parameter. @method didCreateRecords @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didCreateRecords: function(store, type, records, payload) { records.forEach(function(record) { store.didSaveRecord(record); }, this); if (payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type, records); } }, /** @private Acknowledges that the adapter has finished updating or deleting a record. Your adapter should call this method from `updateRecord` or `deleteRecord` when it has updated or deleted a record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update or delete, and you want to update the existing record with the new information, pass the payload as the fourth parameter. @method didSaveRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didSaveRecord: function(store, type, record, payload) { store.didSaveRecord(record); var serializer = get(this, 'serializer'); serializer.eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { if (embeddedType === 'load') { return; } this.didSaveRecord(store, embeddedRecord.constructor, embeddedRecord); }, this); if (payload) { var loader = DS.loaderFor(store); serializer.extract(loader, payload, type); } }, /** Acknowledges that the adapter has finished updating a record. Your adapter should call this method from `updateRecord` when it has updated a record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update, pass the payload as the fourth parameter. @method didUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didUpdateRecord: function() { this.didSaveRecord.apply(this, arguments); }, /** Acknowledges that the adapter has finished deleting a record. Your adapter should call this method from `deleteRecord` when it has deleted a record from its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the deletion, pass the payload as the fourth parameter. @method didDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didDeleteRecord: function() { this.didSaveRecord.apply(this, arguments); }, /** Acknowledges that the adapter has finished updating or deleting multiple records. Your adapter should call this method from its `updateRecords` or `deleteRecords` when it has updated or deleted multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the creation, pass the payload as the fourth parameter. @method didSaveRecords @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didSaveRecords: function(store, type, records, payload) { records.forEach(function(record) { store.didSaveRecord(record); }, this); if (payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type); } }, /** Acknowledges that the adapter has finished updating multiple records. Your adapter should call this method from its `updateRecords` when it has updated multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update, pass the payload as the fourth parameter. @method didUpdateRecords @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didUpdateRecords: function() { this.didSaveRecords.apply(this, arguments); }, /** Acknowledges that the adapter has finished updating multiple records. Your adapter should call this method from its `deleteRecords` when it has deleted multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the deletion, pass the payload as the fourth parameter. @method didDeleteRecords @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didDeleteRecords: function() { this.didSaveRecords.apply(this, arguments); }, /** Loads the response to a request for a record by ID. Your adapter should call this method from its `find` method with the response from the backend. You should pass the same ID to this method that was given to your find method so that the store knows which record to associate the new data with. @method didFindRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload @param {String} id */ didFindRecord: function(store, type, payload, id) { var loader = DS.loaderFor(store); loader.load = function(type, data, prematerialized) { prematerialized = prematerialized || {}; prematerialized.id = id; return store.load(type, data, prematerialized); }; get(this, 'serializer').extract(loader, payload, type); }, /** Loads the response to a request for all records by type. You adapter should call this method from its `findAll` method with the response from the backend. @method didFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ didFindAll: function(store, type, payload) { var loader = DS.loaderFor(store), serializer = get(this, 'serializer'); store.didUpdateAll(type); serializer.extractMany(loader, payload, type); }, /** Loads the response to a request for records by query. Your adapter should call this method from its `findQuery` method with the response from the backend. @method didFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload @param {DS.AdapterPopulatedRecordArray} recordArray */ didFindQuery: function(store, type, payload, recordArray) { var loader = DS.loaderFor(store); loader.populateArray = function(data) { recordArray.load(data); }; get(this, 'serializer').extractMany(loader, payload, type); }, /** Loads the response to a request for many records by ID. You adapter should call this method from its `findMany` method with the response from the backend. @method didFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ didFindMany: function(store, type, payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type); }, /** Notifies the store that a request to the backend returned an error. Your adapter should call this method to indicate that the backend returned an error for a request. @method didError @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record */ didError: function(store, type, record) { store.recordWasError(record); }, dirtyRecordsForAttributeChange: function(dirtySet, record, attributeName, newValue, oldValue) { if (newValue !== oldValue) { // If this record is embedded, add its parent // to the dirty set. this.dirtyRecordsForRecordChange(dirtySet, record); } }, dirtyRecordsForRecordChange: function(dirtySet, record) { dirtySet.add(record); }, dirtyRecordsForBelongsToChange: function(dirtySet, child) { this.dirtyRecordsForRecordChange(dirtySet, child); }, dirtyRecordsForHasManyChange: function(dirtySet, parent) { this.dirtyRecordsForRecordChange(dirtySet, parent); }, /** @private This method recursively climbs the superclass hierarchy and registers any class-registered transforms on the adapter's serializer. Once it registers a transform for a given type, it ignores subsequent transforms for the same attribute type. @method registerSerializerTransforms @param {Class} klass the DS.Adapter subclass to extract the transforms from @param {DS.Serializer} serializer the serializer to register the transforms onto @param {Object} seen a hash of attributes already seen */ registerSerializerTransforms: function(klass, serializer, seen) { var transforms = klass._registeredTransforms, superclass, prop; var enumTransforms = klass._registeredEnumTransforms; for (prop in transforms) { if (!transforms.hasOwnProperty(prop) || prop in seen) { continue; } seen[prop] = true; serializer.registerTransform(prop, transforms[prop]); } for (prop in enumTransforms) { if (!enumTransforms.hasOwnProperty(prop) || prop in seen) { continue; } seen[prop] = true; serializer.registerEnumTransform(prop, enumTransforms[prop]); } if (superclass = klass.superclass) { this.registerSerializerTransforms(superclass, serializer, seen); } }, /** @private This method recursively climbs the superclass hierarchy and registers any class-registered mappings on the adapter's serializer. @method registerSerializerMappings @param {Class} klass the DS.Adapter subclass to extract the transforms from @param {DS.Serializer} serializer the serializer to register the mappings onto */ registerSerializerMappings: function(serializer) { var mappings = this._attributesMap, configurations = this._configurationsMap; mappings.forEach(serializer.map, serializer); configurations.forEach(serializer.configure, serializer); }, /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `load()` method to load the record. Here is an example `find` implementation: find: function(store, type, id) { var url = type.url; url = url.fmt(id); jQuery.getJSON(url, function(data) { // data is a hash of key/value pairs. If your server returns a // root, simply do something like: // store.load(type, id, data.person) store.load(type, id, data); }); } @method find */ find: null, serializer: DS.JSONSerializer, registerTransform: function(attributeType, transform) { get(this, 'serializer').registerTransform(attributeType, transform); }, /** A public method that allows you to register an enumerated type on your adapter. This is useful if you want to utilize a text representation of an integer value. Eg: Say you want to utilize "low","medium","high" text strings in your app, but you want to persist those as 0,1,2 in your backend. You would first register the transform on your adapter instance: adapter.registerEnumTransform('priority', ['low', 'medium', 'high']); You would then refer to the 'priority' DS.attr in your model: App.Task = DS.Model.extend({ priority: DS.attr('priority') }); And lastly, you would set/get the text representation on your model instance, but the transformed result will be the index number of the type. App: myTask.get('priority') => 'low' Server Response / Load: { myTask: {priority: 0} } @method registerEnumTransform @param {String} type of the transform @param {Array} array of String objects to use for the enumerated values. This is an ordered list and the index values will be used for the transform. */ registerEnumTransform: function(attributeType, objects) { get(this, 'serializer').registerEnumTransform(attributeType, objects); }, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record */ generateIdForRecord: null, materialize: function(record, data, prematerialized) { get(this, 'serializer').materialize(record, data, prematerialized); }, serialize: function(record, options) { return get(this, 'serializer').serialize(record, options); }, extractId: function(type, data) { return get(this, 'serializer').extractId(type, data); }, groupByType: function(enumerable) { var map = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.OrderedSet.create(); } }); enumerable.forEach(function(item) { map.get(item.constructor).add(item); }); return map; }, commit: function(store, commitDetails) { this.save(store, commitDetails); }, save: function(store, commitDetails) { var adapter = this; function filter(records) { var filteredSet = Ember.OrderedSet.create(); records.forEach(function(record) { if (adapter.shouldSave(record)) { filteredSet.add(record); } }); return filteredSet; } this.groupByType(commitDetails.created).forEach(function(type, set) { this.createRecords(store, type, filter(set)); }, this); this.groupByType(commitDetails.updated).forEach(function(type, set) { this.updateRecords(store, type, filter(set)); }, this); this.groupByType(commitDetails.deleted).forEach(function(type, set) { this.deleteRecords(store, type, filter(set)); }, this); }, shouldSave: Ember.K, createRecords: function(store, type, records) { records.forEach(function(record) { this.createRecord(store, type, record); }, this); }, updateRecords: function(store, type, records) { records.forEach(function(record) { this.updateRecord(store, type, record); }, this); }, deleteRecords: function(store, type, records) { records.forEach(function(record) { this.deleteRecord(store, type, record); }, this); }, findMany: function(store, type, ids) { ids.forEach(function(id) { this.find(store, type, id); }, this); } }); DS.Adapter.reopenClass({ registerTransform: function(attributeType, transform) { var registeredTransforms = this._registeredTransforms || {}; registeredTransforms[attributeType] = transform; this._registeredTransforms = registeredTransforms; }, registerEnumTransform: function(attributeType, objects) { var registeredEnumTransforms = this._registeredEnumTransforms || {}; registeredEnumTransforms[attributeType] = objects; this._registeredEnumTransforms = registeredEnumTransforms; }, map: DS._Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { var existingValue = map.get(key); merge(existingValue, newValue); }), configure: DS._Mappable.generateMapFunctionFor('configurations', function(key, newValue, map) { var existingValue = map.get(key); // If a mapping configuration is provided, peel it off and apply it // using the DS.Adapter.map API. var mappings = newValue && newValue.mappings; if (mappings) { this.map(key, mappings); delete newValue.mappings; } merge(existingValue, newValue); }), resolveMapConflict: function(oldValue, newValue) { merge(newValue, oldValue); return newValue; } }); })(); (function() { /** @module data @submodule data-serializers */ /** @class FixtureSerializer @constructor @namespace DS @extends DS.Serializer */ var get = Ember.get, set = Ember.set; DS.FixtureSerializer = DS.Serializer.extend({ deserializeValue: function(value, attributeType) { return value; }, serializeValue: function(value, attributeType) { return value; }, addId: function(data, key, id) { data[key] = id; }, addAttribute: function(hash, key, value) { hash[key] = value; }, addBelongsTo: function(hash, record, key, relationship) { var id = get(record, relationship.key+'.id'); if (!Ember.isNone(id)) { hash[key] = id; } }, addHasMany: function(hash, record, key, relationship) { var ids = get(record, relationship.key).map(function(item) { return item.get('id'); }); hash[relationship.key] = ids; }, extract: function(loader, fixture, type, record) { if (record) { loader.updateId(record, fixture); } this.extractRecordRepresentation(loader, type, fixture); }, extractMany: function(loader, fixtures, type, records) { var objects = fixtures, references = []; if (records) { records = records.toArray(); } for (var i = 0; i < objects.length; i++) { if (records) { loader.updateId(records[i], objects[i]); } var reference = this.extractRecordRepresentation(loader, type, objects[i]); references.push(reference); } loader.populateArray(references); }, extractId: function(type, hash) { var primaryKey = this._primaryKey(type); if (hash.hasOwnProperty(primaryKey)) { // Ensure that we coerce IDs to strings so that record // IDs remain consistent between application runs; especially // if the ID is serialized and later deserialized from the URL, // when type information will have been lost. return hash[primaryKey]+''; } else { return null; } }, extractAttribute: function(type, hash, attributeName) { var key = this._keyForAttributeName(type, attributeName); return hash[key]; }, extractHasMany: function(type, hash, key) { return hash[key]; }, extractBelongsTo: function(type, hash, key) { var val = hash[key]; if (val != null) { val = val + ''; } return val; }, extractBelongsToPolymorphic: function(type, hash, key) { var keyForId = this.keyForPolymorphicId(key), keyForType, id = hash[keyForId]; if (id) { keyForType = this.keyForPolymorphicType(key); return {id: id, type: hash[keyForType]}; } return null; }, keyForPolymorphicId: function(key) { return key; }, keyForPolymorphicType: function(key) { return key + '_type'; } }); })(); (function() { /** @module data @submodule data-adapters */ var get = Ember.get, fmt = Ember.String.fmt, dump = Ember.get(window, 'JSON.stringify') || function(object) { return object.toString(); }; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. @class FixtureAdapter @constructor @namespace DS @extends DS.Adapter */ DS.FixtureAdapter = DS.Adapter.extend({ simulateRemoteResponse: true, latency: 50, serializer: DS.FixtureSerializer, /* Implement this method in order to provide data associated with a type */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [dump(fixture)])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /* Implement this method in order to query fixtures data */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /* Implement this method in order to provide provide json for CRUD methods */ mockJSON: function(type, record) { return this.serialize(record, { includeId: true }); }, /* Adapter methods */ generateIdForRecord: function(store, record) { return Ember.guidFor(record); }, find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; Ember.warn("Unable to find fixtures for model type " + type.toString(), fixtures); if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { this.simulateRemoteCall(function() { this.didFindRecord(store, type, fixture, id); }, this); } }, findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return ids.indexOf(item.id) !== -1; }); } if (fixtures) { this.simulateRemoteCall(function() { this.didFindMany(store, type, fixtures); }, this); } }, findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); this.simulateRemoteCall(function() { this.didFindAll(store, type, fixtures); }, this); }, findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { this.simulateRemoteCall(function() { this.didFindQuery(store, type, fixtures, array); }, this); } }, createRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.updateFixtures(type, fixture); this.simulateRemoteCall(function() { this.didCreateRecord(store, type, record, fixture); }, this); }, updateRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.updateFixtures(type, fixture); this.simulateRemoteCall(function() { this.didUpdateRecord(store, type, record, fixture); }, this); }, deleteRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.deleteLoadedFixture(type, fixture); this.simulateRemoteCall(function() { this.didDeleteRecord(store, type, record); }, this); }, /* @private */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = type.FIXTURES.indexOf(existingFixture); type.FIXTURES.splice(index, 1); return true; } }, findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = this.extractId(type, record); return this.findFixtureById(fixtures, id); }, findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, simulateRemoteCall: function(callback, context) { if (get(this, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(context, callback, get(this, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.once(context, callback); } } }); })(); (function() { /** @module data @submodule data-serializers */ /** @class RESTSerializer @constructor @namespace DS @extends DS.Serializer */ var get = Ember.get; DS.RESTSerializer = DS.JSONSerializer.extend({ keyForAttributeName: function(type, name) { return Ember.String.decamelize(name); }, keyForBelongsTo: function(type, name) { var key = this.keyForAttributeName(type, name); if (this.embeddedType(type, name)) { return key; } return key + "_id"; }, keyForHasMany: function(type, name) { var key = this.keyForAttributeName(type, name); if (this.embeddedType(type, name)) { return key; } return this.singularize(key) + "_ids"; }, keyForPolymorphicId: function(key) { return key; }, keyForPolymorphicType: function(key) { return key.replace(/_id$/, '_type'); }, extractValidationErrors: function(type, json) { var errors = {}; get(type, 'attributes').forEach(function(name) { var key = this._keyForAttributeName(type, name); if (json['errors'].hasOwnProperty(key)) { errors[name] = json['errors'][key]; } }, this); return errors; } }); })(); (function() { /** @module data @submodule data-adapters */ var get = Ember.get, set = Ember.set; DS.rejectionHandler = function(reason) { Ember.Logger.assert([reason, reason.message, reason.stack]); throw reason; }; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { title: "I'm Running to Reform the W3C's Tag", author: "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ DS.RESTAdapter = DS.Adapter.extend({ namespace: null, bulkCommit: false, since: 'since', serializer: DS.RESTSerializer, init: function() { this._super.apply(this, arguments); }, shouldSave: function(record) { var reference = get(record, '_reference'); return !reference.parent; }, dirtyRecordsForRecordChange: function(dirtySet, record) { this._dirtyTree(dirtySet, record); }, dirtyRecordsForHasManyChange: function(dirtySet, record, relationship) { var embeddedType = get(this, 'serializer').embeddedType(record.constructor, relationship.secondRecordName); if (embeddedType === 'always') { relationship.childReference.parent = relationship.parentReference; this._dirtyTree(dirtySet, record); } }, _dirtyTree: function(dirtySet, record) { dirtySet.add(record); get(this, 'serializer').eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { if (embeddedType !== 'always') { return; } if (dirtySet.has(embeddedRecord)) { return; } this._dirtyTree(dirtySet, embeddedRecord); }, this); var reference = record.get('_reference'); if (reference.parent) { var store = get(record, 'store'); var parent = store.recordForReference(reference.parent); this._dirtyTree(dirtySet, parent); } }, createRecord: function(store, type, record) { var root = this.rootForType(type); var adapter = this; var data = {}; data[root] = this.serialize(record, { includeId: true }); return this.ajax(this.buildURL(root), "POST", { data: data }).then(function(json){ adapter.didCreateRecord(store, type, record, json); }, function(xhr) { adapter.didError(store, type, record, xhr); throw xhr; }).then(null, DS.rejectionHandler); }, createRecords: function(store, type, records) { var adapter = this; if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } var root = this.rootForType(type), plural = this.pluralize(root); var data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(this.serialize(record, { includeId: true })); }, this); return this.ajax(this.buildURL(root), "POST", { data: data }).then(function(json) { adapter.didCreateRecords(store, type, records, json); }).then(null, DS.rejectionHandler); }, updateRecord: function(store, type, record) { var id, root, adapter, data; id = get(record, 'id'); root = this.rootForType(type); adapter = this; data = {}; data[root] = this.serialize(record); return this.ajax(this.buildURL(root, id), "PUT",{ data: data }).then(function(json){ adapter.didUpdateRecord(store, type, record, json); }, function(xhr) { adapter.didError(store, type, record, xhr); throw xhr; }).then(null, DS.rejectionHandler); }, updateRecords: function(store, type, records) { var root, plural, adapter, data; if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } root = this.rootForType(type); plural = this.pluralize(root); adapter = this; data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(this.serialize(record, { includeId: true })); }, this); return this.ajax(this.buildURL(root, "bulk"), "PUT", { data: data }).then(function(json) { adapter.didUpdateRecords(store, type, records, json); }).then(null, DS.rejectionHandler); }, deleteRecord: function(store, type, record) { var id, root, adapter; id = get(record, 'id'); root = this.rootForType(type); adapter = this; return this.ajax(this.buildURL(root, id), "DELETE").then(function(json){ adapter.didDeleteRecord(store, type, record, json); }, function(xhr){ adapter.didError(store, type, record, xhr); throw xhr; }).then(null, DS.rejectionHandler); }, deleteRecords: function(store, type, records) { var root, plural, serializer, adapter, data; if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } root = this.rootForType(type); plural = this.pluralize(root); serializer = get(this, 'serializer'); adapter = this; data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(serializer.serializeId( get(record, 'id') )); }); return this.ajax(this.buildURL(root, 'bulk'), "DELETE", { data: data }).then(function(json){ adapter.didDeleteRecords(store, type, records, json); }).then(null, DS.rejectionHandler); }, find: function(store, type, id) { var root = this.rootForType(type), adapter = this; return this.ajax(this.buildURL(root, id), "GET"). then(function(json){ adapter.didFindRecord(store, type, json, id); }).then(null, DS.rejectionHandler); }, findAll: function(store, type, since) { var root, adapter; root = this.rootForType(type); adapter = this; return this.ajax(this.buildURL(root), "GET",{ data: this.sinceQuery(since) }).then(function(json) { adapter.didFindAll(store, type, json); }).then(null, DS.rejectionHandler); }, findQuery: function(store, type, query, recordArray) { var root = this.rootForType(type), adapter = this; return this.ajax(this.buildURL(root), "GET", { data: query }).then(function(json){ adapter.didFindQuery(store, type, json, recordArray); }).then(null, DS.rejectionHandler); }, findMany: function(store, type, ids, owner) { var root = this.rootForType(type), adapter = this; ids = this.serializeIds(ids); return this.ajax(this.buildURL(root), "GET", { data: {ids: ids} }).then(function(json) { adapter.didFindMany(store, type, json); }).then(null, DS.rejectionHandler); }, /** @private This method serializes a list of IDs using `serializeId` @return {Array} an array of serialized IDs */ serializeIds: function(ids) { var serializer = get(this, 'serializer'); return Ember.EnumerableUtils.map(ids, function(id) { return serializer.serializeId(id); }); }, didError: function(store, type, record, xhr) { if (xhr.status === 422) { var json = JSON.parse(xhr.responseText), serializer = get(this, 'serializer'), errors = serializer.extractValidationErrors(type, json); store.recordWasInvalid(record, errors); } else { this._super.apply(this, arguments); } }, ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = adapter; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, jqXHR); }; Ember.$.ajax(hash); }); }, url: "", rootForType: function(type) { var serializer = get(this, 'serializer'); return serializer.rootForType(type); }, pluralize: function(string) { var serializer = get(this, 'serializer'); return serializer.pluralize(string); }, buildURL: function(record, suffix) { var url = [this.url]; Ember.assert("Namespace URL (" + this.namespace + ") must not start with slash", !this.namespace || this.namespace.toString().charAt(0) !== "/"); Ember.assert("Record URL (" + record + ") must not start with slash", !record || record.toString().charAt(0) !== "/"); Ember.assert("URL suffix (" + suffix + ") must not start with slash", !suffix || suffix.toString().charAt(0) !== "/"); if (!Ember.isNone(this.namespace)) { url.push(this.namespace); } url.push(this.pluralize(record)); if (suffix !== undefined) { url.push(suffix); } return url.join("/"); }, sinceQuery: function(since) { var query = {}; query[get(this, 'since')] = since; return since ? query : null; } }); })(); (function() { /** Adapters included with Ember-Data. @module data @submodule data-adapters @main data-adapters */ })(); (function() { //Copyright (C) 2011 by Living Social, Inc. //Permission is hereby granted, free of charge, to any person obtaining a copy of //this software and associated documentation files (the "Software"), to deal in //the Software without restriction, including without limitation the rights to //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies //of the Software, and to permit persons to whom the Software is furnished to do //so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. /** Ember Data @module data */ })(); })();
app/index.js
nesfe/electron-LAN-chat
import React from 'react'; import { render } from 'react-dom'; import './app.global.scss'; import Header from './components/Header'; import Contacts from './components/Contacts'; import Home from './components/Home'; import utils from './utils/utils'; import jquery from 'jquery'; import './assets/js/jquery.nicescroll.min'; import { message } from 'antd'; window.onload = () => { jquery('#contacts').niceScroll(); jquery('.exprMain').niceScroll(); }; class Index extends React.Component { constructor(props) { super(props); this.state = { search: '', socket: [], nowIp: 0, connected: true, contacts: [] }; } componentWillMount() { this.state.socket[utils.ip] = utils.ip; this.state.connected = utils.ip; this.state.nowIp = utils.ip; let arr = []; arr.push({ ip: 0, message: 'Hello, ' + utils.ip, date: utils.getDate() }); localStorage[utils.ip] = JSON.stringify(arr); localStorage[utils.ip + 'tx'] = " hp-" + (Math.random() * 48).toFixed(0); this.state.contacts.push(utils.ip); } onRunSearch(sea) { // 暂时不支持搜索 // this.setState({ // search: sea // }); } onSocketAccept(hz) { let ip = utils.IpQz + '.' + hz; if (this.state.socket[ip]) { const err = React.createClass({ render() { return ( <span>已经存在或者目标不存在 <b>😂</b></span> ) } }); const node = React.createElement(err); message.error(node, 4); return false; } else { this.state.socket[ip] = ip; if (this.state.socket[ip]) { let arr = []; arr.push({ ip: 0, message: 'Hello, ' + ip, date: utils.getDate() }); localStorage[ip] = JSON.stringify(arr); localStorage[ip + 'tx'] = " hp-" + (Math.random() * 48).toFixed(0); this.state.contacts.push(ip); this.setState({ nowIp: ip }); } else { } } } onToggleChat(ip) { localStorage[ip + 'unread'] = 500; this.setState({ nowIp: ip }); } onNewAddChat(arrry) { const ip = arrry.ip; this.state.socket[ip] = ip; if (this.state.socket[ip]) { let arr = []; arr.push({ ip: ip, message: arrry.message, date: utils.getDate() }); localStorage[ip] = JSON.stringify(arr); localStorage[ip + 'tx'] = " hp-" + (Math.random() * 48).toFixed(0); this.state.contacts.push(ip); this.setState({ nowIp: ip }); } const err = React.createClass({ render() { return ( <span>{ip}来了 <b>😀</b></span> ) } }); const node = React.createElement(err); message.error(node, 4); } onUnread() { this.refs.contacts.unread(); } render() { return ( <div> <Header onRunSearch={this.onRunSearch.bind(this)} onSocketAccept={this.onSocketAccept.bind(this)}/> <Contacts ref="contacts" search={this.state.search} contacts={this.state.contacts} nowIp={this.state.nowIp} onToggleChat={this.onToggleChat.bind(this)}/> <div className="container"> <Home nowIp={this.state.nowIp} state={this.state} onNewAddChat={this.onNewAddChat.bind(this)} onUnread={this.onUnread.bind(this)}/> </div> </div> ); } } render( <Index />, document.getElementById('root') ); // if (module.hot) { // module.hot.accept('./containers/Root', () => { // render( // <Index />, // document.getElementById('root') // ); // }); // } // if (module.hot) { // module.hot.accept('./containers/App', () => { // render(<Index />); // }); // }
js/components/projectAdd/tabDescription.js
bsusta/HelpdeskAppTemplate
import React, { Component } from 'react'; import { Form, Input, Label, Button, Icon, Item, Footer, FooterTab, Thumbnail, Container, Content, Card, CardItem, Text, ListItem, List, Left, Body, Right } from 'native-base'; import styles from './styles'; import {createProject} from './projectAdd.gquery'; import { Actions } from 'react-native-router-flux'; import { withApollo} from 'react-apollo'; import I18n from '../../translations/'; class TabDescription extends Component { // eslint-disable-line constructor(props){ super(props); this.state={ title:'', description:'' } } submit(){ this.props.client.mutate({ mutation: createProject, variables: { title:this.state.title,description:this.state.description}, }); Actions.pop(); } render() { // eslint-disable-line return ( <Container> <Content padder style={{ marginTop: 0 }}> <Form> <Item stackedLabel> <Label>{I18n.t('title')}</Label> <Input placeholder={I18n.t('title')} value={this.state.title} onChangeText={(value)=>this.setState({title:value})} /> </Item> <Item stackedLabel> <Label>{I18n.t('description')}</Label> <Input style={{height:100}} multiline={true} placeholder={I18n.t('description')} value={this.state.description} onChangeText={(value)=>this.setState({description:value})} /> </Item> </Form> </Content> <Footer> <FooterTab> <Button iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }} onPress={Actions.pop} > <Icon active style={{ color: 'white' }} name="md-add" /> <Text style={{ color: 'white' }} >{I18n.t('cancel')}</Text> </Button> </FooterTab> <FooterTab> <Button iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }} onPress={this.submit.bind(this)}> <Icon active name="md-add" style={{ color: 'white' }} /> <Text style={{ color: 'white' }} >{I18n.t('save')}</Text> </Button> </FooterTab> </Footer> </Container> ); } } export default withApollo(TabDescription);
src/svg-icons/action/system-update-alt.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSystemUpdateAlt = (props) => ( <SvgIcon {...props}> <path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt); ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt'; ActionSystemUpdateAlt.muiName = 'SvgIcon'; export default ActionSystemUpdateAlt;
components/Form/Select/Select.story.js
rdjpalmer/bloom
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import { withKnobs, boolean } from '@storybook/addon-knobs'; import Select from './Select'; import Option from './Option'; import icons from '../../Icon/icons'; const stories = storiesOf('FormComponents', module); stories.addDecorator(withKnobs); stories.add('Select', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> )) .add('Select w/high priority', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } priority="high" > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> ));
ajax/libs/thorax/2.2.1/thorax-combined.js
brunoksato/cdnjs
/*! * jQuery JavaScript Library v1.9.0 * 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-1-14 */ (function( window, undefined ) { "use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // 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.0", // 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 and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; 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 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; 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 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 = 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", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // 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 ); } // 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 // 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; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // 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, select, opt, input, fragment, 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 !== "undefined" ) { // 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 ); // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 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 /* For internal use only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, 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, false ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name, false ); }, // 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 ) { 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.substring(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 === "undefined" || 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 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, 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 ret, hooks, notxml, 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 === "undefined" ) { 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 !== "undefined" ) { 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 handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, // Don't attach events to noData or text/comment nodes (but allow plain objects) elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data( elem ); 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 !== "undefined" && (!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, origCount, tmp, events, t, handleObj, 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 i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = event.type || event, namespaces = 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, j, ret, matched, handleObj, 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 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; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, 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 eventDoc, doc, body, 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 ] === "undefined" ) { 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 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 ); }); }, 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 ); } }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); 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 ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * 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\]\s*\}/, // 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( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); 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 === "*" ) { for ( ; (elem = results[i]); 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 ]; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE ); // 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 = a && b && a.nextSibling; for ( ; cur; 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.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 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 && combinator.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 ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); 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 // `i` starts as a string, so matchedCount would equal "00" if there are no elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); 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 for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < self.length; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < this.length; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( jQuery.unique( 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 && this.nodeType === 1 || this.nodeType === 11 ) { jQuery( this ).remove(); if ( next ) { next.parentNode.insertBefore( elem, next ); } else { parent.appendChild( elem ); } } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_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" || 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, data, e; // 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 !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? 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, srcElements, node, i, clone, 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 contains, elem, tag, tmp, wrap, tbody, j, 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 data, id, elem, type, 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 !== "undefined" ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var curCSS, getStyles, iframe, 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 elem, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.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 ] && !isHidden( elem ) ) { jQuery._data( elem, "olddisplay", 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 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 ) { 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 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 ) { 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 ) { 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)$/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 ); } } 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 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; } 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 = 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 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 (#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 not modified if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data } 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 ct, type, finalDataType, firstDataType, 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 conv, conv2, current, 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, statusText, responseHeaders, responses, xml; // 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; xml = xhr.responseXML; responseHeaders = xhr.getAllResponseHeaders(); // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // 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 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; } } } 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 index, prop, value, length, 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.done(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 a non 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, "auto" ); // 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 !== "undefined" ) { 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 ); /* Copyright (C) 2011 by Yehuda Katz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // lib/handlebars/browser-prefix.js var Handlebars = {}; (function(Handlebars, undefined) { ; // lib/handlebars/base.js Handlebars.VERSION = "1.0.0"; Handlebars.COMPILER_REVISION = 4; Handlebars.REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '== 1.0.0-rc.4', 4: '>= 1.0.0' }; Handlebars.helpers = {}; Handlebars.partials = {}; var toString = Object.prototype.toString, functionType = '[object Function]', objectType = '[object Object]'; Handlebars.registerHelper = function(name, fn, inverse) { if (toString.call(name) === objectType) { if (inverse || fn) { throw new Handlebars.Exception('Arg not supported with multiple helpers'); } Handlebars.Utils.extend(this.helpers, name); } else { if (inverse) { fn.not = inverse; } this.helpers[name] = fn; } }; Handlebars.registerPartial = function(name, str) { if (toString.call(name) === objectType) { Handlebars.Utils.extend(this.partials, name); } else { this.partials[name] = str; } }; Handlebars.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Error("Missing helper: '" + arg + "'"); } }); Handlebars.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { return Handlebars.helpers.each(context, options); } else { return inverse(this); } } else { return fn(context); } }); Handlebars.K = function() {}; Handlebars.createFrame = Object.create || function(object) { Handlebars.K.prototype = object; var obj = new Handlebars.K(); Handlebars.K.prototype = null; return obj; }; Handlebars.logger = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3, methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'}, // can be overridden in the host environment log: function(level, obj) { if (Handlebars.logger.level <= level) { var method = Handlebars.logger.methodMap[level]; if (typeof console !== 'undefined' && console[method]) { console[method].call(console, obj); } } } }; Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); }; Handlebars.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var i = 0, ret = "", data; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if (options.data) { data = Handlebars.createFrame(options.data); } if(context && typeof context === 'object') { if(context instanceof Array){ for(var j = context.length; i<j; i++) { if (data) { data.index = i; } ret = ret + fn(context[i], { data: data }); } } else { for(var key in context) { if(context.hasOwnProperty(key)) { if(data) { data.key = key; } ret = ret + fn(context[key], {data: data}); i++; } } } } if(i === 0){ ret = inverse(this); } return ret; }); Handlebars.registerHelper('if', function(conditional, options) { var type = toString.call(conditional); if(type === functionType) { conditional = conditional.call(this); } if(!conditional || Handlebars.Utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); Handlebars.registerHelper('unless', function(conditional, options) { return Handlebars.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn}); }); Handlebars.registerHelper('with', function(context, options) { var type = toString.call(context); if(type === functionType) { context = context.call(this); } if (!Handlebars.Utils.isEmpty(context)) return options.fn(context); }); Handlebars.registerHelper('log', function(context, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; Handlebars.log(level, context); }); ; // lib/handlebars/compiler/parser.js /* Jison generated parser */ var handlebars = (function(){ var parser = {trace: function trace() { }, yy: {}, symbols_: {"error":2,"root":3,"program":4,"EOF":5,"simpleInverse":6,"statements":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"inMustache":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"CLOSE_UNESCAPED":24,"OPEN_PARTIAL":25,"partialName":26,"params":27,"hash":28,"dataName":29,"param":30,"STRING":31,"INTEGER":32,"BOOLEAN":33,"hashSegments":34,"hashSegment":35,"ID":36,"EQUALS":37,"DATA":38,"pathSegments":39,"SEP":40,"$accept":0,"$end":1}, terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",31:"STRING",32:"INTEGER",33:"BOOLEAN",36:"ID",37:"EQUALS",38:"DATA",40:"SEP"}, productions_: [0,[3,2],[4,2],[4,3],[4,2],[4,1],[4,1],[4,0],[7,1],[7,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[6,2],[17,3],[17,2],[17,2],[17,1],[17,1],[27,2],[27,1],[30,1],[30,1],[30,1],[30,1],[30,1],[28,1],[34,2],[34,1],[35,3],[35,3],[35,3],[35,3],[35,3],[26,1],[26,1],[26,1],[29,2],[21,1],[39,3],[39,1]], performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0-1]; break; case 2: this.$ = new yy.ProgramNode([], $$[$0]); break; case 3: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]); break; case 4: this.$ = new yy.ProgramNode($$[$0-1], []); break; case 5: this.$ = new yy.ProgramNode($$[$0]); break; case 6: this.$ = new yy.ProgramNode([], []); break; case 7: this.$ = new yy.ProgramNode([]); break; case 8: this.$ = [$$[$0]]; break; case 9: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 10: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0]); break; case 11: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0]); break; case 12: this.$ = $$[$0]; break; case 13: this.$ = $$[$0]; break; case 14: this.$ = new yy.ContentNode($$[$0]); break; case 15: this.$ = new yy.CommentNode($$[$0]); break; case 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]); break; case 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]); break; case 18: this.$ = $$[$0-1]; break; case 19: // Parsing out the '&' escape token at this level saves ~500 bytes after min due to the removal of one parser node. this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], $$[$0-2][2] === '&'); break; case 20: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true); break; case 21: this.$ = new yy.PartialNode($$[$0-1]); break; case 22: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1]); break; case 23: break; case 24: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]]; break; case 25: this.$ = [[$$[$0-1]].concat($$[$0]), null]; break; case 26: this.$ = [[$$[$0-1]], $$[$0]]; break; case 27: this.$ = [[$$[$0]], null]; break; case 28: this.$ = [[$$[$0]], null]; break; case 29: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 30: this.$ = [$$[$0]]; break; case 31: this.$ = $$[$0]; break; case 32: this.$ = new yy.StringNode($$[$0]); break; case 33: this.$ = new yy.IntegerNode($$[$0]); break; case 34: this.$ = new yy.BooleanNode($$[$0]); break; case 35: this.$ = $$[$0]; break; case 36: this.$ = new yy.HashNode($$[$0]); break; case 37: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 38: this.$ = [$$[$0]]; break; case 39: this.$ = [$$[$0-2], $$[$0]]; break; case 40: this.$ = [$$[$0-2], new yy.StringNode($$[$0])]; break; case 41: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])]; break; case 42: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])]; break; case 43: this.$ = [$$[$0-2], $$[$0]]; break; case 44: this.$ = new yy.PartialNameNode($$[$0]); break; case 45: this.$ = new yy.PartialNameNode(new yy.StringNode($$[$0])); break; case 46: this.$ = new yy.PartialNameNode(new yy.IntegerNode($$[$0])); break; case 47: this.$ = new yy.DataNode($$[$0]); break; case 48: this.$ = new yy.IdNode($$[$0]); break; case 49: $$[$0-2].push({part: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; break; case 50: this.$ = [{part: $$[$0]}]; break; } }, table: [{3:1,4:2,5:[2,7],6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],22:[1,14],23:[1,15],25:[1,16]},{1:[3]},{5:[1,17]},{5:[2,6],7:18,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,6],22:[1,14],23:[1,15],25:[1,16]},{5:[2,5],6:20,8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,5],22:[1,14],23:[1,15],25:[1,16]},{17:23,18:[1,22],21:24,29:25,36:[1,28],38:[1,27],39:26},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],25:[2,8]},{4:29,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],25:[1,16]},{4:30,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],25:[1,16]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{17:31,21:24,29:25,36:[1,28],38:[1,27],39:26},{17:32,21:24,29:25,36:[1,28],38:[1,27],39:26},{17:33,21:24,29:25,36:[1,28],38:[1,27],39:26},{21:35,26:34,31:[1,36],32:[1,37],36:[1,28],39:26},{1:[2,1]},{5:[2,2],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,2],22:[1,14],23:[1,15],25:[1,16]},{17:23,21:24,29:25,36:[1,28],38:[1,27],39:26},{5:[2,4],7:38,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,4],22:[1,14],23:[1,15],25:[1,16]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{5:[2,23],14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{18:[1,39]},{18:[2,27],21:44,24:[2,27],27:40,28:41,29:48,30:42,31:[1,45],32:[1,46],33:[1,47],34:43,35:49,36:[1,50],38:[1,27],39:26},{18:[2,28],24:[2,28]},{18:[2,48],24:[2,48],31:[2,48],32:[2,48],33:[2,48],36:[2,48],38:[2,48],40:[1,51]},{21:52,36:[1,28],39:26},{18:[2,50],24:[2,50],31:[2,50],32:[2,50],33:[2,50],36:[2,50],38:[2,50],40:[2,50]},{10:53,20:[1,54]},{10:55,20:[1,54]},{18:[1,56]},{18:[1,57]},{24:[1,58]},{18:[1,59],21:60,36:[1,28],39:26},{18:[2,44],36:[2,44]},{18:[2,45],36:[2,45]},{18:[2,46],36:[2,46]},{5:[2,3],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,3],22:[1,14],23:[1,15],25:[1,16]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{18:[2,25],21:44,24:[2,25],28:61,29:48,30:62,31:[1,45],32:[1,46],33:[1,47],34:43,35:49,36:[1,50],38:[1,27],39:26},{18:[2,26],24:[2,26]},{18:[2,30],24:[2,30],31:[2,30],32:[2,30],33:[2,30],36:[2,30],38:[2,30]},{18:[2,36],24:[2,36],35:63,36:[1,64]},{18:[2,31],24:[2,31],31:[2,31],32:[2,31],33:[2,31],36:[2,31],38:[2,31]},{18:[2,32],24:[2,32],31:[2,32],32:[2,32],33:[2,32],36:[2,32],38:[2,32]},{18:[2,33],24:[2,33],31:[2,33],32:[2,33],33:[2,33],36:[2,33],38:[2,33]},{18:[2,34],24:[2,34],31:[2,34],32:[2,34],33:[2,34],36:[2,34],38:[2,34]},{18:[2,35],24:[2,35],31:[2,35],32:[2,35],33:[2,35],36:[2,35],38:[2,35]},{18:[2,38],24:[2,38],36:[2,38]},{18:[2,50],24:[2,50],31:[2,50],32:[2,50],33:[2,50],36:[2,50],37:[1,65],38:[2,50],40:[2,50]},{36:[1,66]},{18:[2,47],24:[2,47],31:[2,47],32:[2,47],33:[2,47],36:[2,47],38:[2,47]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{21:67,36:[1,28],39:26},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,68]},{18:[2,24],24:[2,24]},{18:[2,29],24:[2,29],31:[2,29],32:[2,29],33:[2,29],36:[2,29],38:[2,29]},{18:[2,37],24:[2,37],36:[2,37]},{37:[1,65]},{21:69,29:73,31:[1,70],32:[1,71],33:[1,72],36:[1,28],38:[1,27],39:26},{18:[2,49],24:[2,49],31:[2,49],32:[2,49],33:[2,49],36:[2,49],38:[2,49],40:[2,49]},{18:[1,74]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{18:[2,39],24:[2,39],36:[2,39]},{18:[2,40],24:[2,40],36:[2,40]},{18:[2,41],24:[2,41],36:[2,41]},{18:[2,42],24:[2,42],36:[2,42]},{18:[2,43],24:[2,43],36:[2,43]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]}], defaultActions: {17:[2,1]}, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; /* Jison generated lexer */ var lexer = (function(){ var lexer = ({EOF:1, parseError:function parseError(str, hash) { if (this.yy.parser) { this.yy.parser.parseError(str, hash); } else { throw new Error(str); } }, setInput:function (input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; if (this.options.ranges) this.yylloc.range = [0,0]; this.offset = 0; return this; }, input:function () { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput:function (ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length-len-1); //this.yyleng -= len; this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length-1); this.matched = this.matched.substr(0, this.matched.length-1); if (lines.length-1) this.yylineno -= lines.length-1; var r = this.yylloc.range; this.yylloc = {first_line: this.yylloc.first_line, last_line: this.yylineno+1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more:function () { this._more = true; return this; }, less:function (n) { this.unput(this.match.slice(n)); }, pastInput:function () { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); }, upcomingInput:function () { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20-next.length); } return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); }, showPosition:function () { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c+"^"; }, next:function () { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index, col, lines; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i=0;i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = {first_line: this.yylloc.last_line, last_line: this.yylineno+1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); if (this.done && this._input) this.done = false; if (token) return token; else return; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), {text: "", token: null, line: this.yylineno}); } }, lex:function lex() { var r = this.next(); if (typeof r !== 'undefined') { return r; } else { return this.lex(); } }, begin:function begin(condition) { this.conditionStack.push(condition); }, popState:function popState() { return this.conditionStack.pop(); }, _currentRules:function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; }, topState:function () { return this.conditionStack[this.conditionStack.length-2]; }, pushState:function begin(condition) { this.begin(condition); }}); lexer.options = {}; lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { var YYSTATE=YY_START switch($avoiding_name_collisions) { case 0: yy_.yytext = "\\"; return 14; break; case 1: if(yy_.yytext.slice(-1) !== "\\") this.begin("mu"); if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1), this.begin("emu"); if(yy_.yytext) return 14; break; case 2: return 14; break; case 3: if(yy_.yytext.slice(-1) !== "\\") this.popState(); if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1); return 14; break; case 4: yy_.yytext = yy_.yytext.substr(0, yy_.yyleng-4); this.popState(); return 15; break; case 5: return 25; break; case 6: return 16; break; case 7: return 20; break; case 8: return 19; break; case 9: return 19; break; case 10: return 23; break; case 11: return 22; break; case 12: this.popState(); this.begin('com'); break; case 13: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return 15; break; case 14: return 22; break; case 15: return 37; break; case 16: return 36; break; case 17: return 36; break; case 18: return 40; break; case 19: /*ignore whitespace*/ break; case 20: this.popState(); return 24; break; case 21: this.popState(); return 18; break; case 22: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 31; break; case 23: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\'/g,"'"); return 31; break; case 24: return 38; break; case 25: return 33; break; case 26: return 33; break; case 27: return 32; break; case 28: return 36; break; case 29: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 36; break; case 30: return 'INVALID'; break; case 31: return 5; break; } }; lexer.rules = [/^(?:\\\\(?=(\{\{)))/,/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[}\/ ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:-?[0-9]+(?=[}\s]))/,/^(?:[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; lexer.conditions = {"mu":{"rules":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31],"inclusive":false},"emu":{"rules":[3],"inclusive":false},"com":{"rules":[4],"inclusive":false},"INITIAL":{"rules":[0,1,2,31],"inclusive":true}}; return lexer;})() parser.lexer = lexer; function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; return new Parser; })();; // lib/handlebars/compiler/base.js Handlebars.Parser = handlebars; Handlebars.parse = function(input) { // Just return if an already-compile AST was passed in. if(input.constructor === Handlebars.AST.ProgramNode) { return input; } Handlebars.Parser.yy = Handlebars.AST; return Handlebars.Parser.parse(input); }; ; // lib/handlebars/compiler/ast.js Handlebars.AST = {}; Handlebars.AST.ProgramNode = function(statements, inverse) { this.type = "program"; this.statements = statements; if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); } }; Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) { this.type = "mustache"; this.escaped = !unescaped; this.hash = hash; var id = this.id = rawParams[0]; var params = this.params = rawParams.slice(1); // a mustache is an eligible helper if: // * its id is simple (a single part, not `this` or `..`) var eligibleHelper = this.eligibleHelper = id.isSimple; // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment this.isHelper = eligibleHelper && (params.length || hash); // if a mustache is an eligible helper but not a definite // helper, it is ambiguous, and will be resolved in a later // pass or at runtime. }; Handlebars.AST.PartialNode = function(partialName, context) { this.type = "partial"; this.partialName = partialName; this.context = context; }; Handlebars.AST.BlockNode = function(mustache, program, inverse, close) { var verifyMatch = function(open, close) { if(open.original !== close.original) { throw new Handlebars.Exception(open.original + " doesn't match " + close.original); } }; verifyMatch(mustache.id, close); this.type = "block"; this.mustache = mustache; this.program = program; this.inverse = inverse; if (this.inverse && !this.program) { this.isInverse = true; } }; Handlebars.AST.ContentNode = function(string) { this.type = "content"; this.string = string; }; Handlebars.AST.HashNode = function(pairs) { this.type = "hash"; this.pairs = pairs; }; Handlebars.AST.IdNode = function(parts) { this.type = "ID"; var original = "", dig = [], depth = 0; for(var i=0,l=parts.length; i<l; i++) { var part = parts[i].part; original += (parts[i].separator || '') + part; if (part === ".." || part === "." || part === "this") { if (dig.length > 0) { throw new Handlebars.Exception("Invalid path: " + original); } else if (part === "..") { depth++; } else { this.isScoped = true; } } else { dig.push(part); } } this.original = original; this.parts = dig; this.string = dig.join('.'); this.depth = depth; // an ID is simple if it only has one part, and that part is not // `..` or `this`. this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; this.stringModeValue = this.string; }; Handlebars.AST.PartialNameNode = function(name) { this.type = "PARTIAL_NAME"; this.name = name.original; }; Handlebars.AST.DataNode = function(id) { this.type = "DATA"; this.id = id; }; Handlebars.AST.StringNode = function(string) { this.type = "STRING"; this.original = this.string = this.stringModeValue = string; }; Handlebars.AST.IntegerNode = function(integer) { this.type = "INTEGER"; this.original = this.integer = integer; this.stringModeValue = Number(integer); }; Handlebars.AST.BooleanNode = function(bool) { this.type = "BOOLEAN"; this.bool = bool; this.stringModeValue = bool === "true"; }; Handlebars.AST.CommentNode = function(comment) { this.type = "comment"; this.comment = comment; }; ; // lib/handlebars/utils.js var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } }; Handlebars.Exception.prototype = new Error(); // Build out our basic SafeString type Handlebars.SafeString = function(string) { this.string = string; }; Handlebars.SafeString.prototype.toString = function() { return this.string.toString(); }; var escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; Handlebars.Utils = { extend: function(obj, value) { for(var key in value) { if(value.hasOwnProperty(key)) { obj[key] = value[key]; } } }, escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); } else if (string == null || string === false) { return ""; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = string.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); }, isEmpty: function(value) { if (!value && value !== 0) { return true; } else if(toString.call(value) === "[object Array]" && value.length === 0) { return true; } else { return false; } } }; ; // lib/handlebars/compiler/compiler.js /*jshint eqnull:true*/ var Compiler = Handlebars.Compiler = function() {}; var JavaScriptCompiler = Handlebars.JavaScriptCompiler = function() {}; // the foundHelper register will disambiguate helper lookup from finding a // function in a context. This is necessary for mustache compatibility, which // requires that context functions in blocks are evaluated by blockHelperMissing, // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler.prototype = { compiler: Compiler, disassemble: function() { var opcodes = this.opcodes, opcode, out = [], params, param; for (var i=0, l=opcodes.length; i<l; i++) { opcode = opcodes[i]; if (opcode.opcode === 'DECLARE') { out.push("DECLARE " + opcode.name + "=" + opcode.value); } else { params = []; for (var j=0; j<opcode.args.length; j++) { param = opcode.args[j]; if (typeof param === "string") { param = "\"" + param.replace("\n", "\\n") + "\""; } params.push(param); } out.push(opcode.opcode + " " + params.join(" ")); } } return out.join("\n"); }, equals: function(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i = 0; i < len; i++) { var opcode = this.opcodes[i], otherOpcode = other.opcodes[i]; if (opcode.opcode !== otherOpcode.opcode || opcode.args.length !== otherOpcode.args.length) { return false; } for (var j = 0; j < opcode.args.length; j++) { if (opcode.args[j] !== otherOpcode.args[j]) { return false; } } } len = this.children.length; if (other.children.length !== len) { return false; } for (i = 0; i < len; i++) { if (!this.children[i].equals(other.children[i])) { return false; } } return true; }, guid: 0, compile: function(program, options) { this.children = []; this.depths = {list: []}; this.options = options; // These changes will propagate to the other compiler components var knownHelpers = this.options.knownHelpers; this.options.knownHelpers = { 'helperMissing': true, 'blockHelperMissing': true, 'each': true, 'if': true, 'unless': true, 'with': true, 'log': true }; if (knownHelpers) { for (var name in knownHelpers) { this.options.knownHelpers[name] = knownHelpers[name]; } } return this.program(program); }, accept: function(node) { return this[node.type](node); }, program: function(program) { var statements = program.statements, statement; this.opcodes = []; for(var i=0, l=statements.length; i<l; i++) { statement = statements[i]; this[statement.type](statement); } this.isSimple = l === 1; this.depths.list = this.depths.list.sort(function(a, b) { return a - b; }); return this; }, compileProgram: function(program) { var result = new this.compiler().compile(program, this.options); var guid = this.guid++, depth; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; for(var i=0, l=result.depths.list.length; i<l; i++) { depth = result.depths.list[i]; if(depth < 2) { continue; } else { this.addDepth(depth - 1); } } return guid; }, block: function(block) { var mustache = block.mustache, program = block.program, inverse = block.inverse; if (program) { program = this.compileProgram(program); } if (inverse) { inverse = this.compileProgram(inverse); } var type = this.classifyMustache(mustache); if (type === "helper") { this.helperMustache(mustache, program, inverse); } else if (type === "simple") { this.simpleMustache(mustache); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('blockValue'); } else { this.ambiguousMustache(mustache, program, inverse); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('ambiguousBlockValue'); } this.opcode('append'); }, hash: function(hash) { var pairs = hash.pairs, pair, val; this.opcode('pushHash'); for(var i=0, l=pairs.length; i<l; i++) { pair = pairs[i]; val = pair[1]; if (this.options.stringParams) { if(val.depth) { this.addDepth(val.depth); } this.opcode('getContext', val.depth || 0); this.opcode('pushStringParam', val.stringModeValue, val.type); } else { this.accept(val); } this.opcode('assignToHash', pair[0]); } this.opcode('popHash'); }, partial: function(partial) { var partialName = partial.partialName; this.usePartial = true; if(partial.context) { this.ID(partial.context); } else { this.opcode('push', 'depth0'); } this.opcode('invokePartial', partialName.name); this.opcode('append'); }, content: function(content) { this.opcode('appendContent', content.string); }, mustache: function(mustache) { var options = this.options; var type = this.classifyMustache(mustache); if (type === "simple") { this.simpleMustache(mustache); } else if (type === "helper") { this.helperMustache(mustache); } else { this.ambiguousMustache(mustache); } if(mustache.escaped && !options.noEscape) { this.opcode('appendEscaped'); } else { this.opcode('append'); } }, ambiguousMustache: function(mustache, program, inverse) { var id = mustache.id, name = id.parts[0], isBlock = program != null || inverse != null; this.opcode('getContext', id.depth); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('invokeAmbiguous', name, isBlock); }, simpleMustache: function(mustache) { var id = mustache.id; if (id.type === 'DATA') { this.DATA(id); } else if (id.parts.length) { this.ID(id); } else { // Simplified ID for `this` this.addDepth(id.depth); this.opcode('getContext', id.depth); this.opcode('pushContext'); } this.opcode('resolvePossibleLambda'); }, helperMustache: function(mustache, program, inverse) { var params = this.setupFullMustacheParams(mustache, program, inverse), name = mustache.id.parts[0]; if (this.options.knownHelpers[name]) { this.opcode('invokeKnownHelper', params.length, name); } else if (this.options.knownHelpersOnly) { throw new Error("You specified knownHelpersOnly, but used the unknown helper " + name); } else { this.opcode('invokeHelper', params.length, name); } }, ID: function(id) { this.addDepth(id.depth); this.opcode('getContext', id.depth); var name = id.parts[0]; if (!name) { this.opcode('pushContext'); } else { this.opcode('lookupOnContext', id.parts[0]); } for(var i=1, l=id.parts.length; i<l; i++) { this.opcode('lookup', id.parts[i]); } }, DATA: function(data) { this.options.data = true; if (data.id.isScoped || data.id.depth) { throw new Handlebars.Exception('Scoped data references are not supported: ' + data.original); } this.opcode('lookupData'); var parts = data.id.parts; for(var i=0, l=parts.length; i<l; i++) { this.opcode('lookup', parts[i]); } }, STRING: function(string) { this.opcode('pushString', string.string); }, INTEGER: function(integer) { this.opcode('pushLiteral', integer.integer); }, BOOLEAN: function(bool) { this.opcode('pushLiteral', bool.bool); }, comment: function() {}, // HELPERS opcode: function(name) { this.opcodes.push({ opcode: name, args: [].slice.call(arguments, 1) }); }, declare: function(name, value) { this.opcodes.push({ opcode: 'DECLARE', name: name, value: value }); }, addDepth: function(depth) { if(isNaN(depth)) { throw new Error("EWOT"); } if(depth === 0) { return; } if(!this.depths[depth]) { this.depths[depth] = true; this.depths.list.push(depth); } }, classifyMustache: function(mustache) { var isHelper = mustache.isHelper; var isEligible = mustache.eligibleHelper; var options = this.options; // if ambiguous, we can possibly resolve the ambiguity now if (isEligible && !isHelper) { var name = mustache.id.parts[0]; if (options.knownHelpers[name]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return "helper"; } else if (isEligible) { return "ambiguous"; } else { return "simple"; } }, pushParams: function(params) { var i = params.length, param; while(i--) { param = params[i]; if(this.options.stringParams) { if(param.depth) { this.addDepth(param.depth); } this.opcode('getContext', param.depth || 0); this.opcode('pushStringParam', param.stringModeValue, param.type); } else { this[param.type](param); } } }, setupMustacheParams: function(mustache) { var params = mustache.params; this.pushParams(params); if(mustache.hash) { this.hash(mustache.hash); } else { this.opcode('emptyHash'); } return params; }, // this will replace setupMustacheParams when we're done setupFullMustacheParams: function(mustache, program, inverse) { var params = mustache.params; this.pushParams(params); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); if(mustache.hash) { this.hash(mustache.hash); } else { this.opcode('emptyHash'); } return params; } }; var Literal = function(value) { this.value = value; }; JavaScriptCompiler.prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup: function(parent, name /* , type*/) { if (/^[0-9]+$/.test(name)) { return parent + "[" + name + "]"; } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { return parent + "." + name; } else { return parent + "['" + name + "']"; } }, appendToBuffer: function(string) { if (this.environment.isSimple) { return "return " + string + ";"; } else { return { appendToBuffer: true, content: string, toString: function() { return "buffer += " + string + ";"; } }; } }, initializeBuffer: function() { return this.quotedString(""); }, namespace: "Handlebars", // END PUBLIC API compile: function(environment, options, context, asObject) { this.environment = environment; this.options = options || {}; Handlebars.log(Handlebars.logger.DEBUG, this.environment.disassemble() + "\n\n"); this.name = this.environment.name; this.isChild = !!context; this.context = context || { programs: [], environments: [], aliases: { } }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.registers = { list: [] }; this.compileStack = []; this.inlineStack = []; this.compileChildren(environment, options); var opcodes = environment.opcodes, opcode; this.i = 0; for(l=opcodes.length; this.i<l; this.i++) { opcode = opcodes[this.i]; if(opcode.opcode === 'DECLARE') { this[opcode.name] = opcode.value; } else { this[opcode.opcode].apply(this, opcode.args); } } return this.createFunctionContext(asObject); }, nextOpcode: function() { var opcodes = this.environment.opcodes; return opcodes[this.i + 1]; }, eat: function() { this.i = this.i + 1; }, preamble: function() { var out = []; if (!this.isChild) { var namespace = this.namespace; var copies = "helpers = this.merge(helpers, " + namespace + ".helpers);"; if (this.environment.usePartial) { copies = copies + " partials = this.merge(partials, " + namespace + ".partials);"; } if (this.options.data) { copies = copies + " data = data || {};"; } out.push(copies); } else { out.push(''); } if (!this.environment.isSimple) { out.push(", buffer = " + this.initializeBuffer()); } else { out.push(""); } // track the last context pushed into place to allow skipping the // getContext opcode when it would be a noop this.lastContext = 0; this.source = out; }, createFunctionContext: function(asObject) { var locals = this.stackVars.concat(this.registers.list); if(locals.length > 0) { this.source[1] = this.source[1] + ", " + locals.join(", "); } // Generate minimizer alias mappings if (!this.isChild) { for (var alias in this.context.aliases) { if (this.context.aliases.hasOwnProperty(alias)) { this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; } } } if (this.source[1]) { this.source[1] = "var " + this.source[1].substring(2) + ";"; } // Merge children if (!this.isChild) { this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; } if (!this.environment.isSimple) { this.source.push("return buffer;"); } var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; for(var i=0, l=this.environment.depths.list.length; i<l; i++) { params.push("depth" + this.environment.depths.list[i]); } // Perform a second pass over the output to merge content when possible var source = this.mergeSource(); if (!this.isChild) { var revision = Handlebars.COMPILER_REVISION, versions = Handlebars.REVISION_CHANGES[revision]; source = "this.compilerInfo = ["+revision+",'"+versions+"'];\n"+source; } if (asObject) { params.push(source); return Function.apply(this, params); } else { var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + source + '}'; Handlebars.log(Handlebars.logger.DEBUG, functionSource + "\n\n"); return functionSource; } }, mergeSource: function() { // WARN: We are not handling the case where buffer is still populated as the source should // not have buffer append operations as their final action. var source = '', buffer; for (var i = 0, len = this.source.length; i < len; i++) { var line = this.source[i]; if (line.appendToBuffer) { if (buffer) { buffer = buffer + '\n + ' + line.content; } else { buffer = line.content; } } else { if (buffer) { source += 'buffer += ' + buffer + ';\n '; buffer = undefined; } source += line + '\n '; } } return source; }, // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#foo}}...{{/foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); this.replaceStack(function(current) { params.splice(1, 0, current); return "blockHelperMissing.call(" + params.join(", ") + ")"; }); }, // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); var current = this.topStack(); params.splice(1, 0, current); // Use the options value generated from the invocation params[params.length-1] = 'options'; this.source.push("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }"); }, // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent: function(content) { this.source.push(this.appendToBuffer(this.quotedString(content))); }, // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append: function() { // Force anything that is inlined onto the stack so we don't have duplication // when we examine local this.flushInline(); var local = this.popStack(); this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }"); if (this.environment.isSimple) { this.source.push("else { " + this.appendToBuffer("''") + " }"); } }, // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped: function() { this.context.aliases.escapeExpression = 'this.escapeExpression'; this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")")); }, // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext: function(depth) { if(this.lastContext !== depth) { this.lastContext = depth; } }, // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext: function(name) { this.push(this.nameLookup('depth' + this.lastContext, name, 'context')); }, // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext: function() { this.pushStackLiteral('depth' + this.lastContext); }, // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda: function() { this.context.aliases.functionType = '"function"'; this.replaceStack(function(current) { return "typeof " + current + " === functionType ? " + current + ".apply(depth0) : " + current; }); }, // [lookup] // // On stack, before: value, ... // On stack, after: value[name], ... // // Replace the value on the stack with the result of looking // up `name` on `value` lookup: function(name) { this.replaceStack(function(current) { return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context'); }); }, // [lookupData] // // On stack, before: ... // On stack, after: data[id], ... // // Push the result of looking up `id` on the current data lookupData: function(id) { this.push('data'); }, // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam: function(string, type) { this.pushStackLiteral('depth' + this.lastContext); this.pushString(type); if (typeof string === 'string') { this.pushString(string); } else { this.pushStackLiteral(string); } }, emptyHash: function() { this.pushStackLiteral('{}'); if (this.options.stringParams) { this.register('hashTypes', '{}'); this.register('hashContexts', '{}'); } }, pushHash: function() { this.hash = {values: [], types: [], contexts: []}; }, popHash: function() { var hash = this.hash; this.hash = undefined; if (this.options.stringParams) { this.register('hashContexts', '{' + hash.contexts.join(',') + '}'); this.register('hashTypes', '{' + hash.types.join(',') + '}'); } this.push('{\n ' + hash.values.join(',\n ') + '\n }'); }, // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString: function(string) { this.pushStackLiteral(this.quotedString(string)); }, // [push] // // On stack, before: ... // On stack, after: expr, ... // // Push an expression onto the stack push: function(expr) { this.inlineStack.push(expr); return expr; }, // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral: function(value) { this.pushStackLiteral(value); }, // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram: function(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper: function(paramSize, name) { this.context.aliases.helperMissing = 'helpers.helperMissing'; var helper = this.lastHelper = this.setupHelper(paramSize, name, true); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); this.push(helper.name + ' || ' + nonHelper); this.replaceStack(function(name) { return name + ' ? ' + name + '.call(' + helper.callParams + ") " + ": helperMissing.call(" + helper.helperMissingParams + ")"; }); }, // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper: function(paramSize, name) { var helper = this.setupHelper(paramSize, name); this.push(helper.name + ".call(" + helper.callParams + ")"); }, // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous: function(name, helperCall) { this.context.aliases.functionType = '"function"'; this.pushStackLiteral('{}'); // Hash value var helper = this.setupHelper(0, name, helperCall); var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); var nextStack = this.nextStack(); this.source.push('if (' + nextStack + ' = ' + helperName + ') { ' + nextStack + ' = ' + nextStack + '.call(' + helper.callParams + '); }'); this.source.push('else { ' + nextStack + ' = ' + nonHelper + '; ' + nextStack + ' = typeof ' + nextStack + ' === functionType ? ' + nextStack + '.apply(depth0) : ' + nextStack + '; }'); }, // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial: function(name) { var params = [this.nameLookup('partials', name, 'partial'), "'" + name + "'", this.popStack(), "helpers", "partials"]; if (this.options.data) { params.push("data"); } this.context.aliases.self = "this"; this.push("self.invokePartial(" + params.join(", ") + ")"); }, // [assignToHash] // // On stack, before: value, hash, ... // On stack, after: hash, ... // // Pops a value and hash off the stack, assigns `hash[key] = value` // and pushes the hash back onto the stack. assignToHash: function(key) { var value = this.popStack(), context, type; if (this.options.stringParams) { type = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts.push("'" + key + "': " + context); } if (type) { hash.types.push("'" + key + "': " + type); } hash.values.push("'" + key + "': (" + value + ")"); }, // HELPERS compiler: JavaScriptCompiler, compileChildren: function(environment, options) { var children = environment.children, child, compiler; for(var i=0, l=children.length; i<l; i++) { child = children[i]; compiler = new this.compiler(); var index = this.matchExistingProgram(child); if (index == null) { this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children index = this.context.programs.length; child.index = index; child.name = 'program' + index; this.context.programs[index] = compiler.compile(child, options, this.context); this.context.environments[index] = child; } else { child.index = index; child.name = 'program' + index; } } }, matchExistingProgram: function(child) { for (var i = 0, len = this.context.environments.length; i < len; i++) { var environment = this.context.environments[i]; if (environment && environment.equals(child)) { return i; } } }, programExpression: function(guid) { this.context.aliases.self = "this"; if(guid == null) { return "self.noop"; } var child = this.environment.children[guid], depths = child.depths.list, depth; var programParams = [child.index, child.name, "data"]; for(var i=0, l = depths.length; i<l; i++) { depth = depths[i]; if(depth === 1) { programParams.push("depth0"); } else { programParams.push("depth" + (depth - 1)); } } return (depths.length === 0 ? "self.program(" : "self.programWithDepth(") + programParams.join(", ") + ")"; }, register: function(name, val) { this.useRegister(name); this.source.push(name + " = " + val + ";"); }, useRegister: function(name) { if(!this.registers[name]) { this.registers[name] = true; this.registers.list.push(name); } }, pushStackLiteral: function(item) { return this.push(new Literal(item)); }, pushStack: function(item) { this.flushInline(); var stack = this.incrStack(); if (item) { this.source.push(stack + " = " + item + ";"); } this.compileStack.push(stack); return stack; }, replaceStack: function(callback) { var prefix = '', inline = this.isInline(), stack; // If we are currently inline then we want to merge the inline statement into the // replacement statement via ',' if (inline) { var top = this.popStack(true); if (top instanceof Literal) { // Literals do not need to be inlined stack = top.value; } else { // Get or create the current stack name for use by the inline var name = this.stackSlot ? this.topStackName() : this.incrStack(); prefix = '(' + this.push(name) + ' = ' + top + '),'; stack = this.topStack(); } } else { stack = this.topStack(); } var item = callback.call(this, stack); if (inline) { if (this.inlineStack.length || this.compileStack.length) { this.popStack(); } this.push('(' + prefix + item + ')'); } else { // Prevent modification of the context depth variable. Through replaceStack if (!/^stack/.test(stack)) { stack = this.nextStack(); } this.source.push(stack + " = (" + prefix + item + ");"); } return stack; }, nextStack: function() { return this.pushStack(); }, incrStack: function() { this.stackSlot++; if(this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return this.topStackName(); }, topStackName: function() { return "stack" + this.stackSlot; }, flushInline: function() { var inlineStack = this.inlineStack; if (inlineStack.length) { this.inlineStack = []; for (var i = 0, len = inlineStack.length; i < len; i++) { var entry = inlineStack[i]; if (entry instanceof Literal) { this.compileStack.push(entry); } else { this.pushStack(entry); } } } }, isInline: function() { return this.inlineStack.length; }, popStack: function(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && (item instanceof Literal)) { return item.value; } else { if (!inline) { this.stackSlot--; } return item; } }, topStack: function(wrapped) { var stack = (this.isInline() ? this.inlineStack : this.compileStack), item = stack[stack.length - 1]; if (!wrapped && (item instanceof Literal)) { return item.value; } else { return item; } }, quotedString: function(str) { return '"' + str .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 .replace(/\u2029/g, '\\u2029') + '"'; }, setupHelper: function(paramSize, name, missingParams) { var params = []; this.setupParams(paramSize, params, missingParams); var foundHelper = this.nameLookup('helpers', name, 'helper'); return { params: params, name: foundHelper, callParams: ["depth0"].concat(params).join(", "), helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") }; }, // the params and contexts arguments are passed in arrays // to fill in setupParams: function(paramSize, params, useRegister) { var options = [], contexts = [], types = [], param, inverse, program; options.push("hash:" + this.popStack()); inverse = this.popStack(); program = this.popStack(); // Avoid setting fn and inverse if neither are set. This allows // helpers to do a check for `if (options.fn)` if (program || inverse) { if (!program) { this.context.aliases.self = "this"; program = "self.noop"; } if (!inverse) { this.context.aliases.self = "this"; inverse = "self.noop"; } options.push("inverse:" + inverse); options.push("fn:" + program); } for(var i=0; i<paramSize; i++) { param = this.popStack(); params.push(param); if(this.options.stringParams) { types.push(this.popStack()); contexts.push(this.popStack()); } } if (this.options.stringParams) { options.push("contexts:[" + contexts.join(",") + "]"); options.push("types:[" + types.join(",") + "]"); options.push("hashContexts:hashContexts"); options.push("hashTypes:hashTypes"); } if(this.options.data) { options.push("data:data"); } options = "{" + options.join(",") + "}"; if (useRegister) { this.register('options', options); params.push('options'); } else { params.push(options); } return params.join(", "); } }; var reservedWords = ( "break else new var" + " case finally return void" + " catch for switch while" + " continue function this with" + " default if throw" + " delete in try" + " do instanceof typeof" + " abstract enum int short" + " boolean export interface static" + " byte extends long super" + " char final native synchronized" + " class float package throws" + " const goto private transient" + " debugger implements protected volatile" + " double import public let yield" ).split(" "); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for(var i=0, l=reservedWords.length; i<l; i++) { compilerWords[reservedWords[i]] = true; } JavaScriptCompiler.isValidJavaScriptVariableName = function(name) { if(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) { return true; } return false; }; Handlebars.precompile = function(input, options) { if (input == null || (typeof input !== 'string' && input.constructor !== Handlebars.AST.ProgramNode)) { throw new Handlebars.Exception("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var ast = Handlebars.parse(input); var environment = new Compiler().compile(ast, options); return new JavaScriptCompiler().compile(environment, options); }; Handlebars.compile = function(input, options) { if (input == null || (typeof input !== 'string' && input.constructor !== Handlebars.AST.ProgramNode)) { throw new Handlebars.Exception("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var compiled; function compile() { var ast = Handlebars.parse(input); var environment = new Compiler().compile(ast, options); var templateSpec = new JavaScriptCompiler().compile(environment, options, undefined, true); return Handlebars.template(templateSpec); } // Template is only compiled on first use and cached after that point. return function(context, options) { if (!compiled) { compiled = compile(); } return compiled.call(this, context, options); }; }; ; // lib/handlebars/runtime.js Handlebars.VM = { template: function(templateSpec) { // Just add water var container = { escapeExpression: Handlebars.Utils.escapeExpression, invokePartial: Handlebars.VM.invokePartial, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { programWrapper = Handlebars.VM.program(i, fn, data); } else if (!programWrapper) { programWrapper = this.programs[i] = Handlebars.VM.program(i, fn); } return programWrapper; }, merge: function(param, common) { var ret = param || common; if (param && common) { ret = {}; Handlebars.Utils.extend(ret, common); Handlebars.Utils.extend(ret, param); } return ret; }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop, compilerInfo: null }; return function(context, options) { options = options || {}; var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data); var compilerInfo = container.compilerInfo || [], compilerRevision = compilerInfo[0] || 1, currentRevision = Handlebars.COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision], compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision]; throw "Template was precompiled with an older version of Handlebars than the current runtime. "+ "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."; } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw "Template was precompiled with a newer version of Handlebars than the current runtime. "+ "Please update your runtime to a newer version ("+compilerInfo[1]+")."; } } return result; }; }, programWithDepth: function(i, fn, data /*, $depth */) { var args = Array.prototype.slice.call(arguments, 3); var program = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; program.program = i; program.depth = args.length; return program; }, program: function(i, fn, data) { var program = function(context, options) { options = options || {}; return fn(context, options.data || data); }; program.program = i; program.depth = 0; return program; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) { var options = { helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Handlebars.Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } else if (!Handlebars.compile) { throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } else { partials[name] = Handlebars.compile(partial, {data: data !== undefined}); return partials[name](context, options); } } }; Handlebars.template = Handlebars.VM.template; ; // lib/handlebars/browser-suffix.js })(Handlebars); ; // Underscore.js 1.4.4 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // 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 nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, 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 via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.4.4'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); 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`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // 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 (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // 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, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs, first) { if (_.isEmpty(attrs)) return first ? null : []; return _[first ? 'find' : 'filter'](obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.where(obj, attrs, true); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See: https://bugs.webkit.org/show_bug.cgi?id=80797 _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value : value, index : index, criteria : iterator.call(context, 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 ? -1 : 1; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(obj, value, context, behavior) { var result = {}; var iterator = lookupIterator(value || _.identity); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); 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 = function(obj, value, context) { return group(obj, value, context, function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(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 = function(obj, value, context) { return group(obj, value, context, function(result, key) { if (!_.has(result, key)) result[key] = 0; result[key]++; }); }; // 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, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.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; }; // 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; return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // 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, 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 slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // 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, output) { each(input, function(value) { if (_.isArray(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // 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, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(concat.apply(ArrayProto, arguments)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // 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 = concat.apply(ArrayProto, slice.call(arguments, 1)); 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() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(args, "" + 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, l = list.length; i < l; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // 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, l = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < l; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; 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 = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // 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) { if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); var args = slice.call(arguments, 2); return function() { return func.apply(context, args.concat(slice.call(arguments))); }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _.partial = function(func) { var args = slice.call(arguments, 1); return function() { return func.apply(this, args.concat(slice.call(arguments))); }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // 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. _.throttle = function(func, wait) { var context, args, timeout, result; var previous = 0; var later = function() { previous = new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { 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, result; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) result = func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // 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 function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // 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 funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var values = []; for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var pairs = []; for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; 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) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] == null) 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, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (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; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } 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; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // 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 { // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // 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)) 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) { return obj === 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 !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // 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 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 iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(n); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, 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)); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named property is a function then invoke it; // otherwise, return it. _.result = function(object, property) { if (object == null) return null; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // 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)); }; }); }; // 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', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new 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, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; 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 { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // 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 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)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); }).call(this); // Backbone.js 1.1.0 // (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc. // (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(){ // Initial Setup // ------------- // Save a reference to the global object (`window` in the browser, `exports` // on the server). var root = this; // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // The top-level namespace. All public Backbone classes and modules will // be attached to this. Exported for both the browser and the server. var Backbone; if (typeof exports !== 'undefined') { Backbone = exports; } else { Backbone = root.Backbone = {}; } // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.1.0'; // Require Underscore, if we're on the server, and it's not already present. var _ = root._; if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. 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; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. 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); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. 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 = {}; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { 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 one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(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; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. 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; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. 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; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). 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); } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[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; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = true; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true}, options); // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !options.wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return this.id == null; }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model); } return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); var i, l, id, model, attrs, existing, sort; var at = options.at; var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { attrs = models[i]; if (attrs instanceof Model) { id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute]; } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; if (merge) { attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); // Listen to added models' events, and index models for lookup by // `id` and by `cid`. model.on('all', this._onModelEvent, this); this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; } if (order) order.push(existing || model); } // Remove nonexistent models if appropriate. if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i]); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp, options) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) { if (!attrs.collection) attrs.collection = this; return attrs; } options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method to sever a model's ties to a collection. _removeReference: function(model) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. 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; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _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 = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); callback && callback.apply(router, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^\/]+)'; }) .replace(splatParam, '(.*?)'); return new RegExp('^' + route + '$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param) { return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Cached regex for stripping urls of hash and query. var pathStripper = /[?#].*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = this.location.pathname; var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow; this.navigate(fragment); } // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { Backbone.$(window).on('popstate', this.checkUrl); } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) { Backbone.$(window).on('hashchange', this.checkUrl); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } // Determine if we need to change the base url, for a pushState link // opened by a non-pushState browser. this.fragment = fragment; var loc = this.location; var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !atRoot) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + this.location.search + '#' + this.fragment); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && atRoot && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment + loc.search); } } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl); clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); if (current === this.fragment && this.iframe) { current = this.getFragment(this.getHash(this.iframe)); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { fragment = this.fragment = this.getFragment(fragment); return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; var url = this.root + (fragment = this.getFragment(fragment || '')); // Strip the fragment of the query and hash for matching. fragment = fragment.replace(pathStripper, ''); if (this.fragment === fragment) return; this.fragment = fragment; // Don't include a trailing slash on the root. if (fragment === '' && url !== '/') url = url.slice(0, -1); // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) { // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if(!options.replace) this.iframe.document.open().close(); this._updateHash(this.iframe.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); model.trigger('error', model, resp, options); }; }; }).call(this); /* Copyright (c) 2011-2013 @WalmartLabs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ ;; (function() { /*global cloneInheritVars, createInheritVars, resetInheritVars, createRegistryWrapper, getValue, inheritVars, createErrorMessage */ //support zepto.forEach on jQuery if (!$.fn.forEach) { $.fn.forEach = function(iterator, context) { $.fn.each.call(this, function(index) { iterator.call(context || this, this, index); }); }; } var viewNameAttributeName = 'data-view-name', viewCidAttributeName = 'data-view-cid', viewHelperAttributeName = 'data-view-helper'; //view instances var viewsIndexedByCid = {}; if (!Handlebars.templates) { Handlebars.templates = {}; } var Thorax = this.Thorax = { templatePathPrefix: '', //view classes Views: {}, //certain error prone pieces of code (on Android only it seems) //are wrapped in a try catch block, then trigger this handler in //the catch, with the name of the function or event that was //trying to be executed. Override this with a custom handler //to debug / log / etc onException: function(name, err) { throw err; }, //deprecated, here to ensure existing projects aren't mucked with templates: Handlebars.templates }; Thorax.View = Backbone.View.extend({ constructor: function() { // store first argument for configureView() this._constructorArg = arguments[0]; var response = Backbone.View.apply(this, arguments); delete this._constructorArg; _.each(inheritVars, function(obj) { if (obj.ctor) { obj.ctor.call(this, response); } }, this); return response; }, // View configuration, _configure was removed // in Backbone 1.1, define _configure as a noop // for Backwards compatibility with 1.0 and earlier _configure: function() {}, _ensureElement: function () { configureView.call(this); return Backbone.View.prototype._ensureElement.call(this); }, toString: function() { return '[object View.' + this.name + ']'; }, setElement : function() { var response = Backbone.View.prototype.setElement.apply(this, arguments); this.name && this.$el.attr(viewNameAttributeName, this.name); this.$el.attr(viewCidAttributeName, this.cid); return response; }, _addChild: function(view) { if (this.children[view.cid]) { return view; } view.retain(); this.children[view.cid] = view; // _helperOptions is used to detect if is HelperView // we do not want to remove child in this case as // we are adding the HelperView to the declaring view // (whatever view used the view helper in it's template) // but it's parent will not equal the declaring view // in the case of a nested helper, which will cause an error. // In either case it's not necessary to ever call // _removeChild on a HelperView as _addChild should only // be called when a HelperView is created. if (view.parent && view.parent !== this && !view._helperOptions) { view.parent._removeChild(view); } view.parent = this; this.trigger('child', view); return view; }, _removeChild: function(view) { delete this.children[view.cid]; view.parent = null; view.release(); return view; }, _destroy: function(options) { _.each(this._boundDataObjectsByCid, this.unbindDataObject, this); this.trigger('destroyed'); delete viewsIndexedByCid[this.cid]; _.each(this.children, function(child) { this._removeChild(child); }, this); if (this.el) { this.undelegateEvents(); this.remove(); // Will call stopListening() this.off(); // Kills off remaining events } // Absolute worst case scenario, kill off some known fields to minimize the impact // of being retained. this.el = this.$el = undefined; this.parent = undefined; this.model = this.collection = this._collection = undefined; this._helperOptions = undefined; }, render: function(output) { // NOP for destroyed views if (!this.el) { return; } if (this._rendering) { // Nested rendering of the same view instances can lead to some very nasty issues with // the root render process overwriting any updated data that may have been output in the child // execution. If in a situation where you need to rerender in response to an event that is // triggered sync in the rendering lifecycle it's recommended to defer the subsequent render // or refactor so that all preconditions are known prior to exec. throw new Error(createErrorMessage('nested-render')); } this._previousHelpers = _.filter(this.children, function(child) { return child._helperOptions; }); var children = {}; _.each(this.children, function(child, key) { if (!child._helperOptions) { children[key] = child; } }); this.children = children; this.trigger('before:rendered'); this._rendering = true; try { if (_.isUndefined(output) || (!_.isElement(output) && !Thorax.Util.is$(output) && !(output && output.el) && !_.isString(output) && !_.isFunction(output))) { // try one more time to assign the template, if we don't // yet have one we must raise assignTemplate.call(this, 'template', { required: true }); output = this.renderTemplate(this.template); } else if (_.isFunction(output)) { output = this.renderTemplate(output); } // Destroy any helpers that may be lingering _.each(this._previousHelpers, function(child) { this._removeChild(child); }, this); this._previousHelpers = undefined; //accept a view, string, Handlebars.SafeString or DOM element this.html((output && output.el) || (output && output.string) || output); ++this._renderCount; this.trigger('rendered'); } finally { this._rendering = false; } return output; }, context: function() { return _.extend({}, (this.model && this.model.attributes) || {}); }, _getContext: function() { return _.extend({}, this, getValue(this, 'context') || {}); }, // Private variables in handlebars / options.data in template helpers _getData: function(data) { return { view: this, cid: _.uniqueId('t'), yield: function() { // fn is seeded by template helper passing context to data return data.fn && data.fn(data); } }; }, renderTemplate: function(file, context, ignoreErrors) { var template; context = context || this._getContext(); if (_.isFunction(file)) { template = file; } else { template = Thorax.Util.getTemplate(file, ignoreErrors); } if (!template) { return ''; } else { return template(context, { helpers: this.helpers, data: this._getData(context) }); } }, ensureRendered: function() { !this._renderCount && this.render(); }, shouldRender: function(flag) { // Render if flag is truthy or if we have already rendered and flag is undefined/null return flag || (flag == null && this._renderCount); }, conditionalRender: function(flag) { if (this.shouldRender(flag)) { this.render(); } }, appendTo: function(el) { this.ensureRendered(); $(el).append(this.el); this.trigger('ready', {target: this}); }, html: function(html) { if (_.isUndefined(html)) { return this.el.innerHTML; } else { // Event for IE element fixes this.trigger('before:append'); var element = this._replaceHTML(html); this.trigger('append'); return element; } }, release: function() { --this._referenceCount; if (this._referenceCount <= 0) { this._destroy(); } }, retain: function(owner) { ++this._referenceCount; if (owner) { // Not using listenTo helper as we want to run once the owner is destroyed this.listenTo(owner, 'destroyed', owner.release); } }, _replaceHTML: function(html) { this.el.innerHTML = ""; return this.$el.append(html); }, _anchorClick: function(event) { var target = $(event.currentTarget), href = target.attr('href'); // Route anything that starts with # or / (excluding //domain urls) if (href && (href[0] === '#' || (href[0] === '/' && href[1] !== '/'))) { Backbone.history.navigate(href, { trigger: true }); return false; } return true; } }); Thorax.View.extend = function() { createInheritVars(this); var child = Backbone.View.extend.apply(this, arguments); child.__parent__ = this; resetInheritVars(child); return child; }; createRegistryWrapper(Thorax.View, Thorax.Views); function configureView () { var options = this._constructorArg; var self = this; this._referenceCount = 0; this._objectOptionsByCid = {}; this._boundDataObjectsByCid = {}; // Setup object event tracking _.each(inheritVars, function(obj) { self[obj.name] = []; }); viewsIndexedByCid[this.cid] = this; this.children = {}; this._renderCount = 0; //this.options is removed in Thorax.View, we merge passed //properties directly with the view and template context _.extend(this, options || {}); // Setup helpers bindHelpers.call(this); _.each(inheritVars, function(obj) { if (obj.configure) { obj.configure.call(this); } }, this); this.trigger('configure'); } function bindHelpers() { if (this.helpers) { _.each(this.helpers, function(helper, name) { var view = this; this.helpers[name] = function() { var args = _.toArray(arguments), options = _.last(args); options.context = this; return helper.apply(view, args); }; }, this); } } //$(selector).view() helper $.fn.view = function(options) { options = _.defaults(options || {}, { helper: true }); var selector = '[' + viewCidAttributeName + ']'; if (!options.helper) { selector += ':not([' + viewHelperAttributeName + '])'; } var el = $(this).closest(selector); return (el && viewsIndexedByCid[el.attr(viewCidAttributeName)]) || false; }; ;; /*global createRegistryWrapper:true, cloneEvents: true */ function createErrorMessage(code) { return 'Error "' + code + '". For more information visit http://thoraxjs.org/error-codes.html' + '#' + code; } function createRegistryWrapper(klass, hash) { var $super = klass.extend; klass.extend = function() { var child = $super.apply(this, arguments); if (child.prototype.name) { hash[child.prototype.name] = child; } return child; }; } function registryGet(object, type, name, ignoreErrors) { var target = object[type], value; if (_.indexOf(name, '.') >= 0) { var bits = name.split(/\./); name = bits.pop(); _.each(bits, function(key) { target = target[key]; }); } target && (value = target[name]); if (!value && !ignoreErrors) { throw new Error(type + ': ' + name + ' does not exist.'); } else { return value; } } function assignView(attributeName, options) { var ViewClass; // if attribute is the name of view to fetch if (_.isString(this[attributeName])) { ViewClass = Thorax.Util.getViewClass(this[attributeName], true); // else try and fetch the view based on the name } else if (this.name && !_.isFunction(this[attributeName])) { ViewClass = Thorax.Util.getViewClass(this.name + (options.extension || ''), true); } // if we found something, assign it if (ViewClass && !_.isFunction(this[attributeName])) { this[attributeName] = ViewClass; } // if nothing was found and it's required, throw if (options.required && !_.isFunction(this[attributeName])) { throw new Error('View ' + (this.name || this.cid) + ' requires: ' + attributeName); } } function assignTemplate(attributeName, options) { var template; // if attribute is the name of template to fetch if (_.isString(this[attributeName])) { template = Thorax.Util.getTemplate(this[attributeName], true); // else try and fetch the template based on the name } else if (this.name && !_.isFunction(this[attributeName])) { template = Thorax.Util.getTemplate(this.name + (options.extension || ''), true); } // CollectionView and LayoutView have a defaultTemplate that may be used if none // was found, regular views must have a template if render() is called if (!template && attributeName === 'template' && this._defaultTemplate) { template = this._defaultTemplate; } // if we found something, assign it if (template && !_.isFunction(this[attributeName])) { this[attributeName] = template; } // if nothing was found and it's required, throw if (options.required && !_.isFunction(this[attributeName])) { throw new Error('View ' + (this.name || this.cid) + ' requires: ' + attributeName); } } // getValue is used instead of _.result because we // need an extra scope parameter, and will minify // better than _.result function getValue(object, prop, scope) { if (!(object && object[prop])) { return null; } return _.isFunction(object[prop]) ? object[prop].call(scope || object) : object[prop]; } var inheritVars = {}; function createInheritVars(self) { // Ensure that we have our static event objects _.each(inheritVars, function(obj) { if (!self[obj.name]) { self[obj.name] = []; } }); } function resetInheritVars(self) { // Ensure that we have our static event objects _.each(inheritVars, function(obj) { self[obj.name] = []; }); } function walkInheritTree(source, fieldName, isStatic, callback) { var tree = []; if (_.has(source, fieldName)) { tree.push(source); } var iterate = source; if (isStatic) { while (iterate = iterate.__parent__) { if (_.has(iterate, fieldName)) { tree.push(iterate); } } } else { iterate = iterate.constructor; while (iterate) { if (iterate.prototype && _.has(iterate.prototype, fieldName)) { tree.push(iterate.prototype); } iterate = iterate.__super__ && iterate.__super__.constructor; } } var i = tree.length; while (i--) { _.each(getValue(tree[i], fieldName, source), callback); } } function objectEvents(target, eventName, callback, context) { if (_.isObject(callback)) { var spec = inheritVars[eventName]; if (spec && spec.event) { if (target && target.listenTo && target[eventName] && target[eventName].cid) { addEvents(target, callback, context, eventName); } else { addEvents(target['_' + eventName + 'Events'], callback, context); } return true; } } } // internal listenTo function will error on destroyed // race condition function listenTo(object, target, eventName, callback, context) { // getEventCallback will resolve if it is a string or a method // and return a method var callbackMethod = getEventCallback(callback, object), destroyedCount = 0; function eventHandler() { if (object.el) { callbackMethod.apply(context, arguments); } else { // If our event handler is removed by destroy while another event is processing then we // we might see one latent event percolate through due to caching in the event loop. If we // see multiple events this is a concern and a sign that something was not cleaned properly. if (destroyedCount) { throw new Error('destroyed-event:' + object.name + ':' + eventName); } destroyedCount++; } } eventHandler._callback = callbackMethod._callback || callbackMethod; eventHandler._thoraxBind = true; object.listenTo(target, eventName, eventHandler); } function addEvents(target, source, context, listenToObject) { function addEvent(callback, eventName) { if (listenToObject) { listenTo(target, target[listenToObject], eventName, callback, context || target); } else { target.push([eventName, callback, context]); } } _.each(source, function(callback, eventName) { if (_.isArray(callback)) { _.each(callback, function(cb) { addEvent(cb, eventName); }); } else { addEvent(callback, eventName); } }); } function getOptionsData(options) { if (!options || !options.data) { throw new Error(createErrorMessage('handlebars-no-data')); } return options.data; } // In helpers "tagName" or "tag" may be specified, as well // as "class" or "className". Normalize to "tagName" and // "className" to match the property names used by Backbone // jQuery, etc. Special case for "className" in // Thorax.Util.tag: will be rewritten as "class" in // generated HTML. function normalizeHTMLAttributeOptions(options) { if (options.tag) { options.tagName = options.tag; delete options.tag; } if (options['class']) { options.className = options['class']; delete options['class']; } } Thorax.Util = { getViewInstance: function(name, attributes) { var ViewClass = Thorax.Util.getViewClass(name, true); return ViewClass ? new ViewClass(attributes || {}) : name; }, getViewClass: function(name, ignoreErrors) { if (_.isString(name)) { return registryGet(Thorax, 'Views', name, ignoreErrors); } else if (_.isFunction(name)) { return name; } else { return false; } }, getTemplate: function(file, ignoreErrors) { //append the template path prefix if it is missing var pathPrefix = Thorax.templatePathPrefix, template; if (pathPrefix && file.substr(0, pathPrefix.length) !== pathPrefix) { file = pathPrefix + file; } // Without extension file = file.replace(/\.handlebars$/, ''); template = Handlebars.templates[file]; if (!template) { // With extension file = file + '.handlebars'; template = Handlebars.templates[file]; } if (!template && !ignoreErrors) { throw new Error('templates: ' + file + ' does not exist.'); } return template; }, //'selector' is not present in $('<p></p>') //TODO: investigage a better detection method is$: function(obj) { return _.isObject(obj) && ('length' in obj); }, expandToken: function(input, scope) { if (input && input.indexOf && input.indexOf('{{') >= 0) { var re = /(?:\{?[^{]+)|(?:\{\{([^}]+)\}\})/g, match, ret = []; function deref(token, scope) { if (token.match(/^("|')/) && token.match(/("|')$/)) { return token.replace(/(^("|')|('|")$)/g, ''); } var segments = token.split('.'), len = segments.length; for (var i = 0; scope && i < len; i++) { if (segments[i] !== 'this') { scope = scope[segments[i]]; } } return scope; } while (match = re.exec(input)) { if (match[1]) { var params = match[1].split(/\s+/); if (params.length > 1) { var helper = params.shift(); params = _.map(params, function(param) { return deref(param, scope); }); if (Handlebars.helpers[helper]) { ret.push(Handlebars.helpers[helper].apply(scope, params)); } else { // If the helper is not defined do nothing ret.push(match[0]); } } else { ret.push(deref(params[0], scope)); } } else { ret.push(match[0]); } } input = ret.join(''); } return input; }, tag: function(attributes, content, scope) { var htmlAttributes = _.omit(attributes, 'tagName'), tag = attributes.tagName || 'div'; return '<' + tag + ' ' + _.map(htmlAttributes, function(value, key) { if (_.isUndefined(value) || key === 'expand-tokens') { return ''; } var formattedValue = value; if (scope) { formattedValue = Thorax.Util.expandToken(value, scope); } return (key === 'className' ? 'class' : key) + '="' + Handlebars.Utils.escapeExpression(formattedValue) + '"'; }).join(' ') + '>' + (_.isUndefined(content) ? '' : content) + '</' + tag + '>'; } }; ;; Thorax.Mixins = {}; _.extend(Thorax.View, { mixin: function(name) { Thorax.Mixins[name](this); }, registerMixin: function(name, callback, methods) { Thorax.Mixins[name] = function(obj) { var isInstance = !!obj.cid; if (methods) { _.extend(isInstance ? obj : obj.prototype, methods); } if (isInstance) { callback.call(obj); } else { obj.on('configure', callback); } }; } }); Thorax.View.prototype.mixin = function(name) { Thorax.Mixins[name](this); }; ;; /*global createInheritVars, inheritVars, listenTo, objectEvents, walkInheritTree */ // Save a copy of the _on method to call as a $super method var _on = Thorax.View.prototype.on; inheritVars.event = { name: '_events', configure: function() { var self = this; walkInheritTree(this.constructor, '_events', true, function(event) { self.on.apply(self, event); }); walkInheritTree(this, 'events', false, function(handler, eventName) { self.on(eventName, handler, self); }); } }; _.extend(Thorax.View, { on: function(eventName, callback) { createInheritVars(this); if (objectEvents(this, eventName, callback)) { return this; } //accept on({"rendered": handler}) if (_.isObject(eventName)) { _.each(eventName, function(value, key) { this.on(key, value); }, this); } else { //accept on({"rendered": [handler, handler]}) if (_.isArray(callback)) { _.each(callback, function(cb) { this._events.push([eventName, cb]); }, this); //accept on("rendered", handler) } else { this._events.push([eventName, callback]); } } return this; } }); _.extend(Thorax.View.prototype, { on: function(eventName, callback, context) { if (objectEvents(this, eventName, callback, context)) { return this; } if (_.isObject(eventName) && arguments.length < 3) { //accept on({"rendered": callback}) _.each(eventName, function(value, key) { this.on(key, value, callback || this); // callback is context in this form of the call }, this); } else { //accept on("rendered", callback, context) //accept on("click a", callback, context) _.each((_.isArray(callback) ? callback : [callback]), function(callback) { var params = eventParamsFromEventItem.call(this, eventName, callback, context || this); if (params.type === 'DOM' && !this._eventsDelegated) { //will call _addEvent during delegateEvents() if (!this._eventsToDelegate) { this._eventsToDelegate = []; } this._eventsToDelegate.push(params); } else { this._addEvent(params); } }, this); } return this; }, delegateEvents: function(events) { this.undelegateEvents(); if (events) { if (_.isFunction(events)) { events = events.call(this); } this._eventsToDelegate = []; this.on(events); } this._eventsToDelegate && _.each(this._eventsToDelegate, this._addEvent, this); this._eventsDelegated = true; }, //params may contain: //- name //- originalName //- selector //- type "view" || "DOM" //- handler _addEvent: function(params) { // If this is recursvie due to listenTo delegate below then pass through to super class if (params.handler._thoraxBind) { return _on.call(this, params.name, params.handler, params.context || this); } var boundHandler = bindEventHandler.call(this, params.type + '-event:', params); if (params.type === 'view') { // If we have our context set to an outside view then listen rather than directly bind so // we can cleanup properly. if (params.context && params.context !== this && params.context instanceof Thorax.View) { listenTo(params.context, this, params.name, boundHandler, params.context); } else { _on.call(this, params.name, boundHandler, params.context || this); } } else { if (!params.nested) { boundHandler = containHandlerToCurentView(boundHandler, this.cid); } var name = params.name + '.delegateEvents' + this.cid; if (params.selector) { this.$el.on(name, params.selector, boundHandler); } else { this.$el.on(name, boundHandler); } } } }); Thorax.View.prototype.bind = Thorax.View.prototype.on; // When view is ready trigger ready event on all // children that are present, then register an // event that will trigger ready on new children // when they are added Thorax.View.on('ready', function(options) { if (!this._isReady) { this._isReady = true; function triggerReadyOnChild(child) { child._isReady || child.trigger('ready', options); } _.each(this.children, triggerReadyOnChild); this.on('child', triggerReadyOnChild); } }); var eventSplitter = /^(nested\s+)?(\S+)(?:\s+(.+))?/; var domEvents = [], domEventRegexp; function pushDomEvents(events) { domEvents.push.apply(domEvents, events); domEventRegexp = new RegExp('^(nested\\s+)?(' + domEvents.join('|') + ')(?:\\s|$)'); } pushDomEvents([ 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'touchstart', 'touchend', 'touchmove', 'click', 'dblclick', 'keyup', 'keydown', 'keypress', 'submit', 'change', 'input', 'focus', 'blur' ]); function containHandlerToCurentView(handler, cid) { return function(event) { var view = $(event.target).view({helper: false}); if (view && view.cid === cid) { event.originalContext = this; return handler(event); } }; } function bindEventHandler(eventName, params) { eventName += params.originalName; var callback = params.handler, method = _.isFunction(callback) ? callback : this[callback]; if (!method) { throw new Error('Event "' + callback + '" does not exist ' + (this.name || this.cid) + ':' + eventName); } var context = params.context || this; function ret() { try { return method.apply(context, arguments); } catch (e) { Thorax.onException('thorax-exception: ' + (context.name || context.cid) + ':' + eventName, e); } } // Backbone will delegate to _callback in off calls so we should still be able to support // calling off on specific handlers. ret._callback = method; ret._thoraxBind = true; return ret; } function eventParamsFromEventItem(name, handler, context) { var params = { originalName: name, handler: _.isString(handler) ? this[handler] : handler }; if (name.match(domEventRegexp)) { var match = eventSplitter.exec(name); params.nested = !!match[1]; params.name = match[2]; params.type = 'DOM'; params.selector = match[3]; } else { params.name = name; params.type = 'view'; } params.context = context; return params; } ;; /*global getOptionsData, normalizeHTMLAttributeOptions, viewHelperAttributeName */ var viewPlaceholderAttributeName = 'data-view-tmp', viewTemplateOverrides = {}; // Will be shared by HelperView and CollectionHelperView var helperViewPrototype = { _ensureElement: function() { Thorax.View.prototype._ensureElement.apply(this, arguments); this.$el.attr(viewHelperAttributeName, this._helperName); }, _getContext: function() { return this.parent._getContext.apply(this.parent, arguments); } }; Thorax.HelperView = Thorax.View.extend(helperViewPrototype); // Ensure nested inline helpers will always have this.parent // set to the view containing the template function getParent(parent) { // The `view` helper is a special case as it embeds // a view instead of creating a new one while (parent._helperName && parent._helperName !== 'view') { parent = parent.parent; } return parent; } Handlebars.registerViewHelper = function(name, ViewClass, callback) { if (arguments.length === 2) { if (ViewClass.factory) { callback = ViewClass.callback; } else { callback = ViewClass; ViewClass = Thorax.HelperView; } } var viewOptionWhiteList = ViewClass.attributeWhiteList; Handlebars.registerHelper(name, function() { var args = _.toArray(arguments), options = args.pop(), declaringView = getOptionsData(options).view, expandTokens = options.hash['expand-tokens']; if (expandTokens) { delete options.hash['expand-tokens']; _.each(options.hash, function(value, key) { options.hash[key] = Thorax.Util.expandToken(value, this); }, this); } var viewOptions = { inverse: options.inverse, options: options.hash, declaringView: declaringView, parent: getParent(declaringView), _helperName: name, _helperOptions: { options: cloneHelperOptions(options), args: _.clone(args) } }; normalizeHTMLAttributeOptions(options.hash); var htmlAttributes = _.clone(options.hash); if (viewOptionWhiteList) { _.each(viewOptionWhiteList, function(dest, source) { delete htmlAttributes[source]; if (!_.isUndefined(options.hash[source])) { viewOptions[dest] = options.hash[source]; } }); } if(htmlAttributes.tagName) { viewOptions.tagName = htmlAttributes.tagName; } viewOptions.attributes = function() { var attrs = (ViewClass.prototype && ViewClass.prototype.attributes) || {}; if (_.isFunction(attrs)) { attrs = attrs.apply(this, arguments); } _.extend(attrs, _.omit(htmlAttributes, ['tagName'])); // backbone wants "class" if (attrs.className) { attrs['class'] = attrs.className; delete attrs.className; } return attrs; }; if (options.fn) { // Only assign if present, allow helper view class to // declare template viewOptions.template = options.fn; } else if (ViewClass && ViewClass.prototype && !ViewClass.prototype.template) { // ViewClass may also be an instance or object with factory method // so need to do this check viewOptions.template = Handlebars.VM.noop; } // Check to see if we have an existing instance that we can reuse var instance = _.find(declaringView._previousHelpers, function(child) { return compareHelperOptions(viewOptions, child); }); // Create the instance if we don't already have one if (!instance) { if (ViewClass.factory) { instance = ViewClass.factory(args, viewOptions); if (!instance) { return ''; } instance._helperName = viewOptions._helperName; instance._helperOptions = viewOptions._helperOptions; } else { instance = new ViewClass(viewOptions); } if (!instance.el) { // ViewClass.factory may return existing objects which may have been destroyed throw new Error('insert-destroyed-factory'); } // Remove any possible entry in previous helpers in case this is a cached value returned from // slightly different data that does not qualify for the previous helpers direct reuse. // (i.e. when using an array that is modified between renders) declaringView._previousHelpers = _.without(declaringView._previousHelpers, instance); args.push(instance); declaringView._addChild(instance); declaringView.trigger.apply(declaringView, ['helper', name].concat(args)); declaringView.trigger.apply(declaringView, ['helper:' + name].concat(args)); callback && callback.apply(this, args); } else { if (!instance.el) { throw new Error('insert-destroyed'); } declaringView._previousHelpers = _.without(declaringView._previousHelpers, instance); declaringView.children[instance.cid] = instance; } htmlAttributes[viewPlaceholderAttributeName] = instance.cid; if (ViewClass.modifyHTMLAttributes) { ViewClass.modifyHTMLAttributes(htmlAttributes, instance); } return new Handlebars.SafeString(Thorax.Util.tag(htmlAttributes, '', expandTokens ? this : null)); }); var helper = Handlebars.helpers[name]; return helper; }; Thorax.View.on('append', function(scope, callback) { (scope || this.$el).find('[' + viewPlaceholderAttributeName + ']').forEach(function(el) { var placeholderId = el.getAttribute(viewPlaceholderAttributeName), view = this.children[placeholderId]; if (view) { //see if the view helper declared an override for the view //if not, ensure the view has been rendered at least once if (viewTemplateOverrides[placeholderId]) { view.render(viewTemplateOverrides[placeholderId]); delete viewTemplateOverrides[placeholderId]; } else { view.ensureRendered(); } $(el).replaceWith(view.el); callback && callback(view.el); } }, this); }); /** * Clones the helper options, dropping items that are known to change * between rendering cycles as appropriate. */ function cloneHelperOptions(options) { var ret = _.pick(options, 'fn', 'inverse', 'hash', 'data'); ret.data = _.omit(options.data, 'cid', 'view', 'yield'); return ret; } /** * Checks for basic equality between two sets of parameters for a helper view. * * Checked fields include: * - _helperName * - All args * - Hash * - Data * - Function and Invert (id based if possible) * * This method allows us to determine if the inputs to a given view are the same. If they * are then we make the assumption that the rendering will be the same (or the child view will * otherwise rerendering it by monitoring it's parameters as necessary) and reuse the view on * rerender of the parent view. */ function compareHelperOptions(a, b) { function compareValues(a, b) { return _.every(a, function(value, key) { return b[key] === value; }); } if (a._helperName !== b._helperName) { return false; } a = a._helperOptions; b = b._helperOptions; // Implements a first level depth comparison return a.args.length === b.args.length && compareValues(a.args, b.args) && _.isEqual(_.keys(a.options), _.keys(b.options)) && _.every(a.options, function(value, key) { if (key === 'data' || key === 'hash') { return compareValues(a.options[key], b.options[key]); } else if (key === 'fn' || key === 'inverse') { if (b.options[key] === value) { return true; } var other = b.options[key] || {}; return value && _.has(value, 'program') && !value.depth && other.program === value.program; } return b.options[key] === value; }); } ;; /*global getValue, inheritVars, walkInheritTree */ function dataObject(type, spec) { spec = inheritVars[type] = _.defaults({ name: '_' + type + 'Events', event: true }, spec); // Add a callback in the view constructor spec.ctor = function() { if (this[type]) { // Need to null this.model/collection so setModel/Collection will // not treat it as the old model/collection and immediately return var object = this[type]; this[type] = null; this[spec.set](object); } }; function setObject(dataObject, options) { var old = this[type], $el = getValue(this, spec.$el); if (dataObject === old) { return this; } if (old) { this.unbindDataObject(old); } if (dataObject) { this[type] = dataObject; if (spec.loading) { spec.loading.call(this); } this.bindDataObject(type, dataObject, _.extend({}, this.options, options)); $el && $el.attr(spec.cidAttrName, dataObject.cid); dataObject.trigger('set', dataObject, old); } else { this[type] = false; if (spec.change) { spec.change.call(this, false); } $el && $el.removeAttr(spec.cidAttrName); } this.trigger('change:data-object', type, dataObject, old); return this; } Thorax.View.prototype[spec.set] = setObject; } _.extend(Thorax.View.prototype, { getObjectOptions: function(dataObject) { return dataObject && this._objectOptionsByCid[dataObject.cid]; }, bindDataObject: function(type, dataObject, options) { if (this._boundDataObjectsByCid[dataObject.cid]) { return false; } this._boundDataObjectsByCid[dataObject.cid] = dataObject; var options = this._modifyDataObjectOptions(dataObject, _.extend({}, inheritVars[type].defaultOptions, options)); this._objectOptionsByCid[dataObject.cid] = options; bindEvents.call(this, type, dataObject, this.constructor); bindEvents.call(this, type, dataObject, this); var spec = inheritVars[type]; spec.bindCallback && spec.bindCallback.call(this, dataObject, options); if (dataObject.shouldFetch && dataObject.shouldFetch(options)) { loadObject(dataObject, options); } else if (inheritVars[type].change) { // want to trigger built in rendering without triggering event on model inheritVars[type].change.call(this, dataObject, options); } return true; }, unbindDataObject: function (dataObject) { if (!this._boundDataObjectsByCid[dataObject.cid]) { return false; } delete this._boundDataObjectsByCid[dataObject.cid]; this.stopListening(dataObject); delete this._objectOptionsByCid[dataObject.cid]; return true; }, _modifyDataObjectOptions: function(dataObject, options) { return options; } }); function bindEvents(type, target, source) { var context = this; walkInheritTree(source, '_' + type + 'Events', true, function(event) { listenTo(context, target, event[0], event[1], event[2] || context); }); } function loadObject(dataObject, options) { if (dataObject.load) { dataObject.load(function() { options && options.success && options.success(dataObject); }, options); } else { dataObject.fetch(options); } } function getEventCallback(callback, context) { if (_.isFunction(callback)) { return callback; } else { return context[callback]; } } ;; /*global createRegistryWrapper, dataObject, getValue, inheritVars */ var modelCidAttributeName = 'data-model-cid'; Thorax.Model = Backbone.Model.extend({ isEmpty: function() { return !this.isPopulated(); }, isPopulated: function() { // We are populated if we have attributes set var attributes = _.clone(this.attributes), defaults = getValue(this, 'defaults') || {}; for (var default_key in defaults) { if (attributes[default_key] != defaults[default_key]) { return true; } delete attributes[default_key]; } var keys = _.keys(attributes); return keys.length > 1 || (keys.length === 1 && keys[0] !== this.idAttribute); }, shouldFetch: function(options) { // url() will throw if model has no `urlRoot` and no `collection` // or has `collection` and `collection` has no `url` var url; try { url = getValue(this, 'url'); } catch(e) { url = false; } return options.fetch && !!url && !this.isPopulated(); } }); Thorax.Models = {}; createRegistryWrapper(Thorax.Model, Thorax.Models); dataObject('model', { set: 'setModel', defaultOptions: { render: undefined, // Default to deferred rendering fetch: true, success: false, invalid: true }, change: onModelChange, $el: '$el', cidAttrName: modelCidAttributeName }); function onModelChange(model, options) { if (options && options.serializing) { return; } var modelOptions = this.getObjectOptions(model) || {}; // !modelOptions will be true when setModel(false) is called this.conditionalRender(modelOptions.render); } Thorax.View.on({ model: { invalid: function(model, errors) { if (this.getObjectOptions(model).invalid) { this.trigger('invalid', errors, model); } }, error: function(model, resp, options) { this.trigger('error', resp, model); }, change: function(model, options) { // Indirect refernece to allow for overrides inheritVars.model.change.call(this, model, options); } } }); $.fn.model = function(view) { var $this = $(this), modelElement = $this.closest('[' + modelCidAttributeName + ']'), modelCid = modelElement && modelElement.attr(modelCidAttributeName); if (modelCid) { var view = view || $this.view(); if (view && view.model && view.model.cid === modelCid) { return view.model || false; } var collection = $this.collection(view); if (collection) { return collection.get(modelCid); } } return false; }; ;; /*global assignView, assignTemplate, createRegistryWrapper, dataObject, getEventCallback, getValue, modelCidAttributeName, viewCidAttributeName */ var _fetch = Backbone.Collection.prototype.fetch, _set = Backbone.Collection.prototype.set, _replaceHTML = Thorax.View.prototype._replaceHTML, collectionCidAttributeName = 'data-collection-cid', collectionEmptyAttributeName = 'data-collection-empty', collectionElementAttributeName = 'data-collection-element', ELEMENT_NODE_TYPE = 1; Thorax.Collection = Backbone.Collection.extend({ model: Thorax.Model || Backbone.Model, initialize: function() { this.cid = _.uniqueId('collection'); return Backbone.Collection.prototype.initialize.apply(this, arguments); }, isEmpty: function() { if (this.length > 0) { return false; } else { return this.length === 0 && this.isPopulated(); } }, isPopulated: function() { return this._fetched || this.length > 0 || (!this.length && !getValue(this, 'url')); }, shouldFetch: function(options) { return options.fetch && !!getValue(this, 'url') && !this.isPopulated(); }, fetch: function(options) { options = options || {}; var success = options.success; options.success = function(collection, response) { collection._fetched = true; success && success(collection, response); }; return _fetch.apply(this, arguments); }, set: function(models, options) { this._fetched = !!models; return _set.call(this, models, options); } }); _.extend(Thorax.View.prototype, { getCollectionViews: function(collection) { return _.filter(this.children, function(child) { if (!(child instanceof Thorax.CollectionView)) { return false; } return !collection || (child.collection === collection); }); }, updateFilter: function(collection) { _.invoke(this.getCollectionViews(collection), 'updateFilter'); } }); Thorax.Collections = {}; createRegistryWrapper(Thorax.Collection, Thorax.Collections); dataObject('collection', { set: 'setCollection', bindCallback: onSetCollection, defaultOptions: { render: undefined, // Default to deferred rendering fetch: true, success: false, invalid: true, change: true // Wether or not to re-render on model:change }, change: onCollectionReset, $el: 'getCollectionElement', cidAttrName: collectionCidAttributeName }); Thorax.CollectionView = Thorax.View.extend({ _defaultTemplate: Handlebars.VM.noop, _collectionSelector: '[' + collectionElementAttributeName + ']', // preserve collection element if it was not created with {{collection}} helper _replaceHTML: function(html) { if (this.collection && this.getObjectOptions(this.collection) && this._renderCount) { var element; var oldCollectionElement = this.getCollectionElement(); element = _replaceHTML.call(this, html); if (!oldCollectionElement.attr('data-view-cid')) { this.getCollectionElement().replaceWith(oldCollectionElement); } } else { return _replaceHTML.call(this, html); } }, render: function() { var shouldRender = this.shouldRender(); Thorax.View.prototype.render.apply(this, arguments); if (!shouldRender) { this.renderCollection(); } }, //appendItem(model [,index]) //appendItem(html_string, index) //appendItem(view, index) appendItem: function(model, index, options) { //empty item if (!model) { return; } var itemView, $el = this.getCollectionElement(), collection = this.collection; options = _.defaults(options || {}, { filter: true }); //if index argument is a view index && index.el && (index = $el.children().indexOf(index.el) + 1); //if argument is a view, or html string if (model.el || _.isString(model)) { itemView = model; model = false; } else { index = index || collection.indexOf(model) || 0; itemView = this.renderItem(model, index); } if (itemView) { if (itemView.cid) { itemView.ensureRendered(); this._addChild(itemView); } //if the renderer's output wasn't contained in a tag, wrap it in a div //plain text, or a mixture of top level text nodes and element nodes //will get wrapped if (_.isString(itemView) && !itemView.match(/^\s*</m)) { itemView = '<div>' + itemView + '</div>'; } var itemElement = itemView.$el || $($.trim(itemView)).filter(function() { //filter out top level whitespace nodes return this.nodeType === ELEMENT_NODE_TYPE; }); if (model) { itemElement.attr(modelCidAttributeName, model.cid); } var previousModel = index > 0 ? collection.at(index - 1) : false; if (!previousModel) { $el.prepend(itemElement); } else { //use last() as appendItem can accept multiple nodes from a template var last = $el.children('[' + modelCidAttributeName + '="' + previousModel.cid + '"]').last(); last.after(itemElement); } this.trigger('append', null, function(el) { el.setAttribute(modelCidAttributeName, model.cid); }); if (!options.silent) { this.trigger('rendered:item', this, collection, model, itemElement, index); } if (options.filter) { applyItemVisiblityFilter.call(this, model); } } return itemView; }, // updateItem only useful if there is no item view, otherwise // itemView.render() provides the same functionality updateItem: function(model) { var $el = this.getCollectionElement(), viewEl = $el.find('[' + modelCidAttributeName + '="' + model.cid + '"]'); // NOP For views if (viewEl.attr(viewCidAttributeName)) { return; } this.removeItem(viewEl); this.appendItem(model); }, removeItem: function(model) { var viewEl = model; if (model.cid) { var $el = this.getCollectionElement(); viewEl = $el.find('[' + modelCidAttributeName + '="' + model.cid + '"]'); } if (!viewEl.length) { return false; } var viewCids = viewEl.find('[' + viewCidAttributeName + ']').map(function(i, el) { return $(el).attr(viewCidAttributeName); }); viewEl.remove(); viewCids.push(viewEl.attr(viewCidAttributeName)); _.each(viewCids, function(cid) { var child = this.children[cid]; if (child) { this._removeChild(child); } }, this); return true; }, renderCollection: function() { if (this.collection) { if (this.collection.isEmpty()) { handleChangeFromNotEmptyToEmpty.call(this); } else { handleChangeFromEmptyToNotEmpty.call(this); this.collection.forEach(function(item, i) { this.appendItem(item, i); }, this); } this.trigger('rendered:collection', this, this.collection); } else { handleChangeFromNotEmptyToEmpty.call(this); } }, emptyClass: 'empty', renderEmpty: function() { if (!this.emptyView) { assignView.call(this, 'emptyView', { extension: '-empty' }); } if (!this.emptyTemplate && !this.emptyView) { assignTemplate.call(this, 'emptyTemplate', { extension: '-empty', required: false }); } if (this.emptyView) { var viewOptions = {}; if (this.emptyTemplate) { viewOptions.template = this.emptyTemplate; } var view = Thorax.Util.getViewInstance(this.emptyView, viewOptions); view.ensureRendered(); return view; } else { return this.emptyTemplate && this.renderTemplate(this.emptyTemplate); } }, renderItem: function(model, i) { if (!this.itemView) { assignView.call(this, 'itemView', { extension: '-item', required: false }); } if (!this.itemTemplate && !this.itemView) { assignTemplate.call(this, 'itemTemplate', { extension: '-item', // only require an itemTemplate if an itemView // is not present required: !this.itemView }); } if (this.itemView) { var viewOptions = { model: model }; if (this.itemTemplate) { viewOptions.template = this.itemTemplate; } return Thorax.Util.getViewInstance(this.itemView, viewOptions); } else { return this.renderTemplate(this.itemTemplate, this.itemContext(model, i)); } }, itemContext: function(model /*, i */) { return model.attributes; }, appendEmpty: function() { var $el = this.getCollectionElement(); $el.empty(); var emptyContent = this.renderEmpty(); emptyContent && this.appendItem(emptyContent, 0, { silent: true, filter: false }); this.trigger('rendered:empty', this, this.collection); }, getCollectionElement: function() { var element = this.$(this._collectionSelector); return element.length === 0 ? this.$el : element; }, updateFilter: function() { applyVisibilityFilter.call(this); } }); Thorax.CollectionView.on({ collection: { reset: onCollectionReset, sort: onCollectionReset, change: function(model) { var options = this.getObjectOptions(this.collection); if (options && options.change) { this.updateItem(model); } applyItemVisiblityFilter.call(this, model); }, add: function(model) { var $el = this.getCollectionElement(); if ($el.length) { if (this.collection.length === 1) { handleChangeFromEmptyToNotEmpty.call(this); } var index = this.collection.indexOf(model); this.appendItem(model, index); } }, remove: function(model) { var $el = this.getCollectionElement(); this.removeItem(model); this.collection.length === 0 && $el.length && handleChangeFromNotEmptyToEmpty.call(this); } } }); Thorax.View.on({ collection: { invalid: function(collection, message) { if (this.getObjectOptions(collection).invalid) { this.trigger('invalid', message, collection); } }, error: function(collection, resp, options) { this.trigger('error', resp, collection); } } }); function onCollectionReset(collection) { // Undefined to force conditional render var options = this.getObjectOptions(collection) || undefined; if (this.shouldRender(options && options.render)) { this.renderCollection && this.renderCollection(); } } // Even if the view is not a CollectionView // ensureRendered() to provide similar behavior // to a model function onSetCollection(collection) { // Undefined to force conditional render var options = this.getObjectOptions(collection) || undefined; if (this.shouldRender(options && options.render)) { // Ensure that something is there if we are going to render the collection. this.ensureRendered(); } } function applyVisibilityFilter() { if (this.itemFilter) { this.collection.forEach(applyItemVisiblityFilter, this); } } function applyItemVisiblityFilter(model) { var $el = this.getCollectionElement(); this.itemFilter && $el.find('[' + modelCidAttributeName + '="' + model.cid + '"]')[itemShouldBeVisible.call(this, model) ? 'show' : 'hide'](); } function itemShouldBeVisible(model) { return this.itemFilter(model, this.collection.indexOf(model)); } function handleChangeFromEmptyToNotEmpty() { var $el = this.getCollectionElement(); this.emptyClass && $el.removeClass(this.emptyClass); $el.removeAttr(collectionEmptyAttributeName); $el.empty(); } function handleChangeFromNotEmptyToEmpty() { var $el = this.getCollectionElement(); this.emptyClass && $el.addClass(this.emptyClass); $el.attr(collectionEmptyAttributeName, true); this.appendEmpty(); } //$(selector).collection() helper $.fn.collection = function(view) { if (view && view.collection) { return view.collection; } var $this = $(this), collectionElement = $this.closest('[' + collectionCidAttributeName + ']'), collectionCid = collectionElement && collectionElement.attr(collectionCidAttributeName); if (collectionCid) { view = $this.view(); if (view) { return view.collection; } } return false; }; ;; /*global inheritVars */ inheritVars.model.defaultOptions.populate = true; var oldModelChange = inheritVars.model.change; inheritVars.model.change = function(model, options) { this._isChanging = true; oldModelChange.apply(this, arguments); this._isChanging = false; if (options && options.serializing) { return; } var populate = populateOptions(this); if (this._renderCount && populate) { this.populate(!populate.context && this.model.attributes, populate); } }; _.extend(Thorax.View.prototype, { //serializes a form present in the view, returning the serialized data //as an object //pass {set:false} to not update this.model if present //can pass options, callback or event in any order serialize: function() { var callback, options, event; //ignore undefined arguments in case event was null for (var i = 0; i < arguments.length; ++i) { if (_.isFunction(arguments[i])) { callback = arguments[i]; } else if (_.isObject(arguments[i])) { if ('stopPropagation' in arguments[i] && 'preventDefault' in arguments[i]) { event = arguments[i]; } else { options = arguments[i]; } } } if (event && !this._preventDuplicateSubmission(event)) { return; } options = _.extend({ set: true, validate: true, children: true }, options || {}); var attributes = options.attributes || {}; //callback has context of element var view = this; var errors = []; eachNamedInput(this, options, function(element) { var value = view._getInputValue(element, options, errors); if (!_.isUndefined(value)) { objectAndKeyFromAttributesAndName(attributes, element.name, {mode: 'serialize'}, function(object, key) { if (!object[key]) { object[key] = value; } else if (_.isArray(object[key])) { object[key].push(value); } else { object[key] = [object[key], value]; } }); } }); if (!options._silent) { this.trigger('serialize', attributes, options); } if (options.validate) { var validateInputErrors = this.validateInput(attributes); if (validateInputErrors && validateInputErrors.length) { errors = errors.concat(validateInputErrors); } this.trigger('validate', attributes, errors, options); if (errors.length) { this.trigger('invalid', errors); return; } } if (options.set && this.model) { if (!this.model.set(attributes, {silent: options.silent, serializing: true})) { return false; } } callback && callback.call(this, attributes, _.bind(resetSubmitState, this)); return attributes; }, _preventDuplicateSubmission: function(event, callback) { event.preventDefault(); var form = $(event.target); if ((event.target.tagName || '').toLowerCase() !== 'form') { // Handle non-submit events by gating on the form form = $(event.target).closest('form'); } if (!form.attr('data-submit-wait')) { form.attr('data-submit-wait', 'true'); if (callback) { callback.call(this, event); } return true; } else { return false; } }, //populate a form from the passed attributes or this.model if present populate: function(attributes, options) { options = _.extend({ children: true }, options || {}); var value, attributes = attributes || this._getContext(); //callback has context of element eachNamedInput(this, options, function(element) { objectAndKeyFromAttributesAndName(attributes, element.name, {mode: 'populate'}, function(object, key) { value = object && object[key]; if (!_.isUndefined(value)) { //will only execute if we have a name that matches the structure in attributes var isBinary = element.type === 'checkbox' || element.type === 'radio'; if (isBinary && _.isBoolean(value)) { element.checked = value; } else if (isBinary) { element.checked = value == element.value; } else { element.value = value; } } }); }); ++this._populateCount; if (!options._silent) { this.trigger('populate', attributes); } }, //perform form validation, implemented by child class validateInput: function(/* attributes, options, errors */) {}, _getInputValue: function(input /* , options, errors */) { if (input.type === 'checkbox' || input.type === 'radio') { if (input.checked) { return input.getAttribute('value') || true; } } else if (input.multiple === true) { var values = []; $('option', input).each(function() { if (this.selected) { values.push(this.value); } }); return values; } else { return input.value; } }, _populateCount: 0 }); // Keeping state in the views Thorax.View.on({ 'before:rendered': function() { // Do not store previous options if we have not rendered or if we have changed the associated // model since the last render if (!this._renderCount || (this.model && this.model.cid) !== this._formModelCid) { return; } var modelOptions = this.getObjectOptions(this.model); // When we have previously populated and rendered the view, reuse the user data this.previousFormData = filterObject( this.serialize(_.extend({ set: false, validate: false, _silent: true }, modelOptions)), function(value) { return value !== '' && value != null; } ); }, rendered: function() { var populate = populateOptions(this); if (populate && !this._isChanging && !this._populateCount) { this.populate(!populate.context && this.model.attributes, populate); } if (this.previousFormData) { this.populate(this.previousFormData, _.extend({_silent: true}, populate)); } this._formModelCid = this.model && this.model.cid; this.previousFormData = null; } }); function filterObject(object, callback) { _.each(object, function (value, key) { if (_.isObject(value)) { return filterObject(value, callback); } if (callback(value, key, object) === false) { delete object[key]; } }); return object; } Thorax.View.on({ invalid: onErrorOrInvalidData, error: onErrorOrInvalidData, deactivated: function() { if (this.$el) { resetSubmitState.call(this); } } }); function onErrorOrInvalidData () { resetSubmitState.call(this); // If we errored with a model we want to reset the content but leave the UI // intact. If the user updates the data and serializes any overwritten data // will be restored. if (this.model && this.model.previousAttributes) { this.model.set(this.model.previousAttributes(), { silent: true }); } } function eachNamedInput(view, options, iterator) { var i = 0; $('select,input,textarea', options.root || view.el).each(function() { if (!options.children) { if (view !== $(this).view({helper: false})) { return; } } if (this.type !== 'button' && this.type !== 'cancel' && this.type !== 'submit' && this.name) { iterator(this, i); ++i; } }); } //calls a callback with the correct object fragment and key from a compound name function objectAndKeyFromAttributesAndName(attributes, name, options, callback) { var key, object = attributes, keys = name.split('['), mode = options.mode; for (var i = 0; i < keys.length - 1; ++i) { key = keys[i].replace(']', ''); if (!object[key]) { if (mode === 'serialize') { object[key] = {}; } else { return callback(undefined, key); } } object = object[key]; } key = keys[keys.length - 1].replace(']', ''); callback(object, key); } function resetSubmitState() { this.$('form').removeAttr('data-submit-wait'); } function populateOptions(view) { var modelOptions = view.getObjectOptions(view.model) || {}; return modelOptions.populate === true ? {} : modelOptions.populate; } ;; /*global getOptionsData, normalizeHTMLAttributeOptions, createErrorMessage */ var layoutCidAttributeName = 'data-layout-cid'; Thorax.LayoutView = Thorax.View.extend({ _defaultTemplate: Handlebars.VM.noop, render: function() { var response = Thorax.View.prototype.render.apply(this, arguments); if (this.template === Handlebars.VM.noop) { // if there is no template setView will append to this.$el ensureLayoutCid.call(this); } else { // if a template was specified is must declare a layout-element ensureLayoutViewsTargetElement.call(this); } return response; }, setView: function(view, options) { options = _.extend({ scroll: true }, options || {}); if (_.isString(view)) { view = new (Thorax.Util.registryGet(Thorax, 'Views', view, false))(); } this.ensureRendered(); var oldView = this._view, append, remove, complete; if (view === oldView) { return false; } this.trigger('change:view:start', view, oldView, options); remove = _.bind(function() { if (oldView) { oldView.$el && oldView.$el.remove(); triggerLifecycleEvent.call(oldView, 'deactivated', options); this._removeChild(oldView); } }, this); append = _.bind(function() { if (view) { view.ensureRendered(); triggerLifecycleEvent.call(this, 'activated', options); view.trigger('activated', options); this._view = view; var targetElement = getLayoutViewsTargetElement.call(this); this._view.appendTo(targetElement); this._addChild(view); } else { this._view = undefined; } }, this); complete = _.bind(function() { this.trigger('change:view:end', view, oldView, options); }, this); if (!options.transition) { remove(); append(); complete(); } else { options.transition(view, oldView, append, remove, complete); } return view; }, getView: function() { return this._view; } }); Handlebars.registerHelper('layout-element', function(options) { var view = getOptionsData(options).view; // duck type check for LayoutView if (!view.getView) { throw new Error(createErrorMessage('layout-element-helper')); } options.hash[layoutCidAttributeName] = view.cid; normalizeHTMLAttributeOptions(options.hash); return new Handlebars.SafeString(Thorax.Util.tag.call(this, options.hash, '', this)); }); function triggerLifecycleEvent(eventName, options) { options = options || {}; options.target = this; this.trigger(eventName, options); _.each(this.children, function(child) { child.trigger(eventName, options); }); } function ensureLayoutCid() { ++this._renderCount; //set the layoutCidAttributeName on this.$el if there was no template this.$el.attr(layoutCidAttributeName, this.cid); } function ensureLayoutViewsTargetElement() { if (!this.$('[' + layoutCidAttributeName + '="' + this.cid + '"]')[0]) { throw new Error('No layout element found in ' + (this.name || this.cid)); } } function getLayoutViewsTargetElement() { return this.$('[' + layoutCidAttributeName + '="' + this.cid + '"]')[0] || this.el[0] || this.el; } ;; /* global createErrorMessage */ Thorax.CollectionHelperView = Thorax.CollectionView.extend({ // Forward render events to the parent events: { 'rendered:item': forwardRenderEvent('rendered:item'), 'rendered:collection': forwardRenderEvent('rendered:collection'), 'rendered:empty': forwardRenderEvent('rendered:empty') }, // Thorax.CollectionView allows a collectionSelector // to be specified, disallow in a collection helper // as it will cause problems when neseted getCollectionElement: function() { return this.$el; }, constructor: function(options) { // need to fetch templates if template name was passed if (options.options['item-template']) { options.itemTemplate = Thorax.Util.getTemplate(options.options['item-template']); } if (options.options['empty-template']) { options.emptyTemplate = Thorax.Util.getTemplate(options.options['empty-template']); } // Handlebars.VM.noop is passed in the handlebars options object as // a default for fn and inverse, if a block was present. Need to // check to ensure we don't pick the empty / null block up. if (!options.itemTemplate && options.template && options.template !== Handlebars.VM.noop) { options.itemTemplate = options.template; options.template = Handlebars.VM.noop; } if (!options.emptyTemplate && options.inverse && options.inverse !== Handlebars.VM.noop) { options.emptyTemplate = options.inverse; options.inverse = Handlebars.VM.noop; } var shouldBindItemContext = _.isFunction(options.itemContext), shouldBindItemFilter = _.isFunction(options.itemFilter); var response = Thorax.HelperView.call(this, options); if (shouldBindItemContext) { this.itemContext = _.bind(this.itemContext, this.parent); } else if (_.isString(this.itemContext)) { this.itemContext = _.bind(this.parent[this.itemContext], this.parent); } if (shouldBindItemFilter) { this.itemFilter = _.bind(this.itemFilter, this.parent); } else if (_.isString(this.itemFilter)) { this.itemFilter = _.bind(this.parent[this.itemFilter], this.parent); } if (this.parent.name) { if (!this.emptyView && !this.parent.renderEmpty) { this.emptyView = Thorax.Util.getViewClass(this.parent.name + '-empty', true); } if (!this.emptyTemplate && !this.parent.renderEmpty) { this.emptyTemplate = Thorax.Util.getTemplate(this.parent.name + '-empty', true); } if (!this.itemView && !this.parent.renderItem) { this.itemView = Thorax.Util.getViewClass(this.parent.name + '-item', true); } if (!this.itemTemplate && !this.parent.renderItem) { // item template must be present if an itemView is not this.itemTemplate = Thorax.Util.getTemplate(this.parent.name + '-item', !!this.itemView); } } return response; }, setAsPrimaryCollectionHelper: function() { _.each(forwardableProperties, function(propertyName) { forwardMissingProperty.call(this, propertyName); }, this); var self = this; _.each(['itemFilter', 'itemContext', 'renderItem', 'renderEmpty'], function(propertyName) { if (self.parent[propertyName]) { self[propertyName] = function() { return self.parent[propertyName].apply(self.parent, arguments); }; } }); } }); _.extend(Thorax.CollectionHelperView.prototype, helperViewPrototype); Thorax.CollectionHelperView.attributeWhiteList = { 'item-context': 'itemContext', 'item-filter': 'itemFilter', 'item-template': 'itemTemplate', 'empty-template': 'emptyTemplate', 'item-view': 'itemView', 'empty-view': 'emptyView', 'empty-class': 'emptyClass' }; function forwardRenderEvent(eventName) { return function() { var args = _.toArray(arguments); args.unshift(eventName); this.parent.trigger.apply(this.parent, args); }; } var forwardableProperties = [ 'itemTemplate', 'itemView', 'emptyTemplate', 'emptyView' ]; function forwardMissingProperty(propertyName) { var parent = getParent(this); if (!this[propertyName]) { var prop = parent[propertyName]; if (prop){ this[propertyName] = prop; } } } Handlebars.registerViewHelper('collection', Thorax.CollectionHelperView, function(collection, view) { if (arguments.length === 1) { view = collection; collection = view.parent.collection; collection && view.setAsPrimaryCollectionHelper(); view.$el.attr(collectionElementAttributeName, 'true'); // propagate future changes to the parent's collection object // to the helper view view.listenTo(view.parent, 'change:data-object', function(type, dataObject) { if (type === 'collection') { view.setAsPrimaryCollectionHelper(); view.setCollection(dataObject); } }); } collection && view.setCollection(collection); }); Handlebars.registerHelper('collection-element', function(options) { if (!getOptionsData(options).view.renderCollection) { throw new Error(createErrorMessage('collection-element-helper')); } var hash = options.hash; normalizeHTMLAttributeOptions(hash); hash.tagName = hash.tagName || 'div'; hash[collectionElementAttributeName] = true; return new Handlebars.SafeString(Thorax.Util.tag.call(this, hash, '', this)); }); ;; Handlebars.registerHelper('empty', function(dataObject, options) { if (arguments.length === 1) { options = dataObject; } var view = getOptionsData(options).view; if (arguments.length === 1) { dataObject = view.model; } // listeners for the empty helper rather than listeners // that are themselves empty if (!view._emptyListeners) { view._emptyListeners = {}; } // duck type check for collection if (dataObject && !view._emptyListeners[dataObject.cid] && dataObject.models && ('length' in dataObject)) { view._emptyListeners[dataObject.cid] = true; view.listenTo(dataObject, 'remove', function() { if (dataObject.length === 0) { view.render(); } }); view.listenTo(dataObject, 'add', function() { if (dataObject.length === 1) { view.render(); } }); view.listenTo(dataObject, 'reset', function() { view.render(); }); } return !dataObject || dataObject.isEmpty() ? options.fn(this) : options.inverse(this); }); ;; Handlebars.registerHelper('template', function(name, options) { var context = _.extend({fn: options && options.fn}, this, options ? options.hash : {}); var output = getOptionsData(options).view.renderTemplate(name, context); return new Handlebars.SafeString(output); }); Handlebars.registerHelper('yield', function(options) { return getOptionsData(options).yield && options.data.yield(); }); ;; Handlebars.registerHelper('url', function(url) { url = url || ''; var fragment; if (arguments.length > 2) { fragment = _.map(_.head(arguments, arguments.length - 1), encodeURIComponent).join('/'); } else { var options = arguments[1], hash = (options && options.hash) || options; if (hash && hash['expand-tokens']) { fragment = Thorax.Util.expandToken(url, this); } else { fragment = url; } } if (Backbone.history._hasPushState) { var root = Backbone.history.options.root; if (root === '/' && fragment.substr(0, 1) === '/') { return fragment; } else { return root + fragment; } } else { return '#' + fragment; } }); ;; /*global viewTemplateOverrides, createErrorMessage */ Handlebars.registerViewHelper('view', { factory: function(args, options) { var View = args.length >= 1 ? args[0] : Thorax.View; return Thorax.Util.getViewInstance(View, options.options); }, // ensure generated placeholder tag in template // will match tag of view instance modifyHTMLAttributes: function(htmlAttributes, instance) { htmlAttributes.tagName = instance.el.tagName.toLowerCase(); }, callback: function(view) { var instance = arguments[arguments.length-1], options = instance._helperOptions.options, placeholderId = instance.cid; // view will be the argument passed to the helper, if it was // a string, a new instance was created on the fly, ok to pass // hash arguments, otherwise need to throw as templates should // not introduce side effects to existing view instances if (!_.isString(view) && options.hash && _.keys(options.hash).length > 0) { throw new Error(createErrorMessage('view-helper-hash-args')); } if (options.fn) { viewTemplateOverrides[placeholderId] = options.fn; } } }); ;; /* global createErrorMessage */ var callMethodAttributeName = 'data-call-method', triggerEventAttributeName = 'data-trigger-event'; Handlebars.registerHelper('button', function(method, options) { if (arguments.length === 1) { options = method; method = options.hash.method; } var hash = options.hash, expandTokens = hash['expand-tokens']; delete hash['expand-tokens']; if (!method && !options.hash.trigger) { throw new Error(createErrorMessage('button-trigger')); } normalizeHTMLAttributeOptions(hash); hash.tagName = hash.tagName || 'button'; hash.trigger && (hash[triggerEventAttributeName] = hash.trigger); delete hash.trigger; method && (hash[callMethodAttributeName] = method); return new Handlebars.SafeString(Thorax.Util.tag(hash, options.fn ? options.fn(this) : '', expandTokens ? this : null)); }); Handlebars.registerHelper('link', function() { var args = _.toArray(arguments), options = args.pop(), hash = options.hash, // url is an array that will be passed to the url helper url = args.length === 0 ? [hash.href] : args, expandTokens = hash['expand-tokens']; delete hash['expand-tokens']; if (!url[0] && url[0] !== '') { throw new Error(createErrorMessage('link-href')); } normalizeHTMLAttributeOptions(hash); url.push(options); hash.href = Handlebars.helpers.url.apply(this, url); hash.tagName = hash.tagName || 'a'; hash.trigger && (hash[triggerEventAttributeName] = options.hash.trigger); delete hash.trigger; hash[callMethodAttributeName] = '_anchorClick'; return new Handlebars.SafeString(Thorax.Util.tag(hash, options.fn ? options.fn(this) : '', expandTokens ? this : null)); }); var clickSelector = '[' + callMethodAttributeName + '], [' + triggerEventAttributeName + ']'; function handleClick(event) { var $this = $(this), view = $this.view({helper: false}), methodName = $this.attr(callMethodAttributeName), eventName = $this.attr(triggerEventAttributeName), methodResponse = false; methodName && (methodResponse = view[methodName].call(view, event)); eventName && view.trigger(eventName, event); this.tagName === 'A' && methodResponse === false && event.preventDefault(); } var lastClickHandlerEventName; function registerClickHandler() { unregisterClickHandler(); lastClickHandlerEventName = Thorax._fastClickEventName || 'click'; $(document).on(lastClickHandlerEventName, clickSelector, handleClick); } function unregisterClickHandler() { lastClickHandlerEventName && $(document).off(lastClickHandlerEventName, clickSelector, handleClick); } $(document).ready(function() { if (!Thorax._fastClickEventName) { registerClickHandler(); } }); ;; var elementPlaceholderAttributeName = 'data-element-tmp'; Handlebars.registerHelper('element', function(element, options) { normalizeHTMLAttributeOptions(options.hash); var cid = _.uniqueId('element'), declaringView = getOptionsData(options).view; options.hash[elementPlaceholderAttributeName] = cid; declaringView._elementsByCid || (declaringView._elementsByCid = {}); declaringView._elementsByCid[cid] = element; return new Handlebars.SafeString(Thorax.Util.tag(options.hash)); }); Thorax.View.on('append', function(scope, callback) { (scope || this.$el).find('[' + elementPlaceholderAttributeName + ']').forEach(function(el) { var $el = $(el), cid = $el.attr(elementPlaceholderAttributeName), element = this._elementsByCid[cid]; // A callback function may be specified as the value if (_.isFunction(element)) { element = element.call(this); } $el.replaceWith(element); callback && callback(element); }, this); }); ;; /* global createErrorMessage */ Handlebars.registerHelper('super', function(options) { var declaringView = getOptionsData(options).view, parent = declaringView.constructor && declaringView.constructor.__super__; if (parent) { var template = parent.template; if (!template) { if (!parent.name) { throw new Error(createErrorMessage('super-parent')); } template = parent.name; } if (_.isString(template)) { template = Thorax.Util.getTemplate(template, false); } return new Handlebars.SafeString(template(this, options)); } else { return ''; } }); ;; /*global collectionOptionNames, inheritVars, createErrorMessage */ var loadStart = 'load:start', loadEnd = 'load:end', rootObject; Thorax.setRootObject = function(obj) { rootObject = obj; }; Thorax.loadHandler = function(start, end, context) { var loadCounter = _.uniqueId('load'); return function(message, background, object) { var self = context || this; self._loadInfo = self._loadInfo || {}; var loadInfo = self._loadInfo[loadCounter]; function startLoadTimeout() { // If the timeout has been set already but has not triggered yet do nothing // Otherwise set a new timeout (either initial or for going from background to // non-background loading) if (loadInfo.timeout && !loadInfo.run) { return; } var loadingTimeout = self._loadingTimeoutDuration !== undefined ? self._loadingTimeoutDuration : Thorax.View.prototype._loadingTimeoutDuration; loadInfo.timeout = setTimeout(function() { try { // We have a slight race condtion in here where the end event may have occurred // but the end timeout has not executed. Rather than killing a cumulative timeout // immediately we'll protect from that case here if (loadInfo.events.length) { loadInfo.run = true; start.call(self, loadInfo.message, loadInfo.background, loadInfo); } } catch (e) { Thorax.onException('loadStart', e); } }, loadingTimeout * 1000); } if (!loadInfo) { loadInfo = self._loadInfo[loadCounter] = _.extend({ isLoading: function() { return loadInfo.events.length; }, cid: loadCounter, events: [], timeout: 0, message: message, background: !!background }, Backbone.Events); startLoadTimeout(); } else { clearTimeout(loadInfo.endTimeout); loadInfo.message = message; if (!background && loadInfo.background) { loadInfo.background = false; startLoadTimeout(); } } // Prevent binds to the same object multiple times as this can cause very bad things // to happen for the load;load;end;end execution flow. if (_.indexOf(loadInfo.events, object) >= 0) { return; } loadInfo.events.push(object); object.on(loadEnd, function endCallback() { var loadingEndTimeout = self._loadingTimeoutEndDuration; if (loadingEndTimeout === void 0) { // If we are running on a non-view object pull the default timeout loadingEndTimeout = Thorax.View.prototype._loadingTimeoutEndDuration; } var events = loadInfo.events, index = _.indexOf(events, object); if (index >= 0 && !object.isLoading()) { events.splice(index, 1); if (_.indexOf(events, object) < 0) { // Last callback for this particlar object, remove the bind object.off(loadEnd, endCallback); } } if (!events.length) { clearTimeout(loadInfo.endTimeout); loadInfo.endTimeout = setTimeout(function() { try { if (!events.length) { if (loadInfo.run) { // Emit the end behavior, but only if there is a paired start end && end.call(self, loadInfo.background, loadInfo); loadInfo.trigger(loadEnd, loadInfo); } // If stopping make sure we don't run a start clearTimeout(loadInfo.timeout); loadInfo = self._loadInfo[loadCounter] = undefined; } } catch (e) { Thorax.onException('loadEnd', e); } }, loadingEndTimeout * 1000); } }); }; }; /** * Helper method for propagating load:start events to other objects. * * Forwards load:start events that occur on `source` to `dest`. */ Thorax.forwardLoadEvents = function(source, dest, once) { function load(message, backgound, object) { if (once) { source.off(loadStart, load); } dest.trigger(loadStart, message, backgound, object); } source.on(loadStart, load); return { off: function() { source.off(loadStart, load); } }; }; // // Data load event generation // /** * Mixing for generating load:start and load:end events. */ Thorax.mixinLoadable = function(target, useParent) { _.extend(target, { //loading config _loadingClassName: 'loading', _loadingTimeoutDuration: 0.33, _loadingTimeoutEndDuration: 0.10, // Propagates loading view parameters to the AJAX layer onLoadStart: function(message, background, object) { var that = useParent ? this.parent : this; // Protect against race conditions if (!that || !that.el) { return; } if (!that.nonBlockingLoad && !background && rootObject && rootObject !== this) { rootObject.trigger(loadStart, message, background, object); } that._isLoading = true; $(that.el).addClass(that._loadingClassName); // used by loading helpers that.trigger('change:load-state', 'start', background); }, onLoadEnd: function(/* background, object */) { var that = useParent ? this.parent : this; // Protect against race conditions if (!that || !that.el) { return; } that._isLoading = false; $(that.el).removeClass(that._loadingClassName); // used by loading helper that.trigger('change:load-state', 'end'); } }); }; Thorax.mixinLoadableEvents = function(target, useParent) { _.extend(target, { _loadCount: 0, isLoading: function() { return this._loadCount > 0; }, loadStart: function(message, background) { this._loadCount++; var that = useParent ? this.parent : this; that.trigger(loadStart, message, background, that); }, loadEnd: function() { this._loadCount--; var that = useParent ? this.parent : this; that.trigger(loadEnd, that); } }); }; Thorax.mixinLoadable(Thorax.View.prototype); Thorax.mixinLoadableEvents(Thorax.View.prototype); if (Thorax.HelperView) { Thorax.mixinLoadable(Thorax.HelperView.prototype, true); Thorax.mixinLoadableEvents(Thorax.HelperView.prototype, true); } if (Thorax.CollectionHelperView) { Thorax.mixinLoadable(Thorax.CollectionHelperView.prototype, true); Thorax.mixinLoadableEvents(Thorax.CollectionHelperView.prototype, true); } Thorax.sync = function(method, dataObj, options) { var self = this, complete = options.complete; options.complete = function() { self._request = undefined; self._aborted = false; complete && complete.apply(this, arguments); }; this._request = Backbone.sync.apply(this, arguments); return this._request; }; function bindToRoute(callback, failback) { var fragment = Backbone.history.getFragment(), routeChanged = false; function routeHandler() { if (fragment === Backbone.history.getFragment()) { return; } routeChanged = true; res.cancel(); failback && failback(); } Backbone.history.on('route', routeHandler); function finalizer() { Backbone.history.off('route', routeHandler); if (!routeChanged) { callback.apply(this, arguments); } } var res = _.bind(finalizer, this); res.cancel = function() { Backbone.history.off('route', routeHandler); }; return res; } function loadData(callback, failback, options) { if (this.isPopulated()) { // Defer here to maintain async callback behavior for all loading cases return _.defer(callback, this); } if (arguments.length === 2 && !_.isFunction(failback) && _.isObject(failback)) { options = failback; failback = false; } var self = this, routeChanged = false, successCallback = bindToRoute(_.bind(callback, self), function() { routeChanged = true; if (self._request) { self._aborted = true; self._request.abort(); } failback && failback.call(self, false); }); this.fetch(_.defaults({ success: successCallback, error: function() { successCallback.cancel(); if (!routeChanged && failback) { failback.apply(self, [true].concat(_.toArray(arguments))); } } }, options)); } function fetchQueue(options, $super) { if (options.resetQueue) { // WARN: Should ensure that loaders are protected from out of band data // when using this option this.fetchQueue = undefined; } else if (this.fetchQueue) { // concurrent set/reset fetch events are not advised var reset = (this.fetchQueue[0] || {}).reset; if (reset !== options.reset) { // fetch with concurrent set & reset not allowed throw new Error(createErrorMessage('mixed-fetch')); } } if (!this.fetchQueue) { // Kick off the request this.fetchQueue = [options]; options = _.defaults({ success: flushQueue(this, this.fetchQueue, 'success'), error: flushQueue(this, this.fetchQueue, 'error'), complete: flushQueue(this, this.fetchQueue, 'complete') }, options); // Handle callers that do not pass in a super class and wish to implement their own // fetch behavior if ($super) { $super.call(this, options); } return options; } else { // Currently fetching. Queue and process once complete this.fetchQueue.push(options); } } function flushQueue(self, fetchQueue, handler) { return function() { var args = arguments; // Flush the queue. Executes any callback handlers that // may have been passed in the fetch options. _.each(fetchQueue, function(options) { if (options[handler]) { options[handler].apply(this, args); } }, this); // Reset the queue if we are still the active request if (self.fetchQueue === fetchQueue) { self.fetchQueue = undefined; } }; } var klasses = []; Thorax.Model && klasses.push(Thorax.Model); Thorax.Collection && klasses.push(Thorax.Collection); _.each(klasses, function(DataClass) { var $fetch = DataClass.prototype.fetch; Thorax.mixinLoadableEvents(DataClass.prototype, false); _.extend(DataClass.prototype, { sync: Thorax.sync, fetch: function(options) { options = options || {}; if (DataClass === Thorax.Collection) { if (!_.find(['reset', 'remove', 'add', 'update'], function(key) { return !_.isUndefined(options[key]); })) { // use backbone < 1.0 behavior to allow triggering of reset events options.reset = true; } } if (!options.loadTriggered) { var self = this; function endWrapper(method) { var $super = options[method]; options[method] = function() { self.loadEnd(); $super && $super.apply(this, arguments); }; } endWrapper('success'); endWrapper('error'); self.loadStart(undefined, options.background); } return fetchQueue.call(this, options || {}, $fetch); }, load: function(callback, failback, options) { if (arguments.length === 2 && !_.isFunction(failback)) { options = failback; failback = false; } options = options || {}; if (!options.background && !this.isPopulated() && rootObject) { // Make sure that the global scope sees the proper load events here // if we are loading in standalone mode if (this.isLoading()) { // trigger directly because load:start has already been triggered rootObject.trigger(loadStart, options.message, options.background, this); } else { Thorax.forwardLoadEvents(this, rootObject, true); } } loadData.call(this, callback, failback, options); } }); }); Thorax.Util.bindToRoute = bindToRoute; // Propagates loading view parameters to the AJAX layer Thorax.View.prototype._modifyDataObjectOptions = function(dataObject, options) { options.ignoreErrors = this.ignoreFetchError; options.background = this.nonBlockingLoad; return options; }; // Thorax.CollectionHelperView inherits from CollectionView // not HelperView so need to set it manually Thorax.HelperView.prototype._modifyDataObjectOptions = Thorax.CollectionHelperView.prototype._modifyDataObjectOptions = function(dataObject, options) { options.ignoreErrors = this.parent.ignoreFetchError; options.background = this.parent.nonBlockingLoad; return options; }; inheritVars.collection.loading = function() { var loadingView = this.loadingView, loadingTemplate = this.loadingTemplate, loadingPlacement = this.loadingPlacement; //add "loading-view" and "loading-template" options to collection helper if (loadingView || loadingTemplate) { var callback = Thorax.loadHandler(_.bind(function() { var item; if (this.collection.length === 0) { this.$el.empty(); } if (loadingView) { var instance = Thorax.Util.getViewInstance(loadingView); this._addChild(instance); if (loadingTemplate) { instance.render(loadingTemplate); } else { instance.render(); } item = instance; } else { item = this.renderTemplate(loadingTemplate); } var index = loadingPlacement ? loadingPlacement.call(this) : this.collection.length ; this.appendItem(item, index); this.$el.children().eq(index).attr('data-loading-element', this.collection.cid); }, this), _.bind(function() { this.$el.find('[data-loading-element="' + this.collection.cid + '"]').remove(); }, this), this.collection); this.listenTo(this.collection, 'load:start', callback); } }; if (Thorax.CollectionHelperView) { _.extend(Thorax.CollectionHelperView.attributeWhiteList, { 'loading-template': 'loadingTemplate', 'loading-view': 'loadingView', 'loading-placement': 'loadingPlacement' }); } Thorax.View.on({ 'load:start': Thorax.loadHandler( function(message, background, object) { this.onLoadStart(message, background, object); }, function(background, object) { this.onLoadEnd(object); }), collection: { 'load:start': function(message, background, object) { this.trigger(loadStart, message, background, object); } }, model: { 'load:start': function(message, background, object) { this.trigger(loadStart, message, background, object); } } }); ;; Handlebars.registerHelper('loading', function(options) { var view = getOptionsData(options).view; view.off('change:load-state', onLoadStateChange, view); view.on('change:load-state', onLoadStateChange, view); return view._isLoading ? options.fn(this) : options.inverse(this); }); function onLoadStateChange() { this.render(); } ;; /*global _replaceHTML */ var isIE = (/msie [\w.]+/).exec(navigator.userAgent.toLowerCase()); if (isIE) { // IE will lose a reference to the elements if view.el.innerHTML = ''; // If they are removed one by one the references are not lost. // For instance a view's childrens' `el`s will be lost if the view // sets it's `el.innerHTML`. Thorax.View.on('before:append', function() { // note that detach is not available in Zepto, // but IE should never run with Zepto if (this._renderCount > 0) { _.each(this._elementsByCid, function(element) { $(element).detach(); }); _.each(this.children, function(child) { child.$el.detach(); }); } }); // Once nodes are detached their innerHTML gets nuked in IE // so create a deep clone. This method is identical to the // main implementation except for ".clone(true, true)" which // will perform a deep clone with events and data Thorax.CollectionView.prototype._replaceHTML = function(html) { if (this.getObjectOptions(this.collection) && this._renderCount) { var element; var oldCollectionElement = this.getCollectionElement().clone(true, true); element = _replaceHTML.call(this, html); if (!oldCollectionElement.attr('data-view-cid')) { this.getCollectionElement().replaceWith(oldCollectionElement); } } else { return _replaceHTML.call(this, html); } }; } ;; })(); //@ sourceMappingURL=thorax.js.map
assets/js/jquery.min.js
mrrobotteam/employeemanagement
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={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>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-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",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-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",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.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(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,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"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
ajax/libs/inferno/1.0.0-beta17/inferno-mobx.min.js
emmy41124/cdnjs
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("./inferno-component"),require("./inferno"),require("./inferno-create-class"),require("./inferno-create-element")):"function"==typeof define&&define.amd?define(["inferno-component","inferno","inferno-create-class","inferno-create-element"],t):(e.Inferno=e.Inferno||{},e.Inferno.Mobx=t(e.Inferno.Component,e.Inferno,e.Inferno.createClass,e.Inferno.createElement))}(this,function(e,t,n,r){"use strict";function o(e){throw e||(e=p),new Error("Inferno Error: "+e)}function i(e,t){return t={exports:{}},e(t,t.exports),t.exports}function a(e){var t=w(e);t&&S&&S.set(t,e),O.emit({event:"render",renderTime:e.__$mobRenderEnd-e.__$mobRenderStart,totalTime:Date.now()-e.__$mobRenderStart,component:e,node:t})}function s(){"undefined"==typeof WeakMap&&o("[inferno-mobx] tracking components is not supported in this browser."),_||(_=!0)}function u(t){var n=t.prototype||t,r=n.componentDidMount,o=n.componentWillMount,i=n.componentWillUnmount;return n.componentWillMount=function(){var t=this;o&&o.call(this);var n,r=!1,i=this.displayName||this.name||this.constructor&&(this.constructor.displayName||this.constructor.name)||"<component>",a=this.render.bind(this),s=function(o,a){return n=new y(i+".render()",function(){if(!r&&(r=!0,t.__$mobxIsUnmounted!==!0)){var o=!0;try{e.prototype.forceUpdate.call(t),o=!1}finally{o&&n.dispose()}}}),u.$mobx=n,t.render=u,u(o,a)},u=function(e,o){r=!1;var i=void 0;return n.track(function(){_&&(t.__$mobRenderStart=Date.now()),i=g.allowStateChanges(!1,a.bind(t,e,o)),_&&(t.__$mobRenderEnd=Date.now())}),i};this.render=s},n.componentDidMount=function(){_&&a(this),r&&r.call(this)},n.componentWillUnmount=function(){if(i&&i.call(this),this.render.$mobx&&this.render.$mobx.dispose(),this.__$mobxIsUnmounted=!0,_){var e=w(this);e&&S&&S.delete(e),O.emit({event:"destroy",component:this,node:e})}},n.shouldComponentUpdate=function(e,t){var n=this;if(this.state!==t)return!0;var r=Object.keys(this.props);if(r.length!==Object.keys(e).length)return!0;for(var o=r.length-1;o>=0;o--){var i=r[o],a=e[i];if(a!==n.props[i])return!0;if(a&&"object"==typeof a&&!m(a))return!0}return!0},t}function c(e,t){var o=n({displayName:t.name,render:function(){var n=this,o={};for(var i in this.props)n.props.hasOwnProperty(i)&&(o[i]=n.props[i]);var a=e(this.context.mobxStores||{},o,this.context)||{};for(var s in a)o[s]=a[s];return o.ref=function(e){n.wrappedInstance=e},r(t,o)}});return o.contextTypes={mobxStores:function(){}},A(o,t),o}function l(e){var t=arguments;if("function"!=typeof e){for(var n=[],r=0;r<arguments.length;r++)n[r]=t[r];e=R(n)}return function(t){return c(e,t)}}function f(t,r){if(void 0===r&&(r=null),"string"==typeof t&&o("Store names should be provided as array"),Array.isArray(t))return r?l.apply(null,t)(f(r)):function(e){return f(t,e)};var i=t;if(!("function"!=typeof i||i.prototype&&i.prototype.render||i.isReactClass||e.isPrototypeOf(i))){var a=n({displayName:i.displayName||i.name,propTypes:i.propTypes,contextTypes:i.contextTypes,getDefaultProps:function(){return i.defaultProps},render:function(){return i.call(this,this.props,this.context)}});return f(a)}return i||o('Please pass a valid component to "observer"'),i.isMobXReactObserver=!0,u(i)}e="default"in e?e.default:e,t="default"in t?t.default:t,n="default"in n?n.default:n,r="default"in r?r.default:r;var p="a runtime error occured! Use Inferno in development environment to find the error.",h={children:!0,key:!0,ref:!0},d=function(e){function t(t,n){e.call(this,t,n),this.contextTypes={mobxStores:function(){}},this.childContextTypes={mobxStores:function(){}},this.store=t.store}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.render=function(){return this.props.children},t.prototype.getChildContext=function(){var e=this,t={},n=this.context.mobxStores;if(n)for(var r in n)t[r]=n[r];for(var o in this.props)h[o]||(t[o]=e.props[o]);return{mobxStores:t}},t}(e),v="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},b=i(function(e,t){function n(e,t,n,o){return 1===arguments.length&&"function"==typeof e?U(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof t?U(e,t):1===arguments.length&&"string"==typeof e?r(e):r(t).apply(null,arguments)}function r(e){return function(t,n,r){return r&&"function"==typeof r.value?(r.value=U(e,r.value),r.enumerable=!1,r.configurable=!0,r):Vt(e).apply(this,arguments)}}function o(e,t,n){var r="string"==typeof e?e:e.name||"<unnamed action>",o="function"==typeof e?e:t,i="function"==typeof e?t:n;return yt("function"==typeof o,"`runInAction` expects a function"),yt(0===o.length,"`runInAction` expects a function without arguments"),yt("string"==typeof r&&r.length>0,"actions should have valid names, got: '"+r+"'"),N(r,o,i,void 0)}function i(e){return"function"==typeof e&&e.isMobxAction===!0}function a(e,t,n){function r(){a(u)}var o,a,s;"string"==typeof e?(o=e,a=t,s=n):"function"==typeof e&&(o=e.name||"Autorun@"+bt(),a=e,s=t),Fe(a,"autorun methods cannot have modifiers"),yt("function"==typeof a,"autorun expects a function"),yt(i(a)===!1,"Warning: attempted to pass an action to autorun. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."),s&&(a=a.bind(s));var u=new qt(o,function(){this.track(r)});return u.schedule(),u.getDisposer()}function s(e,t,n,r){var o,i,s,u;"string"==typeof e?(o=e,i=t,s=n,u=r):"function"==typeof e&&(o="When@"+bt(),i=e,s=t,u=n);var c=a(o,function(e){if(i.call(u)){e.dispose();var t=ee();s.call(u),te(t)}});return c}function u(e,t,n){return mt("`autorunUntil` is deprecated, please use `when`."),s.apply(null,arguments)}function c(e,t,n,r){function o(){s(f)}var a,s,u,c;"string"==typeof e?(a=e,s=t,u=n,c=r):"function"==typeof e&&(a=e.name||"AutorunAsync@"+bt(),s=e,u=t,c=n),yt(i(s)===!1,"Warning: attempted to pass an action to autorunAsync. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."),void 0===u&&(u=1),c&&(s=s.bind(c));var l=!1,f=new qt(a,function(){l||(l=!0,setTimeout(function(){l=!1,f.isDisposed||f.track(o)},u))});return f.schedule(),f.getDisposer()}function l(e,t,r,o,i,a){function s(){if(!w.isDisposed){var e=!1;w.track(function(){var t=b(w);e=At(y,x,t),x=t}),m&&f&&l(x,w),m||e!==!0||l(x,w),m&&(m=!1)}}var u,c,l,f,p,h;"string"==typeof e?(u=e,c=t,l=r,f=o,p=i,h=a):(u=e.name||t.name||"Reaction@"+bt(),c=e,l=t,f=r,p=o,h=i),void 0===f&&(f=!1),void 0===p&&(p=0);var d=Ne(c,tn.Reference),v=d[0],b=d[1],y=v===tn.Structure;h&&(b=b.bind(h),l=n(u,l.bind(h)));var m=!0,g=!1,x=void 0,w=new qt(u,function(){p<1?s():g||(g=!0,setTimeout(function(){g=!1,s()},p))});return w.schedule(),w.getDisposer()}function f(e,t,n,r){return"function"==typeof e&&arguments.length<3?"function"==typeof t?p(e,t,void 0):p(e,void 0,t):$t.apply(null,arguments)}function p(e,t,n){var r=Ne(e,tn.Recursive),o=r[0],i=r[1];return new Wt(i,n,o===tn.Structure,i.name,t)}function h(e,t){yt("function"==typeof e&&1===e.length,"createTransformer expects a function that accepts one argument");var n={},r=Xt.resetId,o=function(r){function o(t,n){r.call(this,function(){return e(n)},null,!1,"Transformer-"+e.name+"-"+t,void 0),this.sourceIdentifier=t,this.sourceObject=n}return Mt(o,r),o.prototype.onBecomeUnobserved=function(){var e=this.value;r.prototype.onBecomeUnobserved.call(this),delete n[this.sourceIdentifier],t&&t(e,this.sourceObject)},o}(Wt);return function(e){r!==Xt.resetId&&(n={},r=Xt.resetId);var t=d(e),i=n[t];return i?i.get():(i=n[t]=new o(t,e),i.get())}}function d(e){if(null===e||"object"!=typeof e)throw new Error("[mobx] transform expected some kind of object, got: "+e);var t=e.$transformId;return void 0===t&&(t=bt(),Tt(e,"$transformId",t)),t}function b(e,t){return K()||console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."),f(e,t).get()}function y(e){for(var t=arguments,n=[],r=1;r<arguments.length;r++)n[r-1]=t[r];return yt(arguments.length>=2,"extendObservable expected 2 or more arguments"),yt("object"==typeof e,"extendObservable expects an object as first argument"),yt(!pn(e),"extendObservable should not be used on maps, use map.merge instead"),n.forEach(function(t){yt("object"==typeof t,"all arguments of extendObservable should be objects"),yt(!k(t),"extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540"),m(e,t,tn.Recursive,null)}),e}function m(e,t,n,r){var o=Qe(e,r,n);for(var i in t)if(Rt(t,i)){if(e===t&&!jt(e,i))continue;var a=Object.getOwnPropertyDescriptor(t,i);Ze(o,i,a)}return e}function g(e,t){return x(at(e,t))}function x(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=xt(e.observing).map(x)),t}function w(e,t){return _(at(e,t))}function _(e){var t={name:e.name};return ie(e)&&(t.observers=ae(e).map(_)),t}function S(e,t,n){return"function"==typeof n?A(e,t,n):O(e,t)}function O(e,t){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),st(I(e)).intercept(t)):st(e).intercept(t)}function A(e,t,n){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),y(e,{property:e[t]}),A(e,t,n)):st(e,t).intercept(n)}function R(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(it(e)===!1)return!1;var n=at(e,t);return Gt(n)}return Gt(e)}function k(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(qe(e)||pn(e))throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");if(it(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return!!e.$mobx||Jt(e)||Zt(e)||Gt(e)}function T(e,t,n){return yt(arguments.length>=2&&arguments.length<=3,"Illegal decorator config",t),Et(e,t),yt(!n||!n.get,"@observable can not be used on getters, use @computed instead"),Ut.apply(null,arguments)}function I(e,t){if(void 0===e&&(e=void 0),"string"==typeof arguments[1])return T.apply(null,arguments);if(yt(arguments.length<3,"observable expects zero, one or two arguments"),k(e))return e;var n=Ne(e,tn.Recursive),r=n[0],o=n[1],i=r===tn.Reference?Nt.Reference:j(o);switch(i){case Nt.Array:case Nt.PlainObject:return ze(o,r);case Nt.Reference:case Nt.ComplexObject:return new mn(o,r);case Nt.ComplexFunction:throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");case Nt.ViewFunction:return mt("Use `computed(expr)` instead of `observable(expr)`"),f(e,t)}yt(!1,"Illegal State")}function j(e){return null===e||void 0===e?Nt.Reference:"function"==typeof e?e.length?Nt.ComplexFunction:Nt.ViewFunction:Lt(e)?Nt.Array:"object"==typeof e?St(e)?Nt.PlainObject:Nt.ComplexObject:Nt.Reference}function E(e,t,n,r){return"function"==typeof n?P(e,t,n,r):C(e,t,n)}function C(e,t,n){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),st(I(e)).observe(t,n)):st(e).observe(t,n)}function P(e,t,n,r){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),y(e,{property:e[t]}),P(e,t,n,r)):st(e,t).observe(n,r)}function D(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),k(e)){if(t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;o<i;o++)if(n[o][0]===e)return n[o][1];if(qe(e)){var a=r([]),s=e.map(function(e){return D(e,t,n)});a.length=s.length;for(var o=0,i=s.length;o<i;o++)a[o]=s[o];return a}if(it(e)){var a=r({});for(var u in e)a[u]=D(e[u],t,n);return a}if(pn(e)){var c=r({});return e.forEach(function(e,r){return c[r]=D(e,t,n)}),c}if(gn(e))return D(e.get(),t,n)}return e}function L(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),mt("toJSlegacy is deprecated and will be removed in the next major. Use `toJS` instead. See #566"),e instanceof Date||e instanceof RegExp)return e;if(t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;o<i;o++)if(n[o][0]===e)return n[o][1];if(!e)return e;if(Lt(e)){var a=r([]),s=e.map(function(e){return L(e,t,n)});a.length=s.length;for(var o=0,i=s.length;o<i;o++)a[o]=s[o];return a}if(pn(e)){var u=r({});return e.forEach(function(e,r){return u[r]=L(e,t,n)}),u}if(gn(e))return L(e.get(),t,n);if("object"==typeof e){var a=r({});for(var c in e)a[c]=L(e[c],t,n);return a}return e}function M(e,t,n){return void 0===t&&(t=!0),void 0===n&&(n=null),mt("toJSON is deprecated. Use toJS instead"),L.apply(null,arguments)}function V(e){return console.log(e),e}function $(e,t){switch(arguments.length){case 0:if(e=Xt.trackingDerivation,!e)return V("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value.");break;case 2:e=at(e,t)}return e=at(e),Gt(e)?V(e.whyRun()):Zt(e)?V(e.whyRun()):void yt(!1,"whyRun can only be used on reactions and computed values")}function U(e,t){yt("function"==typeof t,"`action` can only be invoked on functions"),yt("string"==typeof e&&e.length>0,"actions should have valid names, got: '"+e+"'");var n=function(){return N(e,t,this,arguments)};return n.isMobxAction=!0,n}function N(e,t,n,r){yt(!Gt(Xt.trackingDerivation),"Computed values or transformers should not invoke actions or trigger other side effects");var o,i=ge();if(i){o=Date.now();var a=r&&r.length||0,s=new Array(a);if(a>0)for(var u=0;u<a;u++)s[u]=r[u];we({type:"action",name:e,fn:t,target:n,arguments:s})}var c=ee();Re(e,n,!1);var l=J(!0);try{return t.apply(n,r)}finally{W(l),ke(!1),te(c),i&&_e({time:Date.now()-o})}}function B(e){return 0===arguments.length?(mt("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead"),Xt.strictMode):(yt(null===Xt.trackingDerivation,"It is not allowed to set `useStrict` when a derivation is running"),Xt.strictMode=e,Xt.allowStateChanges=!e,void 0)}function z(){return Xt.strictMode}function F(e,t){var n=J(e),r=t();return W(n),r}function J(e){var t=Xt.allowStateChanges;return Xt.allowStateChanges=e,t}function W(e){Xt.allowStateChanges=e}function G(e){switch(e.dependenciesState){case Ft.UP_TO_DATE:return!1;case Ft.NOT_TRACKING:case Ft.STALE:return!0;case Ft.POSSIBLY_STALE:var t=!0,n=ee();try{for(var r=e.observing,o=r.length,i=0;i<o;i++){var a=r[i];if(Gt(a)&&(a.get(),e.dependenciesState===Ft.STALE))return t=!1,te(n),!0}return t=!1,ne(e),te(n),!1}finally{t&&ne(e)}}}function K(){return null!==Xt.trackingDerivation}function H(){Xt.allowStateChanges||yt(!1,Xt.strictMode?"It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended":"It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.")}function X(e,t){ne(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++Xt.runId;var n=Xt.trackingDerivation;Xt.trackingDerivation=e;var r,o=!0;try{r=t.call(e),o=!1}finally{o?q(e):(Xt.trackingDerivation=n,Y(e))}return r}function q(e){var t="[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. These functions should never throw exceptions as MobX will not always be able to recover from them. "+("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '"+e.name+"'. ")+"For more details see https://github.com/mobxjs/mobx/issues/462";ge()&&xe({type:"error",message:t}),console.warn(t),ne(e),e.newObserving=null,e.unboundDepsCount=0,e.recoverFromError(),fe(),oe()}function Y(e){var t=e.observing,n=e.observing=e.newObserving;e.newObserving=null;for(var r=0,o=e.unboundDepsCount,i=0;i<o;i++){var a=n[i];0===a.diffValue&&(a.diffValue=1,r!==i&&(n[r]=a),r++)}for(n.length=r,o=t.length;o--;){var a=t[o];0===a.diffValue&&ue(a,e),a.diffValue=0}for(;r--;){var a=n[r];1===a.diffValue&&(a.diffValue=0,se(a,e))}}function Q(e){for(var t=e.observing,n=t.length;n--;)ue(t[n],e);e.dependenciesState=Ft.NOT_TRACKING,t.length=0}function Z(e){var t=ee(),n=e();return te(t),n}function ee(){var e=Xt.trackingDerivation;return Xt.trackingDerivation=null,e}function te(e){Xt.trackingDerivation=e}function ne(e){if(e.dependenciesState!==Ft.UP_TO_DATE){e.dependenciesState=Ft.UP_TO_DATE;for(var t=e.observing,n=t.length;n--;)t[n].lowestObserverState=Ft.UP_TO_DATE}}function re(){}function oe(){Xt.resetId++;var e=new Ht;for(var t in e)Kt.indexOf(t)===-1&&(Xt[t]=e[t]);Xt.allowStateChanges=!Xt.strictMode}function ie(e){return e.observers&&e.observers.length>0}function ae(e){return e.observers}function se(e,t){var n=e.observers.length;n&&(e.observersIndexes[t.__mapid]=n),e.observers[n]=t,e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function ue(e,t){if(1===e.observers.length)e.observers.length=0,ce(e);else{var n=e.observers,r=e.observersIndexes,o=n.pop();if(o!==t){var i=r[t.__mapid]||0;i?r[o.__mapid]=i:delete r[o.__mapid],n[i]=o}delete r[t.__mapid]}}function ce(e){e.isPendingUnobservation||(e.isPendingUnobservation=!0,Xt.pendingUnobservations.push(e))}function le(){Xt.inBatch++}function fe(){if(1===Xt.inBatch){for(var e=Xt.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,0===n.observers.length&&n.onBecomeUnobserved()}Xt.pendingUnobservations=[]}Xt.inBatch--}function pe(e){var t=Xt.trackingDerivation;null!==t?t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e):0===e.observers.length&&ce(e)}function he(e){if(e.lowestObserverState!==Ft.STALE){e.lowestObserverState=Ft.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Ft.UP_TO_DATE&&r.onBecomeStale(),r.dependenciesState=Ft.STALE}}}function de(e){if(e.lowestObserverState!==Ft.STALE){e.lowestObserverState=Ft.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Ft.POSSIBLY_STALE?r.dependenciesState=Ft.STALE:r.dependenciesState===Ft.UP_TO_DATE&&(e.lowestObserverState=Ft.UP_TO_DATE)}}}function ve(e){if(e.lowestObserverState===Ft.UP_TO_DATE){e.lowestObserverState=Ft.POSSIBLY_STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Ft.UP_TO_DATE&&(r.dependenciesState=Ft.POSSIBLY_STALE,r.onBecomeStale())}}}function be(){Xt.isRunningReactions===!0||Xt.inTransaction>0||Qt(ye)}function ye(){Xt.isRunningReactions=!0;for(var e=Xt.pendingReactions,t=0;e.length>0;){if(++t===Yt)throw oe(),new Error("Reaction doesn't converge to a stable state after "+Yt+" iterations. Probably there is a cycle in the reactive function: "+e[0]);for(var n=e.splice(0),r=0,o=n.length;r<o;r++)n[r].runReaction()}Xt.isRunningReactions=!1}function me(e){var t=Qt;Qt=function(n){return e(function(){return t(n)})}}function ge(){return!!Xt.spyListeners.length}function xe(e){if(!Xt.spyListeners.length)return!1;for(var t=Xt.spyListeners,n=0,r=t.length;n<r;n++)t[n](e)}function we(e){var t=Ot({},e,{spyReportStart:!0});xe(t)}function _e(e){xe(e?Ot({},e,en):en)}function Se(e){return Xt.spyListeners.push(e),gt(function(){var t=Xt.spyListeners.indexOf(e);t!==-1&&Xt.spyListeners.splice(t,1)})}function Oe(e){return mt("trackTransitions is deprecated. Use mobx.spy instead"),"boolean"==typeof e&&(mt("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"),e=arguments[1]),e?Se(e):(mt("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"),function(){})}function Ae(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),Re(e.name||"anonymous transaction",t,n);try{return e.call(t)}finally{ke(n)}}function Re(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),le(),Xt.inTransaction+=1,n&&ge()&&we({type:"transaction",target:t,name:e})}function ke(e){void 0===e&&(e=!0),0===--Xt.inTransaction&&be(),e&&ge()&&_e(),fe()}function Te(e){return e.interceptors&&e.interceptors.length>0}function Ie(e,t){var n=e.interceptors||(e.interceptors=[]);return n.push(t),gt(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function je(e,t){for(var n=ee(),r=e.interceptors,o=0,i=r.length;o<i;o++)if(t=r[o](t),yt(!t||t.type,"Intercept handlers should return nothing or a change object"),!t)return null;return te(n),t}function Ee(e){return e.changeListeners&&e.changeListeners.length>0}function Ce(e,t){var n=e.changeListeners||(e.changeListeners=[]);return n.push(t),gt(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Pe(e,t){var n=ee(),r=e.changeListeners;if(r){r=r.slice();for(var o=0,i=r.length;o<i;o++)Array.isArray(t)?r[o].apply(null,t):r[o](t);te(n)}}function De(e,t){return Fe(t,"Modifiers are not allowed to be nested"),{mobxModifier:e,value:t}}function Le(e){return e?e.mobxModifier||null:null}function Me(e){return De(tn.Reference,e)}function Ve(e){return De(tn.Structure,e)}function $e(e){return De(tn.Flat,e)}function Ue(e,t){return Ye(e,t)}function Ne(e,t){var n=Le(e);return n?[n,e.value]:[t,e]}function Be(e){if(void 0===e)return tn.Recursive;var t=Le(e);return yt(null!==t,"Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: "+e),t}function ze(e,t,n){var r;if(k(e))return e;switch(t){case tn.Reference:return e;case tn.Flat:Fe(e,"Items inside 'asFlat' cannot have modifiers"),r=tn.Reference;break;case tn.Structure:Fe(e,"Items inside 'asStructure' cannot have modifiers"),r=tn.Structure;break;case tn.Recursive:o=Ne(e,tn.Recursive),r=o[0],e=o[1];break;default:yt(!1,"Illegal State")}return Array.isArray(e)?He(e,r,n):St(e)&&Object.isExtensible(e)?m(e,e,r,n):e;var o}function Fe(e,t){if(null!==Le(e))throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. "+t)}function Je(e){var t=We(e),n=Ge(e);Object.defineProperty(sn.prototype,""+e,{enumerable:!1,configurable:!0,set:t,get:n})}function We(e){return function(t){var n=this.$mobx,r=n.values;if(Fe(t,"Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."),e<r.length){H();var o=r[e];if(Te(n)){var i=je(n,{type:"update",object:n.array,index:e,newValue:t});if(!i)return;t=i.newValue}t=n.makeReactiveArrayItem(t);var a=n.mode===tn.Structure?!Pt(o,t):o!==t;a&&(r[e]=t,n.notifyArrayChildUpdate(e,t,o))}else{if(e!==r.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+r.length);n.spliceWithArray(e,0,[t])}}}function Ge(e){return function(){var t=this.$mobx;return t&&e<t.values.length?(t.atom.reportObserved(),t.values[e]):void console.warn("[mobx.array] Attempt to read an array index ("+e+") that is out of bounds ("+t.values.length+"). Please check length first. Out of bound indices will not be tracked by MobX")}}function Ke(e){for(var t=rn;t<e;t++)Je(t);rn=e}function He(e,t,n){return new sn(e,t,n)}function Xe(e){return mt("fastArray is deprecated. Please use `observable(asFlat([]))`"),He(e,tn.Flat,null)}function qe(e){return _t(e)&&cn(e.$mobx)}function Ye(e,t){return new fn(e,t)}function Qe(e,t,n){if(void 0===n&&(n=tn.Recursive),it(e))return e.$mobx;St(e)||(t=e.constructor.name+"@"+bt()),t||(t="ObservableObject@"+bt());var r=new hn(e,t,n);return It(e,"$mobx",r),r}function Ze(e,t,n){e.values[t]?(yt("value"in n,"cannot redefine property "+t),e.target[t]=n.value):"value"in n?et(e,t,n.value,!0,void 0):et(e,t,n.get,!0,n.set)}function et(e,t,n,r,o){r&&Et(e.target,t);var a,s=e.name+"."+t,u=!0;if(Gt(n))a=n,n.name=s,n.scope||(n.scope=e.target);else if("function"!=typeof n||0!==n.length||i(n))if(Le(n)===tn.Structure&&"function"==typeof n.value&&0===n.value.length)a=new Wt(n.value,e.target,!0,s,o);else{if(u=!1,Te(e)){var c=je(e,{object:e.target,name:t,type:"add",newValue:n});if(!c)return;n=c.newValue}a=new mn(n,e.mode,s,!1),n=a.value}else a=new Wt(n,e.target,!1,s,o);e.values[t]=a,r&&Object.defineProperty(e.target,t,u?nt(t):tt(t)),u||ot(e,e.target,t,n)}function tt(e){var t=dn[e];return t?t:dn[e]={configurable:!0,enumerable:!0,get:function(){return this.$mobx.values[e].get()},set:function(t){rt(this,e,t)}}}function nt(e){var t=vn[e];return t?t:vn[e]={configurable:!0,enumerable:!1,get:function(){return this.$mobx.values[e].get()},set:function(t){return this.$mobx.values[e].set(t)}}}function rt(e,t,n){var r=e.$mobx,o=r.values[t];if(Te(r)){var i=je(r,{type:"update",object:e,name:t,newValue:n});if(!i)return;n=i.newValue}if(n=o.prepareNewValue(n),n!==yn){var a=Ee(r),s=ge(),i=a||s?{type:"update",object:e,oldValue:o.value,name:t,newValue:n}:null;s&&we(i),o.setNewValue(n),a&&Pe(r,i),s&&_e()}}function ot(e,t,n,r){var o=Ee(e),i=ge(),a=o||i?{type:"add",object:t,name:n,newValue:r}:null;i&&we(a),o&&Pe(e,a),i&&_e()}function it(e){return!!_t(e)&&(ft(e),bn(e.$mobx))}function at(e,t){if("object"==typeof e&&null!==e){if(qe(e))return yt(void 0===t,"It is not possible to get index atoms from arrays"),e.$mobx.atom;if(pn(e)){if(void 0===t)return at(e._keys);var n=e._data[t]||e._hasMap[t];return yt(!!n,"the entry '"+t+"' does not exist in the observable map '"+ut(e)+"'"),n}if(ft(e),it(e)){yt(!!t,"please specify a property");var r=e.$mobx.values[t];return yt(!!r,"no observable property '"+t+"' found on the observable object '"+ut(e)+"'"),r}if(Jt(e)||Gt(e)||Zt(e))return e}else if("function"==typeof e&&Zt(e.$mobx))return e.$mobx;yt(!1,"Cannot obtain atom from "+e)}function st(e,t){return yt(e,"Expecting some object"),void 0!==t?st(at(e,t)):Jt(e)||Gt(e)||Zt(e)?e:pn(e)?e:(ft(e),e.$mobx?e.$mobx:void yt(!1,"Cannot obtain administration from "+e))}function ut(e,t){var n;return n=void 0!==t?at(e,t):it(e)||pn(e)?st(e):at(e),n.name}function ct(e,t,n,r,o){function i(i,a,s,u,c){if(yt(o||pt(arguments),"This function is a decorator, but it wasn't invoked like a decorator"),s){Rt(i,"__mobxLazyInitializers")||Tt(i,"__mobxLazyInitializers",i.__mobxLazyInitializers&&i.__mobxLazyInitializers.slice()||[]);var l=s.value,f=s.initializer;return i.__mobxLazyInitializers.push(function(t){e(t,a,f?f.call(t):l,u,s)}),{enumerable:r,configurable:!0,get:function(){return this.__mobxDidRunLazyInitializers!==!0&&ft(this),t.call(this,a)},set:function(e){this.__mobxDidRunLazyInitializers!==!0&&ft(this),n.call(this,a,e)}}}var p={enumerable:r,configurable:!0,get:function(){return this.__mobxInitializedProps&&this.__mobxInitializedProps[a]===!0||lt(this,a,void 0,e,u,s),t.call(this,a)},set:function(t){this.__mobxInitializedProps&&this.__mobxInitializedProps[a]===!0?n.call(this,a,t):lt(this,a,t,e,u,s)}};return(arguments.length<3||5===arguments.length&&c<3)&&Object.defineProperty(i,a,p),p}return o?function(){if(pt(arguments))return i.apply(null,arguments);var e=arguments,t=arguments.length;return function(n,r,o){return i(n,r,o,e,t)}}:i}function lt(e,t,n,r,o,i){Rt(e,"__mobxInitializedProps")||Tt(e,"__mobxInitializedProps",{}),e.__mobxInitializedProps[t]=!0,r(e,t,n,o,i)}function ft(e){e.__mobxDidRunLazyInitializers!==!0&&e.__mobxLazyInitializers&&(Tt(e,"__mobxDidRunLazyInitializers",!0),e.__mobxDidRunLazyInitializers&&e.__mobxLazyInitializers.forEach(function(t){return t(e)}))}function pt(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]}function ht(){return"function"==typeof Symbol&&Symbol.iterator||"@@iterator"}function dt(e){yt(e[xn]!==!0,"Illegal state: cannot recycle array as iterator"),It(e,xn,!0);var t=-1;return It(e,"next",function(){return t++,{done:t>=this.length,value:t<this.length?this[t]:void 0}}),e}function vt(e,t){It(e,ht(),t)}function bt(){return++Xt.mobxGuid}function yt(e,t,n){if(!e)throw new Error("[mobx] Invariant failed: "+t+(n?" in '"+n+"'":""))}function mt(e){Sn.indexOf(e)===-1&&(Sn.push(e),console.error("[mobx] Deprecated: "+e))}function gt(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function xt(e){var t=[];return e.forEach(function(e){t.indexOf(e)===-1&&t.push(e)}),t}function wt(e,t,n){if(void 0===t&&(t=100),void 0===n&&(n=" - "),!e)return"";var r=e.slice(0,t);return""+r.join(n)+(e.length>t?" (... and "+(e.length-t)+"more)":"")}function _t(e){return null!==e&&"object"==typeof e}function St(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Ot(){for(var e=arguments,t=arguments[0],n=1,r=arguments.length;n<r;n++){var o=e[n];for(var i in o)Rt(o,i)&&(t[i]=o[i])}return t}function At(e,t,n){return e?!Pt(t,n):t!==n}function Rt(e,t){return An.call(e,t)}function kt(e,t){for(var n=0;n<t.length;n++)Tt(e,t[n],e[t[n]])}function Tt(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function It(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function jt(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return!n||n.configurable!==!1&&n.writable!==!1}function Et(e,t){yt(jt(e,t),"Cannot make property '"+t+"' observable, it is not configurable and writable in the target object")}function Ct(e){var t=[];for(var n in e)t.push(n);return t}function Pt(e,t){if(null===e&&null===t)return!0;if(void 0===e&&void 0===t)return!0;var n=Lt(e);if(n!==Lt(t))return!1;if(n){if(e.length!==t.length)return!1;for(var r=e.length-1;r>=0;r--)if(!Pt(e[r],t[r]))return!1;return!0}if("object"==typeof e&&"object"==typeof t){if(null===e||null===t)return!1;if(Ct(e).length!==Ct(t).length)return!1;for(var o in e){if(!(o in t))return!1;if(!Pt(e[o],t[o]))return!1}return!0}return e===t}function Dt(e,t){var n="isMobX"+e;return t.prototype[n]=!0,function(e){return _t(e)&&e[n]===!0}}function Lt(e){return Array.isArray(e)||qe(e)}var Mt=v&&v.__extends||function(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)};re(),t.extras={allowStateChanges:F,getAtom:at,getDebugName:ut,getDependencyTree:g,getObserverTree:w,isComputingDerivation:K,isSpyEnabled:ge,resetGlobalState:oe,spyReport:xe,spyReportEnd:_e,spyReportStart:we,trackTransitions:Oe,setReactionScheduler:me},t._={getAdministration:st,resetGlobalState:oe},"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(e.exports);var Vt=ct(function(e,t,r,o,i){var a=o&&1===o.length?o[0]:r.name||t||"<unnamed action>",s=n(a,r);Tt(e,t,s)},function(e){return this[e]},function(){yt(!1,"It is not allowed to assign new values to @action fields")},!1,!0);t.action=n,t.runInAction=o,t.isAction=i,t.autorun=a,t.when=s,t.autorunUntil=u,t.autorunAsync=c,t.reaction=l;var $t=ct(function(e,t,n,r,o){yt("undefined"!=typeof o,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property.");var i=o.get,a=o.set;yt("function"==typeof i,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");var s=!1;r&&1===r.length&&r[0].asStructure===!0&&(s=!0);var u=Qe(e,void 0,tn.Recursive);et(u,t,s?Ve(i):i,!1,a)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){this.$mobx.values[e].set(t)},!1,!0);t.computed=f,t.createTransformer=h,t.expr=b,t.extendObservable=y,t.intercept=S,t.isComputed=R,t.isObservable=k;var Ut=ct(function(e,t,n){var r=J(!0);"function"==typeof n&&(n=Me(n));var o=Qe(e,void 0,tn.Recursive);et(o,t,n,!0,void 0),W(r)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){rt(this,e,t)},!0,!1);t.observable=I;var Nt;!function(e){e[e.Reference=0]="Reference",e[e.PlainObject=1]="PlainObject",e[e.ComplexObject=2]="ComplexObject",e[e.Array=3]="Array",e[e.ViewFunction=4]="ViewFunction", e[e.ComplexFunction=5]="ComplexFunction"}(Nt||(Nt={})),t.observe=E,t.toJS=D,t.toJSlegacy=L,t.toJSON=M,t.whyRun=$,t.useStrict=B,t.isStrictModeEnabled=z;var Bt=function(){function e(e){void 0===e&&(e="Atom@"+bt()),this.name=e,this.isPendingUnobservation=!0,this.observers=[],this.observersIndexes={},this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=Ft.NOT_TRACKING}return e.prototype.onBecomeUnobserved=function(){},e.prototype.reportObserved=function(){pe(this)},e.prototype.reportChanged=function(){Re("propagatingAtomChange",null,!1),he(this),ke(!1)},e.prototype.toString=function(){return this.name},e}();t.BaseAtom=Bt;var zt=function(e){function t(t,n,r){void 0===t&&(t="Atom@"+bt()),void 0===n&&(n=On),void 0===r&&(r=On),e.call(this,t),this.name=t,this.onBecomeObservedHandler=n,this.onBecomeUnobservedHandler=r,this.isPendingUnobservation=!1,this.isBeingTracked=!1}return Mt(t,e),t.prototype.reportObserved=function(){return le(),e.prototype.reportObserved.call(this),this.isBeingTracked||(this.isBeingTracked=!0,this.onBecomeObservedHandler()),fe(),!!Xt.trackingDerivation},t.prototype.onBecomeUnobserved=function(){this.isBeingTracked=!1,this.onBecomeUnobservedHandler()},t}(Bt);t.Atom=zt;var Ft,Jt=Dt("Atom",Bt),Wt=function(){function e(e,t,n,r,o){this.derivation=e,this.scope=t,this.compareStructural=n,this.dependenciesState=Ft.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isPendingUnobservation=!1,this.observers=[],this.observersIndexes={},this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=Ft.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+bt(),this.value=void 0,this.isComputing=!1,this.isRunningSetter=!1,this.name=r||"ComputedValue@"+bt(),o&&(this.setter=U(r+"-setter",o))}return e.prototype.peek=function(){this.isComputing=!0;var e=J(!1),t=this.derivation.call(this.scope);return W(e),this.isComputing=!1,t},e.prototype.peekUntracked=function(){var e=!0;try{var t=this.peek();return e=!1,t}finally{e&&q(this)}},e.prototype.onBecomeStale=function(){ve(this)},e.prototype.onBecomeUnobserved=function(){yt(this.dependenciesState!==Ft.NOT_TRACKING,"INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row"),Q(this),this.value=void 0},e.prototype.get=function(){yt(!this.isComputing,"Cycle detected in computation "+this.name,this.derivation),le(),1===Xt.inBatch?G(this)&&(this.value=this.peekUntracked()):(pe(this),G(this)&&this.trackAndCompute()&&de(this));var e=this.value;return fe(),e},e.prototype.recoverFromError=function(){this.isComputing=!1},e.prototype.set=function(e){if(this.setter){yt(!this.isRunningSetter,"The setter of computed value '"+this.name+"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"),this.isRunningSetter=!0;try{this.setter.call(this.scope,e)}finally{this.isRunningSetter=!1}}else yt(!1,"[ComputedValue '"+this.name+"'] It is not possible to assign a new value to a computed value.")},e.prototype.trackAndCompute=function(){ge()&&xe({object:this,type:"compute",fn:this.derivation,target:this.scope});var e=this.value,t=this.value=X(this,this.peek);return At(this.compareStructural,t,e)},e.prototype.observe=function(e,t){var n=this,r=!0,o=void 0;return a(function(){var i=n.get();if(!r||t){var a=ee();e(i,o),te(a)}r=!1,o=i})},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.whyRun=function(){var e=Boolean(Xt.trackingDerivation),t=xt(this.isComputing?this.newObserving:this.observing).map(function(e){return e.name}),n=xt(ae(this).map(function(e){return e.name}));return"\nWhyRun? computation '"+this.name+"':\n * Running because: "+(e?"[active] the value of this computation is needed by a reaction":this.isComputing?"[get] The value of this computed was requested outside a reaction":"[idle] not running at the moment")+"\n"+(this.dependenciesState===Ft.NOT_TRACKING?" * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n":" * This computation will re-run if any of the following observables changes:\n "+wt(t)+"\n "+(this.isComputing&&e?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n "+wt(n)+"\n")},e}(),Gt=Dt("ComputedValue",Wt);!function(e){e[e.NOT_TRACKING=-1]="NOT_TRACKING",e[e.UP_TO_DATE=0]="UP_TO_DATE",e[e.POSSIBLY_STALE=1]="POSSIBLY_STALE",e[e.STALE=2]="STALE"}(Ft||(Ft={})),t.IDerivationState=Ft,t.untracked=Z;var Kt=["mobxGuid","resetId","spyListeners","strictMode","runId"],Ht=function(){function e(){this.version=4,this.trackingDerivation=null,this.runId=0,this.mobxGuid=0,this.inTransaction=0,this.isRunningReactions=!1,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.allowStateChanges=!0,this.strictMode=!1,this.resetId=0,this.spyListeners=[]}return e}(),Xt=function(){var e=new Ht;if(v.__mobservableTrackingStack||v.__mobservableViewStack)throw new Error("[mobx] An incompatible version of mobservable is already loaded.");if(v.__mobxGlobal&&v.__mobxGlobal.version!==e.version)throw new Error("[mobx] An incompatible version of mobx is already loaded.");return v.__mobxGlobal?v.__mobxGlobal:v.__mobxGlobal=e}(),qt=function(){function e(e,t){void 0===e&&(e="Reaction@"+bt()),this.name=e,this.onInvalidate=t,this.observing=[],this.newObserving=[],this.dependenciesState=Ft.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+bt(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,Xt.pendingReactions.push(this),le(),be(),fe())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){this.isDisposed||(this._isScheduled=!1,G(this)&&(this._isTrackPending=!0,this.onInvalidate(),this._isTrackPending&&ge()&&xe({object:this,type:"scheduled-reaction"})))},e.prototype.track=function(e){le();var t,n=ge();n&&(t=Date.now(),we({object:this,type:"reaction",fn:e})),this._isRunning=!0,X(this,e),this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&Q(this),n&&_e({time:Date.now()-t}),fe()},e.prototype.recoverFromError=function(){this._isRunning=!1,this._isTrackPending=!1},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(le(),Q(this),fe()))},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e.$mobx=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e.prototype.whyRun=function(){var e=xt(this._isRunning?this.newObserving:this.observing).map(function(e){return e.name});return"\nWhyRun? reaction '"+this.name+"':\n * Status: ["+(this.isDisposed?"stopped":this._isRunning?"running":this.isScheduled()?"scheduled":"idle")+"]\n * This reaction will re-run if any of the following observables changes:\n "+wt(e)+"\n "+(this._isRunning?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"},e}();t.Reaction=qt;var Yt=100,Qt=function(e){return e()},Zt=Dt("Reaction",qt),en={spyReportEnd:!0};t.spy=Se,t.transaction=Ae;var tn;!function(e){e[e.Recursive=0]="Recursive",e[e.Reference=1]="Reference",e[e.Structure=2]="Structure",e[e.Flat=3]="Flat"}(tn||(tn={})),t.asReference=Me,Me.mobxModifier=tn.Reference,t.asStructure=Ve,Ve.mobxModifier=tn.Structure,t.asFlat=$e,$e.mobxModifier=tn.Flat,t.asMap=Ue;var nn=function(){var e=!1,t={};return Object.defineProperty(t,"0",{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),rn=0,on=function(){function e(){}return e}();on.prototype=[];var an=function(){function e(e,t,n,r){this.mode=t,this.array=n,this.owned=r,this.lastKnownLength=0,this.interceptors=null,this.changeListeners=null,this.atom=new Bt(e||"ObservableArray@"+bt())}return e.prototype.makeReactiveArrayItem=function(e){return Fe(e,"Array values cannot have modifiers"),this.mode===tn.Flat||this.mode===tn.Reference?e:ze(e,this.mode,this.atom.name+"[..]")},e.prototype.intercept=function(e){return Ie(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.array,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),Ce(this,e)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||e<0)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;e!==t&&(e>t?this.spliceWithArray(t,0,new Array(e-t)):this.spliceWithArray(e,t-e))},e.prototype.updateArrayLength=function(e,t){if(e!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");this.lastKnownLength+=t,t>0&&e+t+1>rn&&Ke(e+t+1)},e.prototype.spliceWithArray=function(e,t,n){H();var r=this.values.length;if(void 0===e?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=1===arguments.length?r-e:void 0===t||null===t?0:Math.max(0,Math.min(t,r-e)),void 0===n&&(n=[]),Te(this)){var o=je(this,{object:this.array,type:"splice",index:e,removedCount:t,added:n});if(!o)return _n;t=o.removedCount,n=o.added}n=n.map(this.makeReactiveArrayItem,this);var i=n.length-t;this.updateArrayLength(r,i);var a=(s=this.values).splice.apply(s,[e,t].concat(n));return 0===t&&0===n.length||this.notifyArraySplice(e,n,a),a;var s},e.prototype.notifyArrayChildUpdate=function(e,t,n){var r=!this.owned&&ge(),o=Ee(this),i=o||r?{object:this.array,type:"update",index:e,newValue:t,oldValue:n}:null;r&&we(i),this.atom.reportChanged(),o&&Pe(this,i),r&&_e()},e.prototype.notifyArraySplice=function(e,t,n){var r=!this.owned&&ge(),o=Ee(this),i=o||r?{object:this.array,type:"splice",index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&we(i),this.atom.reportChanged(),o&&Pe(this,i),r&&_e()},e}(),sn=function(e){function t(t,n,r,o){void 0===o&&(o=!1),e.call(this);var i=new an(r,n,this,o);It(this,"$mobx",i),t&&t.length?(i.updateArrayLength(0,t.length),i.values=t.map(i.makeReactiveArrayItem,i),i.notifyArraySplice(0,i.values.slice(),_n)):i.values=[],nn&&Object.defineProperty(i.array,"0",un)}return Mt(t,e),t.prototype.intercept=function(e){return this.$mobx.intercept(e)},t.prototype.observe=function(e,t){return void 0===t&&(t=!1),this.$mobx.observe(e,t)},t.prototype.clear=function(){return this.splice(0)},t.prototype.concat=function(){for(var e=arguments,t=[],n=0;n<arguments.length;n++)t[n-0]=e[n];return this.$mobx.atom.reportObserved(),Array.prototype.concat.apply(this.slice(),t.map(function(e){return qe(e)?e.slice():e}))},t.prototype.replace=function(e){return this.$mobx.spliceWithArray(0,this.$mobx.values.length,e)},t.prototype.toJS=function(){return this.slice()},t.prototype.toJSON=function(){return this.toJS()},t.prototype.peek=function(){return this.$mobx.values},t.prototype.find=function(e,t,n){var r=this;void 0===n&&(n=0),this.$mobx.atom.reportObserved();for(var o=this.$mobx.values,i=o.length,a=n;a<i;a++)if(e.call(t,o[a],a,r))return o[a]},t.prototype.splice=function(e,t){for(var n=arguments,r=[],o=2;o<arguments.length;o++)r[o-2]=n[o];switch(arguments.length){case 0:return[];case 1:return this.$mobx.spliceWithArray(e);case 2:return this.$mobx.spliceWithArray(e,t)}return this.$mobx.spliceWithArray(e,t,r)},t.prototype.push=function(){for(var e=arguments,t=[],n=0;n<arguments.length;n++)t[n-0]=e[n];var r=this.$mobx;return r.spliceWithArray(r.values.length,0,t),r.values.length},t.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},t.prototype.shift=function(){return this.splice(0,1)[0]},t.prototype.unshift=function(){for(var e=arguments,t=[],n=0;n<arguments.length;n++)t[n-0]=e[n];var r=this.$mobx;return r.spliceWithArray(0,0,t),r.values.length},t.prototype.reverse=function(){this.$mobx.atom.reportObserved();var e=this.slice();return e.reverse.apply(e,arguments)},t.prototype.sort=function(e){this.$mobx.atom.reportObserved();var t=this.slice();return t.sort.apply(t,arguments)},t.prototype.remove=function(e){var t=this.$mobx.values.indexOf(e);return t>-1&&(this.splice(t,1),!0)},t.prototype.toString=function(){return"[mobx.array] "+Array.prototype.toString.apply(this.$mobx.values,arguments)},t.prototype.toLocaleString=function(){return"[mobx.array] "+Array.prototype.toLocaleString.apply(this.$mobx.values,arguments)},t}(on);vt(sn.prototype,function(){return dt(this.slice())}),kt(sn.prototype,["constructor","intercept","observe","clear","concat","replace","toJS","toJSON","peek","find","splice","push","pop","shift","unshift","reverse","sort","remove","toString","toLocaleString"]),Object.defineProperty(sn.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return this.$mobx.getArrayLength()},set:function(e){this.$mobx.setArrayLength(e)}}),["every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some"].forEach(function(e){var t=Array.prototype[e];yt("function"==typeof t,"Base function not defined on Array prototype: '"+e+"'"),Tt(sn.prototype,e,function(){return this.$mobx.atom.reportObserved(),t.apply(this.$mobx.values,arguments)})});var un={configurable:!0,enumerable:!1,set:We(0),get:Ge(0)};Ke(1e3),t.fastArray=Xe;var cn=Dt("ObservableArrayAdministration",an);t.isObservableArray=qe;var ln={},fn=function(){function e(e,t){var n=this;this.$mobx=ln,this._data={},this._hasMap={},this.name="ObservableMap@"+bt(),this._keys=new sn(null,tn.Reference,this.name+".keys()",!0),this.interceptors=null,this.changeListeners=null,this._valueMode=Be(t),this._valueMode===tn.Flat&&(this._valueMode=tn.Reference),F(!0,function(){St(e)?n.merge(e):Array.isArray(e)&&e.forEach(function(e){var t=e[0],r=e[1];return n.set(t,r)})})}return e.prototype._has=function(e){return"undefined"!=typeof this._data[e]},e.prototype.has=function(e){return!!this.isValidKey(e)&&(e=""+e,this._hasMap[e]?this._hasMap[e].get():this._updateHasMapEntry(e,!1).get())},e.prototype.set=function(e,t){this.assertValidKey(e),e=""+e;var n=this._has(e);if(Fe(t,"[mobx.map.set] Expected unwrapped value to be inserted to key '"+e+"'. If you need to use modifiers pass them as second argument to the constructor"),Te(this)){var r=je(this,{type:n?"update":"add",object:this,newValue:t,name:e});if(!r)return;t=r.newValue}n?this._updateValue(e,t):this._addValue(e,t)},e.prototype.delete=function(e){var t=this;if(this.assertValidKey(e),e=""+e,Te(this)){var n=je(this,{type:"delete",object:this,name:e});if(!n)return!1}if(this._has(e)){var r=ge(),o=Ee(this),n=o||r?{type:"delete",object:this,oldValue:this._data[e].value,name:e}:null;return r&&we(n),Ae(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1);var n=t._data[e];n.setNewValue(void 0),t._data[e]=void 0},void 0,!1),o&&Pe(this,n),r&&_e(),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var n=this._hasMap[e];return n?n.setNewValue(t):n=this._hasMap[e]=new mn(t,tn.Reference,this.name+"."+e+"?",!1),n},e.prototype._updateValue=function(e,t){var n=this._data[e];if(t=n.prepareNewValue(t),t!==yn){var r=ge(),o=Ee(this),i=o||r?{type:"update",object:this,oldValue:n.value,name:e,newValue:t}:null;r&&we(i),n.setNewValue(t),o&&Pe(this,i),r&&_e()}},e.prototype._addValue=function(e,t){var n=this;Ae(function(){var r=n._data[e]=new mn(t,n._valueMode,n.name+"."+e,!1);t=r.value,n._updateHasMapEntry(e,!0),n._keys.push(e)},void 0,!1);var r=ge(),o=Ee(this),i=o||r?{type:"add",object:this,name:e,newValue:t}:null;r&&we(i),o&&Pe(this,i),r&&_e()},e.prototype.get=function(e){if(e=""+e,this.has(e))return this._data[e].get()},e.prototype.keys=function(){return dt(this._keys.slice())},e.prototype.values=function(){return dt(this._keys.map(this.get,this))},e.prototype.entries=function(){var e=this;return dt(this._keys.map(function(t){return[t,e.get(t)]}))},e.prototype.forEach=function(e,t){var n=this;this.keys().forEach(function(r){return e.call(t,n.get(r),r)})},e.prototype.merge=function(e){var t=this;return Ae(function(){pn(e)?e.keys().forEach(function(n){return t.set(n,e.get(n))}):Object.keys(e).forEach(function(n){return t.set(n,e[n])})},void 0,!1),this},e.prototype.clear=function(){var e=this;Ae(function(){Z(function(){e.keys().forEach(e.delete,e)})},void 0,!1)},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toJS=function(){var e=this,t={};return this.keys().forEach(function(n){return t[n]=e.get(n)}),t},e.prototype.toJs=function(){return mt("toJs is deprecated, use toJS instead"),this.toJS()},e.prototype.toJSON=function(){return this.toJS()},e.prototype.isValidKey=function(e){return null!==e&&void 0!==e&&("string"==typeof e||"number"==typeof e||"boolean"==typeof e)},e.prototype.assertValidKey=function(e){if(!this.isValidKey(e))throw new Error("[mobx.map] Invalid key: '"+e+"'")},e.prototype.toString=function(){var e=this;return this.name+"[{ "+this.keys().map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return yt(t!==!0,"`observe` doesn't support the fire immediately property for observable maps."),Ce(this,e)},e.prototype.intercept=function(e){return Ie(this,e)},e}();t.ObservableMap=fn,vt(fn.prototype,function(){return this.entries()}),t.map=Ye;var pn=Dt("ObservableMap",fn);t.isObservableMap=pn;var hn=function(){function e(e,t,n){this.target=e,this.name=t,this.mode=n,this.values={},this.changeListeners=null,this.interceptors=null}return e.prototype.observe=function(e,t){return yt(t!==!0,"`observe` doesn't support the fire immediately property for observable objects."),Ce(this,e)},e.prototype.intercept=function(e){return Ie(this,e)},e}(),dn={},vn={},bn=Dt("ObservableObjectAdministration",hn);t.isObservableObject=it;var yn={},mn=function(e){function t(t,n,r,o){void 0===r&&(r="ObservableValue@"+bt()),void 0===o&&(o=!0),e.call(this,r),this.mode=n,this.hasUnreportedChange=!1,this.value=void 0;var i=Ne(t,tn.Recursive),a=i[0],s=i[1];this.mode===tn.Recursive&&(this.mode=a),this.value=ze(s,this.mode,this.name),o&&ge()&&xe({type:"create",object:this,newValue:this.value})}return Mt(t,e),t.prototype.set=function(e){var t=this.value;if(e=this.prepareNewValue(e),e!==yn){var n=ge();n&&we({type:"update",object:this,newValue:e,oldValue:t}),this.setNewValue(e),n&&_e()}},t.prototype.prepareNewValue=function(e){if(Fe(e,"Modifiers cannot be used on non-initial values."),H(),Te(this)){var t=je(this,{object:this,type:"update",newValue:e});if(!t)return yn;e=t.newValue}var n=At(this.mode===tn.Structure,this.value,e);return n?ze(e,this.mode,this.name):yn},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),Ee(this)&&Pe(this,[e,t])},t.prototype.get=function(){return this.reportObserved(),this.value},t.prototype.intercept=function(e){return Ie(this,e)},t.prototype.observe=function(e,t){return t&&e(this.value,void 0),Ce(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t}(Bt),gn=Dt("ObservableValue",mn),xn="__$$iterating",wn=function(){function e(){this.listeners=[],mt("extras.SimpleEventEmitter is deprecated and will be removed in the next major release")}return e.prototype.emit=function(){for(var e=arguments,t=this.listeners.slice(),n=0,r=t.length;n<r;n++)t[n].apply(null,e)},e.prototype.on=function(e){var t=this;return this.listeners.push(e),gt(function(){var n=t.listeners.indexOf(e);n!==-1&&t.listeners.splice(n,1)})},e.prototype.once=function(e){var t=this.on(function(){t(),e.apply(this,arguments)});return t},e}();t.SimpleEventEmitter=wn;var _n=[];Object.freeze(_n);var Sn=[],On=function(){},An=Object.prototype.hasOwnProperty;t.isArrayLike=Lt}),y=b.Reaction,m=b.isObservable,g=b.extras,x=function(){this.listeners=[]};x.prototype.on=function(e){var t=this;return this.listeners.push(e),function(){var n=t.listeners.indexOf(e);n!==-1&&t.listeners.splice(n,1)}},x.prototype.emit=function(e){this.listeners.forEach(function(t){return t(e)})},x.prototype.getTotalListeners=function(){return this.listeners.length},x.prototype.clearListeners=function(){this.listeners=[]};var w=t.findDOMNode,_=!1,S=new WeakMap,O=new x,A=i(function(e){function t(e,t,i){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var s=0;s<a.length;++s)if(!(n[a[s]]||r[a[s]]||i&&i[a[s]]))try{e[a[s]]=t[a[s]]}catch(e){}}return e}var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,propTypes:!0,type:!0},r={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=t,e.exports.default=e.exports}),R=function(e){return function(t,n){return e.forEach(function(e){if(!(e in n)){if(!(e in t))throw new Error('MobX observer: Store "'+e+'" is not available! Make sure it is provided by some Provider');n[e]=t[e]}}),n}},k={Provider:d,inject:l,connect:f,observer:f,trackComponents:s,renderReporter:O,componentByNodeRegistery:S};return k});
ajax/libs/onsen/2.0.0-beta/js/angular-onsenui.js
BenjaminVanRyseghem/cdnjs
/*! angular-onsenui.js for onsenui - v2.0.0-beta - 2015-11-11 */ (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/sliding_menu.tpl', '<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n' + '<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/split_view.tpl', '<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n' + '<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n' + ''); }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @ngdoc object * @name ons * @category util * @description * [ja]Onsen UIで利用できるグローバルなオブジェクトです。このオブジェクトは、AngularJSのスコープから参照することができます。 [/ja] * [en]A global object that's used in Onsen UI. This object can be reached from the AngularJS scope.[/en] */ /** * @ngdoc method * @signature ready(callback) * @description * [ja]アプリの初期化に利用するメソッドです。渡された関数は、Onsen UIの初期化が終了している時点で必ず呼ばれます。[/ja] * [en]Method used to wait for app initialization. The callback will not be executed until Onsen UI has been completely initialized.[/en] * @param {Function} callback * [en]Function that executes after Onsen UI has been initialized.[/en] * [ja]Onsen UIが初期化が完了した後に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature bootstrap([moduleName, [dependencies]]) * @extensionOf angular * @description * [ja]Onsen UIの初期化を行います。Angular.jsのng-app属性を利用すること無しにOnsen UIを読み込んで初期化してくれます。[/ja] * [en]Initialize Onsen UI. Can be used to load Onsen UI without using the <code>ng-app</code> attribute from AngularJS.[/en] * @param {String} [moduleName] * [en]AngularJS module name.[/en] * [ja]Angular.jsでのモジュール名[/ja] * @param {Array} [dependencies] * [en]List of AngularJS module dependencies.[/en] * [ja]依存するAngular.jsのモジュール名の配列[/ja] * @return {Object} * [en]An AngularJS module object.[/en] * [ja]AngularJSのModuleオブジェクトを表します。[/ja] */ /** * @ngdoc method * @signature enableAutoStatusBarFill() * @description * [en]Enable status bar fill feature on iOS7 and above.[/en] * [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を有効にします。[/ja] */ /** * @ngdoc method * @signature disableAutoStatusBarFill() * @description * [en]Disable status bar fill feature on iOS7 and above.[/en] * [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を無効にします。[/ja] */ /** * @ngdoc method * @signature disableAnimations() * @description * [en]Disable all animations. Could be handy for testing and older devices.[/en] * [ja]アニメーションを全て無効にします。テストの際に便利です。[/ja] */ /** * @ngdoc method * @signature enableAnimations() * @description * [en]Enable animations (default).[/en] * [ja]アニメーションを有効にします。[/ja] */ /** * @ngdoc method * @signature findParentComponentUntil(name, [dom]) * @extensionOf angular * @param {String} name * [en]Name of component, i.e. 'ons-page'.[/en] * [ja]コンポーネント名を指定します。例えばons-pageなどを指定します。[/ja] * @param {Object|jqLite|HTMLElement} [dom] * [en]$event, jqLite or HTMLElement object.[/en] * [ja]$eventオブジェクト、jqLiteオブジェクト、HTMLElementオブジェクトのいずれかを指定できます。[/ja] * @return {Object} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find parent component object of <code>dom</code> element.[/en] * [ja]指定されたdom引数の親要素をたどってコンポーネントを検索します。[/ja] */ /** * @ngdoc method * @signature findComponent(selector, [dom]) * @extensionOf angular * @param {String} selector * [en]CSS selector[/en] * [ja]CSSセレクターを指定します。[/ja] * @param {HTMLElement} [dom] * [en]DOM element to search from.[/en] * [ja]検索対象とするDOM要素を指定します。[/ja] * @return {Object} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find component object using CSS selector.[/en] * [ja]CSSセレクタを使ってコンポーネントのオブジェクトを検索します。[/ja] */ /** * @ngdoc method * @signature setDefaultDeviceBackButtonListener(listener) * @param {Function} listener * [en]Function that executes when device back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時に実行される関数オブジェクトを指定します。[/ja] * @description * [en]Set default handler for device back button.[/en] * [ja]デバイスのバックボタンのためのデフォルトのハンドラを設定します。[/ja] */ /** * @ngdoc method * @signature disableDeviceBackButtonHandler() * @description * [en]Disable device back button event handler.[/en] * [ja]デバイスのバックボタンのイベントを受け付けないようにします。[/ja] */ /** * @ngdoc method * @signature enableDeviceBackButtonHandler() * @description * [en]Enable device back button event handler.[/en] * [ja]デバイスのバックボタンのイベントを受け付けるようにします。[/ja] */ /** * @ngdoc method * @signature isReady() * @return {Boolean} * [en]Will be true if Onsen UI is initialized.[/en] * [ja]初期化されているかどうかを返します。[/ja] * @description * [en]Returns true if Onsen UI is initialized.[/en] * [ja]Onsen UIがすでに初期化されているかどうかを返すメソッドです。[/ja] */ /** * @ngdoc method * @signature compile(dom) * @extensionOf angular * @param {HTMLElement} dom * [en]Element to compile.[/en] * [ja]コンパイルする要素を指定します。[/ja] * @description * [en]Compile Onsen UI components.[/en] * [ja]通常のHTMLの要素をOnsen UIのコンポーネントにコンパイルします。[/ja] */ /** * @ngdoc method * @signature isWebView() * @return {Boolean} * [en]Will be true if the app is running in Cordova.[/en] * [ja]Cordovaで実行されている場合にtrueになります。[/ja] * @description * [en]Returns true if running inside Cordova.[/en] * [ja]Cordovaで実行されているかどうかを返すメソッドです。[/ja] */ /** * @ngdoc method * @signature createAlertDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-alert-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the alert dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a alert dialog instance from a template.[/en] * [ja]テンプレートからアラートダイアログのインスタンスを生成します。[/ja] */ /** * @ngdoc method * @signature createDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a dialog instance from a template.[/en] * [ja]テンプレートからダイアログのインスタンスを生成します。[/ja] */ /** * @ngdoc method * @signature createPopover(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the popover component object.[/en] * [ja]ポップオーバーのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a popover instance from a template.[/en] * [ja]テンプレートからポップオーバーのインスタンスを生成します。[/ja] */ /** * @ngdoc method * @signature resolveLoadingPlaceholder(page) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> element.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @description * [en]If no page is defined for the `ons-loading-placeholder` attribute it will wait for this method being called before loading the page.[/en] * [ja]ons-loading-placeholderの属性値としてページが指定されていない場合は、ページロード前に呼ばれるons.resolveLoadingPlaceholder処理が行われるまで表示されません。[/ja] */ (function(ons){ 'use strict'; var module = angular.module('onsen', ['templates-main']); angular.module('onsen.directives', ['onsen']); // for BC // JS Global facade for Onsen UI. initOnsenFacade(); waitOnsenUILoad(); initAngularModule(); function waitOnsenUILoad() { var unlockOnsenUI = ons._readyLock.lock(); module.run(['$compile', '$rootScope', function($compile, $rootScope) { // for initialization hook. if (document.readyState === 'loading' || document.readyState == 'uninitialized') { window.addEventListener('DOMContentLoaded', function() { document.body.appendChild(document.createElement('ons-dummy-for-init')); }); } else if (document.body) { document.body.appendChild(document.createElement('ons-dummy-for-init')); } else { throw new Error('Invalid initialization state.'); } $rootScope.$on('$ons-ready', unlockOnsenUI); }]); } function initAngularModule() { module.value('$onsGlobal', ons); module.run(['$compile', '$rootScope', '$onsen', '$q', function($compile, $rootScope, $onsen, $q) { ons._onsenService = $onsen; ons._qService = $q; $rootScope.ons = window.ons; $rootScope.console = window.console; $rootScope.alert = window.alert; ons.$compile = $compile; }]); } function initOnsenFacade() { ons._onsenService = null; // Object to attach component variables to when using the var="..." attribute. // Can be set to null to avoid polluting the global scope. ons.componentBase = window; /** * Bootstrap this document as a Onsen UI application. * * @param {String} [name] optional name * @param {Array} [deps] optional dependency modules */ ons.bootstrap = function(name, deps) { if (angular.isArray(name)) { deps = name; name = undefined; } if (!name) { name = 'myOnsenApp'; } deps = ['onsen'].concat(angular.isArray(deps) ? deps : []); var module = angular.module(name, deps); var doc = window.document; if (doc.readyState == 'loading' || doc.readyState == 'uninitialized' || doc.readyState == 'interactive') { doc.addEventListener('DOMContentLoaded', function() { angular.bootstrap(doc.documentElement, [name]); }, false); } else if (doc.documentElement) { angular.bootstrap(doc.documentElement, [name]); } else { throw new Error('Invalid state'); } return module; }; /** * @param {String} [name] * @param {Object/jqLite/HTMLElement} dom $event object or jqLite object or HTMLElement object. * @return {Object} */ ons.findParentComponentUntil = function(name, dom) { var element; if (dom instanceof HTMLElement) { element = angular.element(dom); } else if (dom instanceof angular.element) { element = dom; } else if (dom.target) { element = angular.element(dom.target); } return element.inheritedData(name); }; /** * Find view object correspond dom element queried by CSS selector. * * @param {String} selector CSS selector * @param {HTMLElement} [dom] * @return {Object/void} */ ons.findComponent = function(selector, dom) { var target = (dom ? dom : document).querySelector(selector); return target ? angular.element(target).data(target.nodeName.toLowerCase()) || null : null; }; /** * @param {HTMLElement} dom */ ons.compile = function(dom) { if (!ons.$compile) { throw new Error('ons.$compile() is not ready. Wait for initialization with ons.ready().'); } if (!(dom instanceof HTMLElement)) { throw new Error('First argument must be an instance of HTMLElement.'); } var scope = angular.element(dom).scope(); if (!scope) { throw new Error('AngularJS Scope is null. Argument DOM element must be attached in DOM document.'); } ons.$compile(dom)(scope); }; ons._getOnsenService = function() { if (!this._onsenService) { throw new Error('$onsen is not loaded, wait for ons.ready().'); } return this._onsenService; }; /** * @param {String} elementName * @param {Function} lastReady * @return {Function} */ ons._waitDiretiveInit = function(elementName, lastReady) { return function(element, callback) { if (angular.element(element).data(elementName)) { lastReady(element, callback); } else { var listen = function() { lastReady(element, callback); element.removeEventListener(elementName + ':init', listen, false); }; element.addEventListener(elementName + ':init', listen, false); } }; }; /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ ons.createAlertDialog = function(page, options) { options = options || {}; options.link = function(element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createAlertDialogOriginal(page, options).then(function(alertDialog) { return angular.element(alertDialog).data('ons-alert-dialog'); }); }; /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ ons.createDialog = function(page, options) { options = options || {}; options.link = function(element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createDialogOriginal(page, options).then(function(dialog) { return angular.element(dialog).data('ons-dialog'); }); }; /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ ons.createPopover = function(page, options) { options = options || {}; options.link = function(element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createPopoverOriginal(page, options).then(function(popover) { return angular.element(popover).data('ons-popover'); }); }; /** * @param {String} page */ ons.resolveLoadingPlaceholder = function(page) { return ons._resolveLoadingPlaceholderOriginal(page, function(element, done) { ons.compile(element); angular.element(element).scope().$evalAsync(function() { setImmediate(done); }); }); }; ons._setupLoadingPlaceHolders = function() { // Do nothing }; } })(window.ons = window.ons || {}); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('AlertDialogView', ['$onsen', function($onsen) { var AlertDialogView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'getDeviceBackButtonHandler', 'show', 'hide', 'isShown', 'destroy', 'setDisabled', 'isDisabled', 'setCancelable', 'isCancelable' ]); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], [ 'preshow', 'postshow', 'prehide', 'posthide', 'cancel' ], function(detail) { if (detail.alertDialog) { detail.alertDialog = this; } return detail; }.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function() { this.emit('destroy'); this._element.remove(); this._clearDerivingMethods(); this._clearDerivingEvents(); this._scope = this._attrs = this._element = null; } }); MicroEvent.mixin(AlertDialogView); return AlertDialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen') .value('AlertDialogAnimator', ons._internal.AlertDialogAnimator) .value('AndroidAlertDialogAnimator', ons._internal.AndroidAlertDialogAnimator) .value('IOSAlertDialogAnimator', ons._internal.IOSAlertDialogAnimator); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('AnimationChooser', ons._internal.AnimatorFactory); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('CarouselView', ['$onsen', function($onsen) { /** * @class CarouselView */ var CarouselView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], [ 'setSwipeable', 'isSwipeable', 'setAutoScrollRatio', 'getAutoScrollRatio', 'setActiveCarouselItemIndex', 'getActiveCarouselItemIndex', 'next', 'prev', 'setAutoScrollEnabled', 'isAutoScrollEnabled', 'setDisabled', 'isDisabled', 'setOverscrollable', 'isOverscrollable', 'refresh', 'first', 'last' ]); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['refresh', 'postchange', 'overscroll'], function(detail) { if (detail.carousel) { detail.carousel = this; } return detail; }.bind(this)); }, _destroy: function() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(CarouselView); return CarouselView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('DialogView', ['$onsen', function($onsen) { var DialogView = Class.extend({ init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'getDeviceBackButtonHandler', 'show', 'hide', 'isShown', 'destroy' ]); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], [ 'preshow', 'postshow', 'prehide', 'posthide', 'cancel' ], function(detail) { if (detail.dialog) { detail.dialog = this; } return detail; }.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function() { this.emit('destroy'); this._element.remove(); this._clearDerivingMethods(); this._clearDerivingEvents(); this._scope = this._attrs = this._element = null; } }); DialogView.registerAnimator = function(name, Animator) { return window.OnsDialogElement.registerAnimator(name, Animator); }; MicroEvent.mixin(DialogView); return DialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen') .value('DialogAnimator', ons._internal.DialogAnimator) .value('IOSDialogAnimator', ons._internal.IOSDialogAnimator) .value('AndroidDialogAnimator', ons._internal.AndroidDialogAnimator) .value('SlideDialogAnimator', ons._internal.SlideDialogAnimator); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; angular.module('onsen').factory('GenericView', ['$onsen', function($onsen) { var GenericView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs * @param {Object} [options] * @param {Boolean} [options.directiveOnly] * @param {Function} [options.onDestroy] * @param {String} [options.modifierTemplate] */ init: function(scope, element, attrs, options) { var self = this; options = {}; this._element = element; this._scope = scope; this._attrs = attrs; if (options.directiveOnly) { if (!options.modifierTemplate) { throw new Error('options.modifierTemplate is undefined.'); } $onsen.addModifierMethods(this, options.modifierTemplate, element); } else { $onsen.addModifierMethodsForCustomElements(this, element); } $onsen.cleaner.onDestroy(scope, function() { self._events = undefined; $onsen.removeModifierMethods(self); if (options.onDestroy) { options.onDestroy(self); } $onsen.clearComponent({ scope: scope, attrs: attrs, element: element }); self = element = self._element = self._scope = scope = self._attrs = attrs = options = null; }); } }); /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs * @param {Object} options * @param {String} options.viewKey * @param {Boolean} [options.directiveOnly] * @param {Function} [options.onDestroy] * @param {String} [options.modifierTemplate] */ GenericView.register = function(scope, element, attrs, options) { var view = new GenericView(scope, element, attrs, options); if (!options.viewKey) { throw new Error('options.viewKey is required.'); } $onsen.declareVarAttribute(attrs, view); element.data(options.viewKey, view); var destroy = options.onDestroy || angular.noop; options.onDestroy = function(view) { destroy(view); element.data(options.viewKey, null); }; return view; }; MicroEvent.mixin(GenericView); return GenericView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('LazyRepeatView', ['AngularLazyRepeatDelegate', function(AngularLazyRepeatDelegate) { var LazyRepeatView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs, linker) { this._element = element; this._scope = scope; this._attrs = attrs; this._linker = linker; var userDelegate = this._getDelegate(); var internalDelegate = new AngularLazyRepeatDelegate(element[0], userDelegate, element.scope()); this._provider = new ons._internal.LazyRepeatProvider(element[0].parentNode, element[0], internalDelegate); element.remove(); this._injectReloadMethod(userDelegate, this._provider); // Render when number of items change. this._scope.$watch(internalDelegate.countItems.bind(internalDelegate), this._provider._onChange.bind(this._provider)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _injectReloadMethod: function(userDelegate, provider) { var oldReload = userDelegate.reload; if (typeof oldReload === 'function') { userDelegate.reload = function() { oldReload(); provider._onChange(); }.bind(this); } else { userDelegate.reload = function() { provider._onChange(); }.bind(this); } }.bind(this), _getDelegate: function() { var delegate = this._scope.$eval(this._attrs.onsLazyRepeat); if (typeof delegate === 'undefined') { /*jshint evil:true */ delegate = eval(this._attrs.onsLazyRepeat); } return delegate; }, _destroy: function() { this._element = this._scope = this._attrs = this._linker = null; } }); return LazyRepeatView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; angular.module('onsen').factory('AngularLazyRepeatDelegate', ['$compile', function($compile) { var AngularLazyRepeatDelegate = function() { AngularLazyRepeatDelegate.prototype.init.apply(this, arguments); }; AngularLazyRepeatDelegate.prototype = Object.create(ons._internal.LazyRepeatDelegate.prototype); angular.extend(AngularLazyRepeatDelegate.prototype, { /** * @param {Element} templateElement * @param {Object} userDelegate * @param {Scope} parentScope */ init: function(templateElement, userDelegate, parentScope) { this._templateElement = templateElement.cloneNode(true); this._userDelegate = userDelegate; this._parentScope = parentScope; this._removeLazyRepeatDirective(); this._linker = $compile(this._templateElement.cloneNode(true)); }, /** * @return {Boolean} */ _usingBinding: function() { if (this._userDelegate.configureItemScope) { return true; } if (this._userDelegate.createItemContent) { return false; } throw new Error('`lazy-repeat` delegate object is vague.'); }, _removeLazyRepeatDirective: function() { this._templateElement.removeAttribute('ons-lazy-repeat'); this._templateElement.removeAttribute('ons:lazy:repeat'); this._templateElement.removeAttribute('ons_lazy_repeat'); this._templateElement.removeAttribute('data-ons-lazy-repeat'); this._templateElement.removeAttribute('x-ons-lazy-repeat'); }, prepareItem: function(index, done) { var scope = this._parentScope.$new(); this._addSpecialProperties(index, scope); if (this._usingBinding()) { this._userDelegate.configureItemScope(index, scope); } this._linker(scope, function(cloned) { cloned[0].style.display = 'none'; if (!this._usingBinding()) { var contentElement = this._userDelegate.createItemContent(index, null); cloned.append(contentElement); $compile(cloned[0].firstChild)(scope); } done({ element: cloned[0], scope: scope }); scope.$evalAsync(function() { cloned[0].style.display = 'block'; }); }.bind(this)); }, /** * @param {Number} index * @param {Object} scope */ _addSpecialProperties: function(index, scope) { scope.$index = index; scope.$first = index === 0; scope.$last = index === this.countItems() - 1; scope.$middle = !scope.$first && !scope.$last; scope.$even = index % 2 === 0; scope.$odd = !scope.$even; }, countItems: function() { return this._userDelegate.countItems(); }, updateItem: function(index, item) { if (this._usingBinding()) { item.scope.$evalAsync(function() { this._userDelegate.configureItemScope(index, item.scope); }.bind(this)); } }, /** * @param {Number} index * @param {Object} item * @param {Object} item.scope * @param {Element} item.element */ destroyItem: function(index, item) { if (this._usingBinding()) { if (this._userDelegate.destroyItemScope instanceof Function) { this._userDelegate.destroyItemScope(index, item.scope); } } else { if (this._userDelegate.destroyItemContent instanceof Function) { this._userDelegate.destroyItemContent(index, item.element); } } item.scope.$destroy(); }, destroy: function() { this._userDelegate = this._templateElement = this._scope = null; }, calculateItemHeight: function(index) { return this._userDelegate.calculateItemHeight(index); } }); return AngularLazyRepeatDelegate; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.value('ModalAnimator', ons._internal.ModalAnimator); module.value('FadeModalAnimator', ons._internal.FadeModalAnimator); module.factory('ModalView', ['$onsen', '$parse', function($onsen, $parse) { var ModalView = Class.extend({ _element: undefined, _scope: undefined, init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._scope.$on('$destroy', this._destroy.bind(this)); element[0]._animatorFactory.setAnimationOptions($parse(attrs.animationOptions)()); }, getDeviceBackButtonHandler: function() { return this._element[0].getDeviceBackButtonHandler(); }, setDeviceBackButtonHandler: function(callback) { this._element[0].setDeviceBackButtonHandler(callback); }, show: function(options) { return this._element[0].show(options); }, hide: function(options) { return this._element[0].hide(options); }, toggle: function(options) { return this._element[0].toggle(options); }, _destroy: function() { this.emit('destroy', {page: this}); this._events = this._element = this._scope = null; } }); ModalView.registerAnimator = function(name, Animator) { return window.OnsModalElement.registerAnimator(name, Animator); }; MicroEvent.mixin(ModalView); return ModalView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('NavigatorView', ['$http', '$parse', '$compile', '$onsen', '$timeout', 'AnimationChooser', 'SimpleSlideTransitionAnimator', 'NavigatorTransitionAnimator', 'LiftTransitionAnimator', 'NullTransitionAnimator', 'IOSSlideTransitionAnimator', 'FadeTransitionAnimator', function($http, $parse, $compile, $onsen, $timeout, AnimationChooser, SimpleSlideTransitionAnimator, NavigatorTransitionAnimator, LiftTransitionAnimator, NullTransitionAnimator, IOSSlideTransitionAnimator, FadeTransitionAnimator) { /** * Manages the page navigation backed by page stack. * * @class NavigatorView */ var NavigatorView = Class.extend({ /** * @member {jqLite} Object */ _element: undefined, /** * @member {Object} Object */ _attrs: undefined, /** * @member {Object} */ _scope: undefined, /** * @param {Object} scope * @param {jqLite} element jqLite Object to manage with navigator * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element || angular.element(window.document.body); this._scope = scope || this._element.scope(); this._attrs = attrs; this._previousPageScope = null; this._boundOnPrepop = this._onPrepop.bind(this); this._boundOnPostpop = this._onPostpop.bind(this); this._element.on('prepop', this._boundOnPrepop); this._element.on('postpop', this._boundOnPostpop); this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], [ 'prepush', 'postpush', 'prepop', 'postpop', 'init', 'show', 'hide', 'destroy' ], function(detail) { if (detail.navigator) { detail.navigator = this; } return detail; }.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], [ 'insertPage', 'pushPage', 'bringPageTop', 'getDeviceBackButtonHandler', 'popPage', 'replacePage', 'resetToPage', 'getCurrentPage', 'canPopPage' ]); }, _onPrepop: function(event) { var pages = event.detail.navigator.pages; angular.element(pages[pages.length - 2].element).scope().$evalAsync(); this._previousPageScope = angular.element(pages[pages.length - 1].element).scope(); }, _onPostpop: function(event) { this._previousPageScope.$destroy(); this._previoousPageScope = null; }, _compileAndLink: function(pageElement, callback) { var link = $compile(pageElement); var pageScope = this._createPageScope(); link(pageScope); pageScope.$evalAsync(function() { callback(pageElement); }); }, _destroy: function() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element.off('prepop', this._boundOnPrepop); this._element.off('postpop', this._boundOnPostpop); this._element = this._scope = this._attrs = null; }, _createPageScope: function() { return this._scope.$new(); }, /** * Retrieve the entire page stages of the navigator. * * @return {Array} */ getPages: function() { return this._element[0].pages; } }); MicroEvent.mixin(NavigatorView); Object.defineProperty(NavigatorView.prototype, 'pages', { get: function () { return this.getPages(); }, set: function() { throw new Error(); } }); return NavigatorView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen') .value('NavigatorTransitionAnimator', ons._internal.NavigatorTransitionAnimator) .value('FadeTransitionAnimator', ons._internal.FadeNavigatorTransitionAnimator) .value('IOSSlideTransitionAnimator', ons._internal.IOSSlideNavigatorTransitionAnimator) .value('LiftTransitionAnimator', ons._internal.LiftNavigatorTransitionAnimator) .value('NullTransitionAnimator', ons._internal.NavigatorTransitionAnimator) .value('SimpleSlideTransitionAnimator', ons._internal.SimpleSlideNavigatorTransitionAnimator); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('OverlaySlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var OverlaySlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _element: false, _menuPage: false, _mainPage: false, _width: false, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { options = options || {}; this._width = options.width || '90%'; this._isRight = !!options.isRight; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; menuPage.css('box-shadow', '0px 0 10px 0px rgba(0, 0, 0, 0.2)'); menuPage.css({ width: options.width, display: 'none', zIndex: 2 }); // Fix for transparent menu page on iOS8. menuPage.css('-webkit-transform', 'translate3d(0px, 0px, 0px)'); mainPage.css({zIndex: 1}); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none', zIndex: 0 }); element.prepend(this._blackMask); }, /** * @param {Object} options * @param {String} options.width */ onResized: function(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); animit(this._menuPage[0]).queue(menuStyle).play(); } }, /** */ destroy: function() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); var mainPageStyle = this._generateMainPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue(mainPageStyle, { duration: duration, timing: this.timing }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .wait(delay) .queue(menuStyle, { duration: duration, timing: this.timing }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._blackMask.css({display: 'block'}); var menuPageStyle = this._generateMenuPageStyle(0); var mainPageStyle = this._generateMainPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue(mainPageStyle, { duration: duration, timing: this.timing }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .wait(delay) .queue(menuPageStyle, { duration: duration, timing: this.timing }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); this._blackMask.css({display: 'block'}); var menuPageStyle = this._generateMenuPageStyle(Math.min(options.maxDistance, options.distance)); var mainPageStyle = this._generateMainPageStyle(Math.min(options.maxDistance, options.distance)); delete mainPageStyle.opacity; animit(this._menuPage[0]) .queue(menuPageStyle) .play(); if (Object.keys(mainPageStyle).length > 0) { animit(this._mainPage[0]) .queue(mainPageStyle) .play(); } }, _generateMenuPageStyle: function(distance) { var x = this._isRight ? -distance : distance; var transform = 'translate3d(' + x + 'px, 0, 0)'; return { transform: transform, 'box-shadow': distance === 0 ? 'none' : '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }; }, _generateMainPageStyle: function(distance) { var max = this._menuPage[0].clientWidth; var opacity = 1 - (0.1 * distance / max); return { opacity: opacity }; }, copy: function() { return new OverlaySlidingMenuAnimator(); } }); return OverlaySlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('PageView', ['$onsen', '$parse', function($onsen, $parse) { var PageView = Class.extend({ _nullElement : window.document.createElement('div'), init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._clearListener = scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); this._userDeviceBackButtonListener = angular.noop; if (this._attrs.ngDeviceBackbutton || this._attrs.onDeviceBackbutton) { this._element[0].setDeviceBackButtonHandler(this._onDeviceBackButton.bind(this)); } }, _onDeviceBackButton: function($event) { this._userDeviceBackButtonListener($event); // ng-device-backbutton if (this._attrs.ngDeviceBackbutton) { $parse(this._attrs.ngDeviceBackbutton)(this._scope, {$event: $event}); } // on-device-backbutton /* jshint ignore:start */ if (this._attrs.onDeviceBackbutton) { var lastEvent = window.$event; window.$event = $event; new Function(this._attrs.onDeviceBackbutton)(); window.$event = lastEvent; } /* jshint ignore:end */ }, /** * @param {Function} callback */ setDeviceBackButtonHandler: function(callback) { this._userDeviceBackButtonListener = callback; }, /** * @return {Object/null} */ getDeviceBackButtonHandler: function() { return this._element[0].getDeviceBackButtonHandler(); }, _destroy: function() { this._element[0]._destroy(); this._clearDerivingEvents(); this._element = null; this._nullElement = null; this._scope = null; this._clearListener(); } }); MicroEvent.mixin(PageView); return PageView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; angular.module('onsen').factory('PopoverView', ['$onsen', function($onsen) { var PopoverView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'show', 'hide', 'isShown', 'setCancelable', 'destroy' ]); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], [ 'preshow', 'postshow', 'prehide', 'posthide' ], function(detail) { if (detail.popover) { detail.popover = this; } return detail; }.bind(this)); }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._clearDerivingEvents(); this._element.remove(); this._element = this._scope = null; } }); MicroEvent.mixin(PopoverView); return PopoverView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen') .value('PopoverAnimator', ons._internal.PopoverAnimator) .value('FadePopoverAnimator', ons._internal.FadePopoverAnimator); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('PullHookView', ['$onsen', '$parse', function($onsen, $parse) { var PullHookView = Class.extend({ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'getHeight', 'setHeight', 'setThresholdHeight', 'getThresholdHeight', 'getCurrentState', 'getPullDistance', 'isDisabled', 'setDisabled' ]); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], [ 'changestate', ], function(detail) { if (detail.pullHook) { detail.pullHook = this; } return detail; }.bind(this)); this.on('changestate', function(event) { this._scope.$evalAsync(); }.bind(this)); this._boundOnAction = this._onAction.bind(this); this._element[0].setActionCallback(this._boundOnAction); this._scope.$on('$destroy', this._destroy.bind(this)); }, _onAction: function(done) { if (this._attrs.ngAction) { this._scope.$eval(this._attrs.ngAction, {$done: done}); } else if (this._attrs.onAction) { /*jshint evil:true */ eval(this._attrs.onAction); } }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._clearDerivingEvents(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(PullHookView); return PullHookView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('PushSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var PushSlidingMenuAnimator = SlidingMenuAnimator.extend({ _isRight: false, _element: undefined, _menuPage: undefined, _mainPage: undefined, _width: undefined, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { options = options || {}; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; menuPage.css({ width: options.width, display: 'none' }); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } }, /** * @param {Object} options * @param {String} options.width * @param {Object} options.isRight */ onResized: function(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var mainPageTransform = this._generateAbovePageTransform(max); var menuPageStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({transform: mainPageTransform}).play(); animit(this._menuPage[0]).queue(menuPageStyle).play(); } }, /** */ destroy: function() { this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .wait(delay) .queue(behindStyle, { duration: duration, timing: this.timing }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }) .queue({ transform: 'translate3d(0, 0, 0)' }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .wait(delay) .queue(behindStyle, { duration: duration, timing: this.timing }) .queue(function(done) { done(); }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); animit(this._mainPage[0]) .queue({transform: aboveTransform}) .play(); animit(this._menuPage[0]) .queue(behindStyle) .play(); }, _generateAbovePageTransform: function(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function(distance) { var behindX = this._isRight ? -distance : distance; var behindTransform = 'translate3d(' + behindX + 'px, 0, 0)'; return { transform: behindTransform }; }, copy: function() { return new PushSlidingMenuAnimator(); } }); return PushSlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('RevealSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var RevealSlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _menuPage: undefined, _element: undefined, _mainPage: undefined, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { this._element = element; this._menuPage = menuPage; this._mainPage = mainPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; mainPage.css({ boxShadow: '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }); menuPage.css({ width: options.width, opacity: 0.9, display: 'none' }); if (this._isRight) { menuPage.css({ right: '0px', left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '0px' }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none' }); element.prepend(this._blackMask); // Dirty fix for broken rendering bug on android 4.x. animit(mainPage[0]).queue({transform: 'translate3d(0, 0, 0)'}).play(); }, /** * @param {Object} options * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function(options) { this._width = options.width; this._menuPage.css('width', this._width); if (options.isOpened) { var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({transform: aboveTransform}).play(); animit(this._menuPage[0]).queue(behindStyle).play(); } }, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage */ destroy: function() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } if (this._mainPage) { this._mainPage.attr('style', ''); } if (this._menuPage) { this._menuPage.attr('style', ''); } this._mainPage = this._menuPage = this._element = undefined; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .wait(delay) .queue(behindStyle, { duration: duration, timing: this.timing }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .wait(delay) .queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }) .queue({ transform: 'translate3d(0, 0, 0)' }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .wait(delay) .queue(behindStyle, { duration: duration, timing: this.timing }) .queue(function(done) { done(); }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); delete behindStyle.opacity; animit(this._mainPage[0]) .queue({transform: aboveTransform}) .play(); animit(this._menuPage[0]) .queue(behindStyle) .play(); }, _generateAbovePageTransform: function(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function(distance) { var max = this._menuPage[0].getBoundingClientRect().width; var behindDistance = (distance - max) / max * 10; behindDistance = isNaN(behindDistance) ? 0 : Math.max(Math.min(behindDistance, 0), -10); var behindX = this._isRight ? -behindDistance : behindDistance; var behindTransform = 'translate3d(' + behindX + '%, 0, 0)'; var opacity = 1 + behindDistance / 100; return { transform: behindTransform, opacity: opacity }; }, copy: function() { return new RevealSlidingMenuAnimator(); } }); return RevealSlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); var SlidingMenuViewModel = Class.extend({ /** * @member Number */ _distance: 0, /** * @member Number */ _maxDistance: undefined, /** * @param {Object} options * @param {Number} maxDistance */ init: function(options) { if (!angular.isNumber(options.maxDistance)) { throw new Error('options.maxDistance must be number'); } this.setMaxDistance(options.maxDistance); }, /** * @param {Number} maxDistance */ setMaxDistance: function(maxDistance) { if (maxDistance <= 0) { throw new Error('maxDistance must be greater then zero.'); } if (this.isOpened()) { this._distance = maxDistance; } this._maxDistance = maxDistance; }, /** * @return {Boolean} */ shouldOpen: function() { return !this.isOpened() && this._distance >= this._maxDistance / 2; }, /** * @return {Boolean} */ shouldClose: function() { return !this.isClosed() && this._distance < this._maxDistance / 2; }, openOrClose: function(options) { if (this.shouldOpen()) { this.open(options); } else if (this.shouldClose()) { this.close(options); } }, close: function(options) { var callback = options.callback || function() {}; if (!this.isClosed()) { this._distance = 0; this.emit('close', options); } else { callback(); } }, open: function(options) { var callback = options.callback || function() {}; if (!this.isOpened()) { this._distance = this._maxDistance; this.emit('open', options); } else { callback(); } }, /** * @return {Boolean} */ isClosed: function() { return this._distance === 0; }, /** * @return {Boolean} */ isOpened: function() { return this._distance === this._maxDistance; }, /** * @return {Number} */ getX: function() { return this._distance; }, /** * @return {Number} */ getMaxDistance: function() { return this._maxDistance; }, /** * @param {Number} x */ translate: function(x) { this._distance = Math.max(1, Math.min(this._maxDistance - 1, x)); var options = { distance: this._distance, maxDistance: this._maxDistance }; this.emit('translate', options); }, toggle: function() { if (this.isClosed()) { this.open(); } else { this.close(); } } }); MicroEvent.mixin(SlidingMenuViewModel); module.factory('SlidingMenuView', ['$onsen', '$compile', '$parse', 'AnimationChooser', 'SlidingMenuAnimator', 'RevealSlidingMenuAnimator', 'PushSlidingMenuAnimator', 'OverlaySlidingMenuAnimator', function($onsen, $compile, $parse, AnimationChooser, SlidingMenuAnimator, RevealSlidingMenuAnimator, PushSlidingMenuAnimator, OverlaySlidingMenuAnimator) { var SlidingMenuView = Class.extend({ _scope: undefined, _attrs: undefined, _element: undefined, _menuPage: undefined, _mainPage: undefined, _doorLock: undefined, _isRightMenu: false, init: function(scope, element, attrs) { this._scope = scope; this._attrs = attrs; this._element = element; this._menuPage = angular.element(element[0].querySelector('.onsen-sliding-menu__menu')); this._mainPage = angular.element(element[0].querySelector('.onsen-sliding-menu__main')); this._doorLock = new DoorLock(); this._isRightMenu = attrs.side === 'right'; // Close menu on tap event. this._mainPageGestureDetector = new ons.GestureDetector(this._mainPage[0]); this._boundOnTap = this._onTap.bind(this); var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic = new SlidingMenuViewModel({maxDistance: Math.max(maxDistance, 1)}); this._logic.on('translate', this._translate.bind(this)); this._logic.on('open', function(options) { this._open(options); }.bind(this)); this._logic.on('close', function(options) { this._close(options); }.bind(this)); attrs.$observe('maxSlideDistance', this._onMaxSlideDistanceChanged.bind(this)); attrs.$observe('swipeable', this._onSwipeableChanged.bind(this)); this._boundOnWindowResize = this._onWindowResize.bind(this); window.addEventListener('resize', this._boundOnWindowResize); this._boundHandleEvent = this._handleEvent.bind(this); this._bindEvents(); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.menuPage) { this.setMenuPage(attrs.menuPage); } this._deviceBackButtonHandler = ons._deviceBackButtonDispatcher.createHandler(this._element[0], this._onDeviceBackButton.bind(this)); var unlock = this._doorLock.lock(); window.setTimeout(function() { var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic.setMaxDistance(maxDistance); this._menuPage.css({opacity: 1}); var animationChooser = new AnimationChooser({ animators: SlidingMenuView._animatorDict, baseClass: SlidingMenuAnimator, baseClassName: 'SlidingMenuAnimator', defaultAnimation: attrs.type, defaultAnimationOptions: $parse(attrs.animationOptions)() }); this._animator = animationChooser.newAnimator(); this._animator.setup( this._element, this._mainPage, this._menuPage, { isRight: this._isRightMenu, width: this._attrs.maxSlideDistance || '90%' } ); unlock(); }.bind(this), 400); scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); if (!attrs.swipeable) { this.setSwipeable(true); } }, getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler; }, _onDeviceBackButton: function(event) { if (this.isMenuOpened()) { this.closeMenu(); } else { event.callParentHandler(); } }, _onTap: function() { if (this.isMenuOpened()) { this.closeMenu(); } }, _refreshMenuPageWidth: function() { var width = ('maxSlideDistance' in this._attrs) ? this._attrs.maxSlideDistance : '90%'; if (this._animator) { this._animator.onResized({ isOpened: this._logic.isOpened(), width: width }); } }, _destroy: function() { this.emit('destroy'); this._clearDerivingEvents(); this._deviceBackButtonHandler.destroy(); window.removeEventListener('resize', this._boundOnWindowResize); this._mainPageGestureDetector.off('tap', this._boundOnTap); this._element = this._scope = this._attrs = null; }, _onSwipeableChanged: function(swipeable) { swipeable = swipeable === '' || swipeable === undefined || swipeable == 'true'; this.setSwipeable(swipeable); }, /** * @param {Boolean} enabled */ setSwipeable: function(enabled) { if (enabled) { this._activateGestureDetector(); } else { this._deactivateGestureDetector(); } }, _onWindowResize: function() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, _onMaxSlideDistanceChanged: function() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, /** * @return {Number} */ _normalizeMaxSlideDistanceAttr: function() { var maxDistance = this._attrs.maxSlideDistance; if (!('maxSlideDistance' in this._attrs)) { maxDistance = 0.9 * this._mainPage[0].clientWidth; } else if (typeof maxDistance == 'string') { if (maxDistance.indexOf('px', maxDistance.length - 2) !== -1) { maxDistance = parseInt(maxDistance.replace('px', ''), 10); } else if (maxDistance.indexOf('%', maxDistance.length - 1) > 0) { maxDistance = maxDistance.replace('%', ''); maxDistance = parseFloat(maxDistance) / 100 * this._mainPage[0].clientWidth; } } else { throw new Error('invalid state'); } return maxDistance; }, _recalculateMAX: function() { var maxDistance = this._normalizeMaxSlideDistanceAttr(); if (maxDistance) { this._logic.setMaxDistance(parseInt(maxDistance, 10)); } }, _activateGestureDetector: function(){ this._gestureDetector.on('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _deactivateGestureDetector: function(){ this._gestureDetector.off('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _bindEvents: function() { this._gestureDetector = new ons.GestureDetector(this._element[0], { dragMinDistance: 1 }); }, _appendMainPage: function(pageUrl, templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._mainPage.append(pageContent); if (this._currentPageElement) { this._currentPageElement.remove(); this._currentPageScope.$destroy(); } link(pageScope); this._currentPageElement = pageContent; this._currentPageScope = pageScope; this._currentPageUrl = pageUrl; this._currentPageElement[0]._show(); }, /** * @param {String} */ _appendMenuPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._menuPage.append(pageContent); if (this._currentMenuPageScope) { this._currentMenuPageScope.$destroy(); this._currentMenuPageElement.remove(); } link(pageScope); this._currentMenuPageElement = pageContent; this._currentMenuPageScope = pageScope; }, /** * @param {String} page * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMenuPage: function(page, options) { if (page) { options = options || {}; options.callback = options.callback || function() {}; var self = this; $onsen.getPageHTMLAsync(page).then(function(html) { self._appendMenuPage(angular.element(html)); if (options.closeMenu) { self.close(); } options.callback(); }, function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} pageUrl * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMainPage: function(pageUrl, options) { options = options || {}; options.callback = options.callback || function() {}; var done = function() { if (options.closeMenu) { this.close(); } options.callback(); }.bind(this); if (this.currentPageUrl === pageUrl) { done(); return; } if (pageUrl) { var self = this; $onsen.getPageHTMLAsync(pageUrl).then(function(html) { self._appendMainPage(pageUrl, html); done(); }, function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _handleEvent: function(event) { if (this._doorLock.isLocked()) { return; } if (this._isInsideIgnoredElement(event.target)){ this._deactivateGestureDetector(); } switch (event.type) { case 'dragleft': case 'dragright': if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } event.gesture.preventDefault(); var deltaX = event.gesture.deltaX; var deltaDistance = this._isRightMenu ? -deltaX : deltaX; var startEvent = event.gesture.startEvent; if (!('isOpened' in startEvent)) { startEvent.isOpened = this._logic.isOpened(); } if (deltaDistance < 0 && this._logic.isClosed()) { break; } if (deltaDistance > 0 && this._logic.isOpened()) { break; } var distance = startEvent.isOpened ? deltaDistance + this._logic.getMaxDistance() : deltaDistance; this._logic.translate(distance); break; case 'swipeleft': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.open(); } else { this.close(); } event.gesture.stopDetect(); break; case 'swiperight': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.close(); } else { this.open(); } event.gesture.stopDetect(); break; case 'release': this._lastDistance = null; if (this._logic.shouldOpen()) { this.open(); } else if (this._logic.shouldClose()) { this.close(); } break; } }, /** * @param {jqLite} element * @return {Boolean} */ _isInsideIgnoredElement: function(element) { do { if (element.getAttribute && element.getAttribute('sliding-menu-ignore')) { return true; } element = element.parentNode; } while (element); return false; }, _isInsideSwipeTargetArea: function(event) { var x = event.gesture.center.pageX; if (!('_swipeTargetWidth' in event.gesture.startEvent)) { event.gesture.startEvent._swipeTargetWidth = this._getSwipeTargetWidth(); } var targetWidth = event.gesture.startEvent._swipeTargetWidth; return this._isRightMenu ? this._mainPage[0].clientWidth - x < targetWidth : x < targetWidth; }, _getSwipeTargetWidth: function() { var targetWidth = this._attrs.swipeTargetWidth; if (typeof targetWidth == 'string') { targetWidth = targetWidth.replace('px', ''); } var width = parseInt(targetWidth, 10); if (width < 0 || !targetWidth) { return this._mainPage[0].clientWidth; } else { return width; } }, closeMenu: function() { return this.close.apply(this, arguments); }, /** * Close sliding-menu page. * * @param {Object} options */ close: function(options) { options = options || {}; options = typeof options == 'function' ? {callback: options} : options; if (!this._logic.isClosed()) { this.emit('preclose', { slidingMenu: this }); this._doorLock.waitUnlock(function() { this._logic.close(options); }.bind(this)); } }, _close: function(options) { var callback = options.callback || function() {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.closeMenu(function() { unlock(); this._mainPage.children().css('pointer-events', ''); this._mainPageGestureDetector.off('tap', this._boundOnTap); this.emit('postclose', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ openMenu: function() { return this.open.apply(this, arguments); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ open: function(options) { options = options || {}; options = typeof options == 'function' ? {callback: options} : options; this.emit('preopen', { slidingMenu: this }); this._doorLock.waitUnlock(function() { this._logic.open(options); }.bind(this)); }, _open: function(options) { var callback = options.callback || function() {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.openMenu(function() { unlock(); this._mainPage.children().css('pointer-events', 'none'); this._mainPageGestureDetector.on('tap', this._boundOnTap); this.emit('postopen', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Toggle sliding-menu page. * @param {Object} [options] * @param {Function} [options.callback] */ toggle: function(options) { if (this._logic.isClosed()) { this.open(options); } else { this.close(options); } }, /** * Toggle sliding-menu page. */ toggleMenu: function() { return this.toggle.apply(this, arguments); }, /** * @return {Boolean} */ isMenuOpened: function() { return this._logic.isOpened(); }, /** * @param {Object} event */ _translate: function(event) { this._animator.translateMenu(event); } }); // Preset sliding menu animators. SlidingMenuView._animatorDict = { 'default': RevealSlidingMenuAnimator, 'overlay': OverlaySlidingMenuAnimator, 'reveal': RevealSlidingMenuAnimator, 'push': PushSlidingMenuAnimator }; /** * @param {String} name * @param {Function} Animator */ SlidingMenuView.registerAnimator = function(name, Animator) { if (!(Animator.prototype instanceof SlidingMenuAnimator)) { throw new Error('"Animator" param must inherit SlidingMenuAnimator'); } this._animatorDict[name] = Animator; }; MicroEvent.mixin(SlidingMenuView); return SlidingMenuView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('SlidingMenuAnimator', function() { return Class.extend({ delay: 0, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)', /** * @param {Object} options * @param {String} options.timing * @param {Number} options.duration * @param {Number} options.delay */ init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; this.delay = options.delay !== undefined ? options.delay : this.delay; }, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { }, /** * @param {Object} options * @param {Boolean} options.isRight * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function(options) { }, /** * @param {Function} callback */ openMenu: function(callback) { }, /** * @param {Function} callback */ closeClose: function(callback) { }, /** */ destroy: function() { }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(mainPage, menuPage, options) { }, /** * @return {SlidingMenuAnimator} */ copy: function() { throw new Error('Override copy method.'); } }); }); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('SplitView', ['$compile', 'RevealSlidingMenuAnimator', '$onsen', '$onsGlobal', function($compile, RevealSlidingMenuAnimator, $onsen, $onsGlobal) { var SPLIT_MODE = 0; var COLLAPSE_MODE = 1; var MAIN_PAGE_RATIO = 0.9; var SplitView = Class.extend({ init: function(scope, element, attrs) { element.addClass('onsen-sliding-menu'); this._element = element; this._scope = scope; this._attrs = attrs; this._mainPage = angular.element(element[0].querySelector('.onsen-split-view__main')); this._secondaryPage = angular.element(element[0].querySelector('.onsen-split-view__secondary')); this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; this._mode = SPLIT_MODE; this._doorLock = new DoorLock(); this._doSplit = false; this._doCollapse = false; $onsGlobal.orientation.on('change', this._onResize.bind(this)); this._animator = new RevealSlidingMenuAnimator(); this._element.css('display', 'none'); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.secondaryPage) { this.setSecondaryPage(attrs.secondaryPage); } var unlock = this._doorLock.lock(); this._considerChangingCollapse(); this._setSize(); setTimeout(function() { this._element.css('display', 'block'); unlock(); }.bind(this), 1000 / 60 * 2); scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); }, /** * @param {String} templateHTML */ _appendSecondPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._secondaryPage.append(pageContent); if (this._currentSecondaryPageElement) { this._currentSecondaryPageElement.remove(); this._currentSecondaryPageScope.$destroy(); } this._currentSecondaryPageElement = pageContent; this._currentSecondaryPageScope = pageScope; }, /** * @param {String} templateHTML */ _appendMainPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._mainPage.append(pageContent); if (this._currentPage) { this._currentPageScope.$destroy(); } this._currentPage = pageContent; this._currentPageScope = pageScope; this._currentPage[0]._show(); }, /** * @param {String} page */ setSecondaryPage : function(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function(html) { this._appendSecondPage(angular.element(html.trim())); }.bind(this), function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} page */ setMainPage : function(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function(html) { this._appendMainPage(angular.element(html.trim())); }.bind(this), function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _onResize: function() { var lastMode = this._mode; this._considerChangingCollapse(); if (lastMode === COLLAPSE_MODE && this._mode === COLLAPSE_MODE) { this._animator.onResized({ isOpened: false, width: '90%' }); } this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; }, _considerChangingCollapse: function() { var should = this._shouldCollapse(); if (should && this._mode !== COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doSplit) { this._activateSplitMode(); } else { this._activateCollapseMode(); } } else if (!should && this._mode === COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doCollapse) { this._activateCollapseMode(); } else { this._activateSplitMode(); } } this._doCollapse = this._doSplit = false; }, update: function() { this._fireUpdateEvent(); var should = this._shouldCollapse(); if (this._doSplit) { this._activateSplitMode(); } else if (this._doCollapse) { this._activateCollapseMode(); } else if (should) { this._activateCollapseMode(); } else if (!should) { this._activateSplitMode(); } this._doSplit = this._doCollapse = false; }, _getOrientation: function() { if ($onsGlobal.orientation.isPortrait()) { return 'portrait'; } else { return 'landscape'; } }, getCurrentMode: function() { if (this._mode === COLLAPSE_MODE) { return 'collapse'; } else { return 'split'; } }, _shouldCollapse: function() { var c = 'portrait'; if (typeof this._attrs.collapse === 'string') { c = this._attrs.collapse.trim(); } if (c == 'portrait') { return $onsGlobal.orientation.isPortrait(); } else if (c == 'landscape') { return $onsGlobal.orientation.isLandscape(); } else if (c.substr(0,5) == 'width') { var num = c.split(' ')[1]; if (num.indexOf('px') >= 0) { num = num.substr(0,num.length-2); } var width = window.innerWidth; return isNumber(num) && width < num; } else { var mq = window.matchMedia(c); return mq.matches; } }, _setSize: function() { if (this._mode === SPLIT_MODE) { if (!this._attrs.mainPageWidth) { this._attrs.mainPageWidth = '70'; } var secondarySize = 100 - this._attrs.mainPageWidth.replace('%', ''); this._secondaryPage.css({ width: secondarySize + '%', opacity: 1 }); this._mainPage.css({ width: this._attrs.mainPageWidth + '%' }); this._mainPage.css('left', secondarySize + '%'); } }, _fireEvent: function(name) { this.emit(name, { splitView: this, width: window.innerWidth, orientation: this._getOrientation() }); }, _fireUpdateEvent: function() { var that = this; this.emit('update', { splitView: this, shouldCollapse: this._shouldCollapse(), currentMode: this.getCurrentMode(), split: function() { that._doSplit = true; that._doCollapse = false; }, collapse: function() { that._doSplit = false; that._doCollapse = true; }, width: window.innerWidth, orientation: this._getOrientation() }); }, _activateCollapseMode: function() { if (this._mode !== COLLAPSE_MODE) { this._fireEvent('precollapse'); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = COLLAPSE_MODE; this._animator.setup( this._element, this._mainPage, this._secondaryPage, {isRight: false, width: '90%'} ); this._fireEvent('postcollapse'); } }, _activateSplitMode: function() { if (this._mode !== SPLIT_MODE) { this._fireEvent('presplit'); this._animator.destroy(); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = SPLIT_MODE; this._setSize(); this._fireEvent('postsplit'); } }, _destroy: function() { this.emit('destroy'); this._clearDerivingEvents(); this._element = null; this._scope = null; } }); function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } MicroEvent.mixin(SplitView); return SplitView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; angular.module('onsen').factory('SplitterContent', ['$onsen', '$compile', function($onsen, $compile) { var SplitterContent = Class.extend({ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'load' ]); scope.$on('$destroy', this._destroy.bind(this)); }, _link: function(fragment, done) { var link = $compile(fragment); var pageScope = this._createPageScope(); link(pageScope); pageScope.$evalAsync(function() { done(fragment); }); }, _createPageScope: function() { return this._scope.$new(); }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(SplitterContent); Object.defineProperty(SplitterContent.prototype, 'page', { get: function () { return this._element[0].page; }, set: function() { throw new Error(); } }); return SplitterContent; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; angular.module('onsen').factory('SplitterSide', ['$onsen', '$compile', function($onsen, $compile) { var SplitterSide = Class.extend({ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'isSwipeable', 'getCurrentMode', 'isOpened', 'open', 'close', 'toggle', 'load', ]); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], [ 'modechange', 'preopen', 'preclose', 'postopen', 'postclose' ], function(detail) { if (detail.side) { detail.side = this; } return detail; }.bind(this)); scope.$on('$destroy', this._destroy.bind(this)); }, _link: function(fragment, done) { var link = $compile(fragment); var pageScope = this._createPageScope(); link(pageScope); pageScope.$evalAsync(function() { done(fragment); }); }, _createPageScope: function() { return this._scope.$new(); }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._clearDerivingEvents(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(SplitterSide); Object.defineProperty(SplitterSide.prototype, 'page', { get: function () { return this._element[0].page; }, set: function() { throw new Error(); } }); return SplitterSide; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; angular.module('onsen').factory('Splitter', ['$onsen', function($onsen) { var Splitter = Class.extend({ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], [ 'getDeviceBackButtonHandler', 'openRight', 'openLeft', 'closeRight', 'closeLeft', 'toggleRight', 'toggleLeft', 'rightIsOpened', 'leftIsOpened', 'loadContentPage' ]); scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(Splitter); return Splitter; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; angular.module('onsen').factory('SwitchView', ['$parse', '$onsen', function($parse, $onsen) { var SwitchView = Class.extend({ /** * @param {jqLite} element * @param {Object} scope * @param {Object} attrs */ init: function(element, scope, attrs) { this._element = element; this._checkbox = angular.element(element[0].querySelector('input[type=checkbox]')); this._scope = scope; this._checkbox.on('change', function() { this.emit('change', {'switch': this, value: this._checkbox[0].checked, isInteractive: true}); }.bind(this)); this._prepareNgModel(element, scope, attrs); this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], [ 'isChecked', 'setChecked', 'getCheckboxElement' ]); }, _prepareNgModel: function(element, scope, attrs) { if (attrs.ngModel) { var set = $parse(attrs.ngModel).assign; scope.$parent.$watch(attrs.ngModel, function(value) { this.setChecked(!!value); }.bind(this)); this._checkbox.on('change', function(e) { set(scope.$parent, this.isChecked()); if (attrs.ngChange) { scope.$eval(attrs.ngChange); } scope.$parent.$evalAsync(); }.bind(this)); } }, _destroy: function() { this.emit('destroy'); this._clearDerivingMethods(); this._element = this._checkbox = this._scope = null; } }); MicroEvent.mixin(SwitchView); return SwitchView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function() { 'use strict'; var module = angular.module('onsen'); module.value('TabbarNoneAnimator', ons._internal.TabbarNoneAnimator); module.value('TabbarFadeAnimator', ons._internal.TabbarFadeAnimator); module.value('TabbarSlideAnimator', ons._internal.TabbarSlideAnimator); module.factory('TabbarView', ['$onsen', '$compile', '$parse', function($onsen, $compile, $parse) { var TabbarView = Class.extend({ init: function(scope, element, attrs) { if (element[0].nodeName.toLowerCase() !== 'ons-tabbar') { throw new Error('"element" parameter must be a "ons-tabbar" element.'); } this._scope = scope; this._element = element; this._attrs = attrs; this._lastPageElement = null; this._lastPageScope = null; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], [ 'reactive', 'postchange', 'prechange', 'init', 'show', 'hide', 'destroy' ]); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], [ 'setActiveTab', 'setTabbarVisibility', 'getActiveTabIndex', 'loadPage' ]); }, _compileAndLink: function(pageElement, callback) { var link = $compile(pageElement); var pageScope = this._scope.$new(); link(pageScope); pageScope.$evalAsync(function() { callback(pageElement); }); }, _destroy: function() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(TabbarView); TabbarView.registerAnimator = function(name, Animator) { return window.OnsTabbarElement.registerAnimator(name, Animator); }; return TabbarView; }]); })(); /** * @ngdoc directive * @id alert-dialog * @name ons-alert-dialog * @category dialog * @modifier android * [en]Display an Android style alert dialog.[/en] * [ja]Androidライクなスタイルを表示します。[/ja] * @description * [en]Alert dialog that is displayed on top of the current screen.[/en] * [ja]現在のスクリーンにアラートダイアログを表示します。[/ja] * @codepen Qwwxyp * @guide UsingAlert * [en]Learn how to use the alert dialog.[/en] * [ja]アラートダイアログの使い方の解説。[/ja] * @seealso ons-dialog * [en]ons-dialog component[/en] * [ja]ons-dialogコンポーネント[/ja] * @seealso ons-popover * [en]ons-popover component[/en] * [ja]ons-dialogコンポーネント[/ja] * @seealso ons.notification * [en]Using ons.notification utility functions.[/en] * [ja]アラートダイアログを表示するには、ons.notificationオブジェクトのメソッドを使うこともできます。[/ja] * @example * <script> * ons.ready(function() { * ons.createAlertDialog('alert.html').then(function(alertDialog) { * alertDialog.show(); * }); * }); * </script> * * <script type="text/ons-template" id="alert.html"> * <ons-alert-dialog animation="default" cancelable> * <div class="alert-dialog-title">Warning!</div> * <div class="alert-dialog-content"> * An error has occurred! * </div> * <div class="alert-dialog-footer"> * <button class="alert-dialog-button">OK</button> * </div> * </ons-alert-dialog> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the alert dialog is displayed.[/en] * [ja]アラートダイアログが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute to stop the dialog from showing.[/en] * [ja]この関数を実行すると、アラートダイアログの表示を止めます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the alert dialog is displayed.[/en] * [ja]アラートダイアログが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the alert dialog is hidden.[/en] * [ja]アラートダイアログが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute to stop the dialog from hiding.[/en] * [ja]この関数を実行すると、アラートダイアログが閉じようとするのを止めます。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the alert dialog is hidden.[/en] * [ja]アラートダイアログが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this alert dialog.[/en] * [ja]このアラートダイアログを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the dialog.[/en] * [ja]ダイアログの見た目を指定します。[/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the dialog is disabled.[/en] * [ja]この属性がある時、アラートダイアログはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en] * [ja]ダイアログを表示する際のアニメーション名を指定します。デフォルトでは"none"か"default"が指定できます。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {String} * @default rgba(0, 0, 0, 0.2) * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade", "slide" and "none".[/en] * [ja]アニメーション名を指定します。指定できるのは、"fade", "slide", "none"のいずれかです。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.callback] * [en]Function to execute after the dialog has been revealed.[/en] * [ja]ダイアログが表示され終わった時に呼び出されるコールバックを指定します。[/ja] * @description * [en]Show the alert dialog.[/en] * [ja]ダイアログを表示します。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade", "slide" and "none".[/en] * [ja]アニメーション名を指定します。"fade", "slide", "none"のいずれかを指定します。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.callback] * [en]Function to execute after the dialog has been hidden.[/en] * [ja]このダイアログが閉じた時に呼び出されるコールバックを指定します。[/ja] * @description * [en]Hide the alert dialog.[/en] * [ja]ダイアログを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @description * [en]Returns whether the dialog is visible or not.[/en] * [ja]ダイアログが表示されているかどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is currently visible.[/en] * [ja]ダイアログが表示されていればtrueを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the alert dialog and remove it from the DOM tree.[/en] * [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @description * [en]Define whether the dialog can be canceled by the user or not.[/en] * [ja]アラートダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja] * @param {Boolean} cancelable * [en]If true the dialog will be cancelable.[/en] * [ja]キャンセルできるかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @description * [en]Returns whether the dialog is cancelable or not.[/en] * [ja]このアラートダイアログがキャンセル可能かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is cancelable.[/en] * [ja]キャンセル可能であればtrueを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the alert dialog.[/en] * [ja]このアラートダイアログをdisabled状態にするかどうかを設定します。[/ja] * @param {Boolean} disabled * [en]If true the dialog will be disabled.[/en] * [ja]disabled状態にするかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]このアラートダイアログがdisabled状態かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is disabled.[/en] * [ja]disabled状態であればtrueを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火された際に呼び出されるコールバックを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出されるコールバックを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしlistenerパラメータが指定されなかった場合、そのイベントのリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーの関数オブジェクトを渡します。[/ja] */ (function() { 'use strict'; /** * Alert dialog directive. */ angular.module('onsen').directive('onsAlertDialog', ['$onsen', 'AlertDialogView', function($onsen, AlertDialogView) { return { restrict: 'E', replace: false, scope: true, transclude: false, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var alertDialog = new AlertDialogView(scope, element, attrs); $onsen.declareVarAttribute(attrs, alertDialog); $onsen.registerEventHandlers(alertDialog, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(alertDialog, element); element.data('ons-alert-dialog', alertDialog); scope.$on('$destroy', function() { alertDialog._events = undefined; $onsen.removeModifierMethods(alertDialog); element.data('ons-alert-dialog', undefined); element = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id back_button * @name ons-back-button * @category page * @description * [en]Back button component for ons-toolbar. Can be used with ons-navigator to provide back button support.[/en] * [ja]ons-toolbarに配置できる「戻るボタン」用コンポーネントです。ons-navigatorと共に使用し、ページを1つ前に戻る動作を行います。[/ja] * @codepen aHmGL * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-navigator * [en]ons-navigator component[/en] * [ja]ons-navigatorコンポーネント[/en] * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @guide Returningfromapage * [en]Returning from a page[/en] * [ja]一つ前のページに戻る[/ja] * @example * <ons-back-button> * Back * </ons-back-button> */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsBackButton', ['$onsen', '$compile', 'GenericView', 'ComponentCleaner', function($onsen, $compile, GenericView, ComponentCleaner) { return { restrict: 'E', replace: false, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs, controller, transclude) { CustomElements.upgrade(element[0]); var backButton = GenericView.register(scope, element, attrs, { viewKey: 'ons-back-button' }); scope.$on('$destroy', function() { backButton._events = undefined; $onsen.removeModifierMethods(backButton); element = null; }); ComponentCleaner.onDestroy(scope, function() { ComponentCleaner.destroyScope(scope); ComponentCleaner.destroyAttributes(attrs); element = scope = attrs = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id bottom_toolbar * @name ons-bottom-toolbar * @category page * @description * [en]Toolbar component that is positioned at the bottom of the page.[/en] * [ja]ページ下部に配置されるツールバー用コンポーネントです。[/ja] * @modifier transparent * [en]Make the toolbar transparent.[/en] * [ja]ツールバーの背景を透明にして表示します。[/ja] * @seealso ons-toolbar [en]ons-toolbar component[/en][ja]ons-toolbarコンポーネント[/ja] * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @example * <ons-bottom-toolbar> * <div style="text-align: center; line-height: 44px">Text</div> * </ons-bottom-toolbar> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the toolbar.[/en] * [ja]ツールバーの見た目の表現を指定します。[/ja] */ /** * @ngdoc attribute * @name inline * @initonly * @description * [en]Display the toolbar as an inline element.[/en] * [ja]この属性があると、ツールバーを画面下部ではなくスクロール領域内にそのまま表示します。[/ja] */ (function(){ 'use strict'; angular.module('onsen').directive('onsBottomToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-bottomToolbar' }); var inline = typeof attrs.inline !== 'undefined'; var pageView = element.inheritedData('ons-page'); if (pageView && !inline) { pageView._element[0]._registerBottomToolbar(element[0]); } }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); /** * @ngdoc directive * @id button * @name ons-button * @category form * @modifier outline * [en]Button with outline and transparent background[/en] * [ja]アウトラインを持ったボタンを表示します。[/ja] * @modifier light * [en]Button that doesn't stand out.[/en] * [ja]目立たないボタンを表示します。[/ja] * @modifier quiet * [en]Button with no outline and or background..[/en] * [ja]枠線や背景が無い文字だけのボタンを表示します。[/ja] * @modifier cta * [en]Button that really stands out.[/en] * [ja]目立つボタンを表示します。[/ja] * @modifier large * [en]Large button that covers the width of the screen.[/en] * [ja]横いっぱいに広がる大きなボタンを表示します。[/ja] * @modifier large--quiet * [en]Large quiet button.[/en] * [ja]横いっぱいに広がるquietボタンを表示します。[/ja] * @modifier large--cta * [en]Large call to action button.[/en] * [ja]横いっぱいに広がるctaボタンを表示します。[/ja] * @description * [en]Button component. If you want to place a button in a toolbar, use ons-toolbar-button or ons-back-button instead.[/en] * [ja]ボタン用コンポーネント。ツールバーにボタンを設置する場合は、ons-toolbar-buttonもしくはons-back-buttonコンポーネントを使用します。[/ja] * @codepen hLayx * @guide Button [en]Guide for ons-button[/en][ja]ons-buttonの使い方[/ja] * @guide OverridingCSSstyles [en]More details about modifier attribute[/en][ja]modifier属性の使い方[/ja] * @example * <ons-button modifier="large--cta"> * Tap Me * </ons-button> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the button.[/en] * [ja]ボタンの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Specify if button should be disabled.[/en] * [ja]ボタンを無効化する場合は指定します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the button.[/en] * [ja]このボタンをdisabled状態にするかどうかを設定します。[/ja] * @param {String} disabled * [en]If true the button will be disabled.[/en] * [ja]disabled状態にするかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the button is disabled.[/en] * [ja]ボタンがdisabled状態になっているかどうかを返します。[/ja] * @description * [en]Returns whether the button is disabled or enabled.[/en] * [ja]このボタンがdisabled状態かどうかを返します。[/ja] */ (function(){ 'use strict'; angular.module('onsen').directive('onsButton', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var button = GenericView.register(scope, element, attrs, { viewKey: 'ons-button' }); /** * Returns whether the button is disabled or not. */ button.isDisabled = function() { return this._element[0].hasAttribute('disabled'); }; /** * Disabled or enable button. */ button.setDisabled = function(disabled) { if (disabled) { this._element[0].setAttribute('disabled', ''); } else { this._element[0].removeAttribute('disabled'); } }; $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id carousel * @name ons-carousel * @category carousel * @description * [en]Carousel component.[/en] * [ja]カルーセルを表示できるコンポーネント。[/ja] * @codepen xbbzOQ * @guide UsingCarousel * [en]Learn how to use the carousel component.[/en] * [ja]carouselコンポーネントの使い方[/ja] * @example * <ons-carousel style="width: 100%; height: 200px"> * <ons-carousel-item> * ... * </ons-carousel-item> * <ons-carousel-item> * ... * </ons-carousel-item> * </ons-carousel> */ /** * @ngdoc event * @name postchange * @description * [en]Fired just after the current carousel item has changed.[/en] * [ja]現在表示しているカルーセルの要素が変わった時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Carousel object.[/en] * [ja]イベントが発火したCarouselオブジェクトです。[/ja] * @param {Number} event.activeIndex * [en]Current active index.[/en] * [ja]現在アクティブになっている要素のインデックス。[/ja] * @param {Number} event.lastActiveIndex * [en]Previous active index.[/en] * [ja]以前アクティブだった要素のインデックス。[/ja] */ /** * @ngdoc event * @name refresh * @description * [en]Fired when the carousel has been refreshed.[/en] * [ja]カルーセルが更新された時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Carousel object.[/en] * [ja]イベントが発火したCarouselオブジェクトです。[/ja] */ /** * @ngdoc event * @name overscroll * @description * [en]Fired when the carousel has been overscrolled.[/en] * [ja]カルーセルがオーバースクロールした時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Fired when the carousel has been refreshed.[/en] * [ja]カルーセルが更新された時に発火します。[/ja] * @param {Number} event.activeIndex * [en]Current active index.[/en] * [ja]現在アクティブになっている要素のインデックス。[/ja] * @param {String} event.direction * [en]Can be one of either "up", "down", "left" or "right".[/en] * [ja]オーバースクロールされた方向が得られます。"up", "down", "left", "right"のいずれかの方向が渡されます。[/ja] * @param {Function} event.waitToReturn * [en]Takes a <code>Promise</code> object as an argument. The carousel will not scroll back until the promise has been resolved or rejected.[/en] * [ja]この関数はPromiseオブジェクトを引数として受け取ります。渡したPromiseオブジェクトがresolveされるかrejectされるまで、カルーセルはスクロールバックしません。[/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en]The direction of the carousel. Can be either "horizontal" or "vertical". Default is "horizontal".[/en] * [ja]カルーセルの方向を指定します。"horizontal"か"vertical"を指定できます。"horizontal"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name fullscreen * @description * [en]If this attribute is set the carousel will cover the whole screen.[/en] * [ja]この属性があると、absoluteポジションを使ってカルーセルが自動的に画面いっぱいに広がります。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @type {String} * @extensionOf angular * @description * [en]Variable name to refer this carousel.[/en] * [ja]このカルーセルを参照するための変数名を指定します。[/ja] */ /** * @ngdoc attribute * @name overscrollable * @description * [en]If this attribute is set the carousel will be scrollable over the edge. It will bounce back when released.[/en] * [ja]この属性がある時、タッチやドラッグで端までスクロールした時に、バウンドするような効果が当たります。[/ja] */ /** * @ngdoc attribute * @name item-width * @type {String} * @description * [en]ons-carousel-item's width. Only works when the direction is set to "horizontal".[/en] * [ja]ons-carousel-itemの幅を指定します。この属性は、direction属性に"horizontal"を指定した時のみ有効になります。[/ja] */ /** * @ngdoc attribute * @name item-height * @type {String} * @description * [en]ons-carousel-item's height. Only works when the direction is set to "vertical".[/en] * [ja]ons-carousel-itemの高さを指定します。この属性は、direction属性に"vertical"を指定した時のみ有効になります。[/ja] */ /** * @ngdoc attribute * @name auto-scroll * @description * [en]If this attribute is set the carousel will be automatically scrolled to the closest item border when released.[/en] * [ja]この属性がある時、一番近いcarousel-itemの境界まで自動的にスクロールするようになります。[/ja] */ /** * @ngdoc attribute * @name auto-scroll-ratio * @type {Number} * @description * [en]A number between 0.0 and 1.0 that specifies how much the user must drag the carousel in order for it to auto scroll to the next item.[/en] * [ja]0.0から1.0までの値を指定します。カルーセルの要素をどれぐらいの割合までドラッグすると次の要素に自動的にスクロールするかを指定します。[/ja] */ /** * @ngdoc attribute * @name swipeable * @description * [en]If this attribute is set the carousel can be scrolled by drag or swipe.[/en] * [ja]この属性がある時、カルーセルをスワイプやドラッグで移動できるようになります。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the carousel is disabled.[/en] * [ja]この属性がある時、dragやtouchやswipeを受け付けなくなります。[/ja] */ /** * @ngdoc attribute * @name initial-index * @initonly * @type {Number} * @description * [en]Specify the index of the ons-carousel-item to show initially. Default is 0.[/en] * [ja]最初に表示するons-carousel-itemを0始まりのインデックスで指定します。デフォルト値は 0 です。[/ja] */ /** * @ngdoc attribute * @name auto-refresh * @description * [en]When this attribute is set the carousel will automatically refresh when the number of child nodes change.[/en] * [ja]この属性がある時、子要素の数が変わるとカルーセルは自動的に更新されるようになります。[/ja] */ /** * @ngdoc attribute * @name ons-postchange * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-refresh * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "refresh" event is fired.[/en] * [ja]"refresh"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-overscroll * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "overscroll" event is fired.[/en] * [ja]"overscroll"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature next() * @description * [en]Show next ons-carousel item.[/en] * [ja]次のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature prev() * @description * [en]Show previous ons-carousel item.[/en] * [ja]前のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature first() * @description * [en]Show first ons-carousel item.[/en] * [ja]最初のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature last() * @description * [en]Show last ons-carousel item.[/en] * [ja]最後のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature setSwipeable(swipeable) * @param {Boolean} swipeable * [en]If value is true the carousel will be swipeable.[/en] * [ja]swipeableにする場合にはtrueを指定します。[/ja] * @description * [en]Set whether the carousel is swipeable or not.[/en] * [ja]swipeできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isSwipeable() * @return {Boolean} * [en]true if the carousel is swipeable.[/en] * [ja]swipeableであればtrueを返します。[/ja] * @description * [en]Returns whether the carousel is swipeable or not.[/en] * [ja]swipeable属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setActiveCarouselItemIndex(index) * @param {Number} index * [en]The index that the carousel should be set to.[/en] * [ja]carousel要素のインデックスを指定します。[/ja] * @description * [en]Specify the index of the ons-carousel-item to show.[/en] * [ja]表示するons-carousel-itemをindexで指定します。[/ja] */ /** * @ngdoc method * @signature getActiveCarouselItemIndex() * @return {Number} * [en]The current carousel item index.[/en] * [ja]現在表示しているカルーセル要素のインデックスが返されます。[/ja] * @description * [en]Returns the index of the currently visible ons-carousel-item.[/en] * [ja]現在表示されているons-carousel-item要素のインデックスを返します。[/ja] */ /** * @ngdoc method * @signature getCarouselItemCount) * @return {Number} * [en]The number of carousel items.[/en] * [ja]カルーセル要素の数です。[/ja] * @description * [en]Returns the current number of carousel items..[/en] * [ja]現在のカルーセル要素を数を返します。[/ja] */ /** * @ngdoc method * @signature setAutoScrollEnabled(enabled) * @param {Boolean} enabled * [en]If true auto scroll will be enabled.[/en] * [ja]オートスクロールを有効にする場合にはtrueを渡します。[/ja] * @description * [en]Enable or disable "auto-scroll" attribute.[/en] * [ja]auto-scroll属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isAutoScrollEnabled() * @return {Boolean} * [en]true if auto scroll is enabled.[/en] * [ja]オートスクロールが有効であればtrueを返します。[/ja] * @description * [en]Returns whether the "auto-scroll" attribute is set or not.[/en] * [ja]auto-scroll属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setAutoScrollRatio(ratio) * @param {Number} ratio * [en]The desired ratio.[/en] * [ja]オートスクロールするのに必要な0.0から1.0までのratio値を指定します。[/ja] * @description * [en]Set the auto scroll ratio. Must be a value between 0.0 and 1.0.[/en] * [ja]オートスクロールするのに必要なratio値を指定します。0.0から1.0を必ず指定しなければならない。[/ja] */ /** * @ngdoc method * @signature getAutoScrollRatio() * @return {Number} * [en]The current auto scroll ratio.[/en] * [ja]現在のオートスクロールのratio値。[/ja] * @description * [en]Returns the current auto scroll ratio.[/en] * [ja]現在のオートスクロールのratio値を返します。[/ja] */ /** * @ngdoc method * @signature setOverscrollable(overscrollable) * @param {Boolean} overscrollable * [en]If true the carousel will be overscrollable.[/en] * [ja]overscrollできるかどうかを指定します。[/ja] * @description * [en]Set whether the carousel is overscrollable or not.[/en] * [ja]overscroll属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isOverscrollable() * @return {Boolean} * [en]Whether the carousel is overscrollable or not.[/en] * [ja]overscrollできればtrueを返します。[/ja] * @description * [en]Returns whether the carousel is overscrollable or not.[/en] * [ja]overscroll属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature refresh() * @description * [en]Update the layout of the carousel. Used when adding ons-carousel-items dynamically or to automatically adjust the size.[/en] * [ja]レイアウトや内部の状態を最新のものに更新します。ons-carousel-itemを動的に増やしたり、ons-carouselの大きさを動的に変える際に利用します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]Whether the carousel is disabled or not.[/en] * [ja]disabled状態になっていればtrueを返します。[/ja] * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]disabled属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the carousel will be disabled.[/en] * [ja]disabled状態にする場合にはtrueを指定します。[/ja] * @description * [en]Disable or enable the dialog.[/en] * [ja]disabled属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsCarousel', ['$onsen', 'CarouselView', function($onsen, CarouselView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return function(scope, element, attrs) { CustomElements.upgrade(element[0]); var carousel = new CarouselView(scope, element, attrs); element.data('ons-carousel', carousel); $onsen.registerEventHandlers(carousel, 'postchange refresh overscroll destroy'); $onsen.declareVarAttribute(attrs, carousel); scope.$on('$destroy', function() { carousel._events = undefined; element.data('ons-carousel', undefined); element = null; }); if (element[0].hasAttribute('auto-refresh')) { // Refresh carousel when items are added or removed. scope.$watch( function () { return element[0].childNodes.length; }, function () { setImmediate(function() { carousel.refresh(); }); } ); } setImmediate(function() { carousel.refresh(); }); $onsen.fireComponentEvent(element[0], 'init'); }; }, }; }]); module.directive('onsCarouselItem', function() { return { restrict: 'E', compile: function(element, attrs) { CustomElements.upgrade(element[0]); return function(scope, element, attrs) { CustomElements.upgrade(element[0]); }; } }; }); })(); /** * @ngdoc directive * @id col * @name ons-col * @category grid * @description * [en]Represents a column in the grid system. Use with ons-row to layout components.[/en] * [ja]グリッドシステムにて列を定義します。ons-rowとともに使用し、コンポーネントのレイアウトに利用します。[/ja] * @note * [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-column, they may not be displayed correctly. You can use only one align.[/en] * [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-columnを組み合わせた場合に描画が崩れる場合があります。[/ja] * @codepen GgujC {wide} * @guide layouting [en]Layouting guide[/en][ja]レイアウト機能[/ja] * @seealso ons-row [en]ons-row component[/en][ja]ons-rowコンポーネント[/ja] * @example * <ons-row> * <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col> * <ons-col>Text</ons-col> * </ons-row> */ /** * @ngdoc attribute * @name vertical-align * @type {String} * @description * [en]Vertical alignment of the column. Valid values are "top", "center", and "bottom".[/en] * [ja]縦の配置を指定する。"top", "center", "bottom"のいずれかを指定します。[/ja] */ /** * @ngdoc attribute * @name width * @type {String} * @description * [en]The width of the column. Valid values are css width values ("10%", "50px").[/en] * [ja]カラムの横幅を指定する。パーセントもしくはピクセルで指定します(10%や50px)。[/ja] */ /** * @ngdoc directive * @id dialog * @name ons-dialog * @category dialog * @modifier material * [en]Display a Material Design dialog.[/en] * [ja]マテリアルデザインのダイアログを表示します。[/ja] * @description * [en]Dialog that is displayed on top of current screen.[/en] * [ja]現在のスクリーンにダイアログを表示します。[/ja] * @codepen zxxaGa * @guide UsingDialog * [en]Learn how to use the dialog component.[/en] * [ja]ダイアログコンポーネントの使い方[/ja] * @seealso ons-alert-dialog * [en]ons-alert-dialog component[/en] * [ja]ons-alert-dialogコンポーネント[/ja] * @seealso ons-popover * [en]ons-popover component[/en] * [ja]ons-popoverコンポーネント[/ja] * @example * <script> * ons.ready(function() { * ons.createDialog('dialog.html').then(function(dialog) { * dialog.show(); * }); * }); * </script> * * <script type="text/ons-template" id="dialog.html"> * <ons-dialog cancelable> * ... * </ons-dialog> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the dialog is displayed.[/en] * [ja]ダイアログが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute this function to stop the dialog from being shown.[/en] * [ja]この関数を実行すると、ダイアログの表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the dialog is displayed.[/en] * [ja]ダイアログが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the dialog is hidden.[/en] * [ja]ダイアログが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute this function to stop the dialog from being hidden.[/en] * [ja]この関数を実行すると、ダイアログの非表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the dialog is hidden.[/en] * [ja]ダイアログが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @type {String} * @extensionOf angular * @description * [en]Variable name to refer this dialog.[/en] * [ja]このダイアログを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the dialog.[/en] * [ja]ダイアログの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the dialog is disabled.[/en] * [ja]この属性がある時、ダイアログはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en] * [ja]ダイアログを表示する際のアニメーション名を指定します。"none"もしくは"default"を指定できます。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {String} * @default rgba(0, 0, 0, 0.2) * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.callback] * [en]This function is called after the dialog has been revealed.[/en] * [ja]ダイアログが表示され終わった後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the dialog.[/en] * [ja]ダイアログを開きます。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.callback] * [en]This functions is called after the dialog has been hidden.[/en] * [ja]ダイアログが隠れた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Hide the dialog.[/en] * [ja]ダイアログを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @description * [en]Returns whether the dialog is visible or not.[/en] * [ja]ダイアログが表示されているかどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is visible.[/en] * [ja]ダイアログが表示されている場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the dialog and remove it from the DOM tree.[/en] * [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler for overriding the default behavior.[/en] * [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @param {Boolean} cancelable * [en]If true the dialog will be cancelable.[/en] * [ja]ダイアログをキャンセル可能にする場合trueを指定します。[/ja] * @description * [en]Define whether the dialog can be canceled by the user or not.[/en] * [ja]ダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @description * [en]Returns whether the dialog is cancelable or not.[/en] * [ja]このダイアログがキャンセル可能かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is cancelable.[/en] * [ja]ダイアログがキャンセル可能な場合trueを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the dialog.[/en] * [ja]このダイアログをdisabled状態にするかどうかを設定します。[/ja] * @param {Boolean} disabled * [en]If true the dialog will be disabled.[/en] * [ja]trueを指定するとダイアログをdisabled状態になります。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]このダイアログがdisabled状態かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is disabled.[/en] * [ja]ダイアログがdisabled状態の場合trueを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsDialog', ['$onsen', 'DialogView', function($onsen, DialogView) { return { restrict: 'E', scope: true, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var dialog = new DialogView(scope, element, attrs); $onsen.declareVarAttribute(attrs, dialog); $onsen.registerEventHandlers(dialog, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(dialog, element); element.data('ons-dialog', dialog); scope.$on('$destroy', function() { dialog._events = undefined; $onsen.removeModifierMethods(dialog); element.data('ons-dialog', undefined); element = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsDummyForInit', ['$rootScope', function($rootScope) { var isReady = false; return { restrict: 'E', replace: false, link: { post: function(scope, element) { if (!isReady) { isReady = true; $rootScope.$broadcast('$ons-ready'); } element.remove(); } } }; }]); })(); /** * @ngdoc directive * @id gestureDetector * @name ons-gesture-detector * @category input * @description * [en]Component to detect finger gestures within the wrapped element. See the guide for more details.[/en] * [ja]要素内のジェスチャー操作を検知します。詳しくはガイドを参照してください。[/ja] * @guide DetectingFingerGestures * [en]Detecting finger gestures[/en] * [ja]ジェスチャー操作の検知[/ja] * @example * <ons-gesture-detector> * ... * </ons-gesture-detector> */ (function() { 'use strict'; var EVENTS = ('drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight ' + 'swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate').split(/ +/); angular.module('onsen').directive('onsGestureDetector', ['$onsen', function($onsen) { var scopeDef = EVENTS.reduce(function(dict, name) { dict['ng' + titlize(name)] = '&'; return dict; }, {}); function titlize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } return { restrict: 'E', scope: scopeDef, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: true, compile: function(element, attrs) { return function link(scope, element, attrs, _, transclude) { transclude(scope.$parent, function(cloned) { element.append(cloned); }); var handler = function(event) { var attr = 'ng' + titlize(event.type); if (attr in scopeDef) { scope[attr]({$event: event}); } }; var gestureDetector; setImmediate(function() { gestureDetector = element[0]._gestureDetector; gestureDetector.on(EVENTS.join(' '), handler); }); $onsen.cleaner.onDestroy(scope, function() { gestureDetector.off(EVENTS.join(' '), handler); $onsen.clearComponent({ scope: scope, element: element, attrs: attrs }); gestureDetector.element = scope = element = attrs = null; }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id icon * @name ons-icon * @category icon * @description * [en]Displays an icon. Font Awesome and Ionicon icons are supported.[/en] * [ja]アイコンを表示するコンポーネントです。Font AwesomeもしくはIoniconsから選択できます。[/ja] * @codepen xAhvg * @guide UsingIcons [en]Using icons[/en][ja]アイコンを使う[/ja] * @example * <ons-icon * icon="md-car" * size="20px" * fixed-width="false" * style="color: red"> * </ons-icon> */ /** * @ngdoc attribute * @name icon * @type {String} * @description * [en]The icon name. "md-" prefix for Material Icons, "fa-" for Font Awesome and "ion-" prefix for Ionicons icons. See all icons at http://zavoloklom.github.io/material-design-iconic-font/icons.html, http://fontawesome.io/icons/ and http://ionicons.com.[/en] * [ja]アイコン名を指定します。<code>fa-</code>で始まるものはFont Awesomeとして、<code>ion-</code>で始まるものはIoniconsとして扱われます。使用できるアイコンはこちら: http://fontawesome.io/icons/ および http://ionicons.com。[/ja] */ /** * @ngdoc attribute * @name size * @type {String} * @description * [en]The sizes of the icon. Valid values are lg, 2x, 3x, 4x, 5x, or in pixels.[/en] * [ja]アイコンのサイズを指定します。値は、lg, 2x, 3x, 4x, 5xもしくはピクセル単位で指定できます。[/ja] */ /** * @ngdoc attribute * @name rotate * @type {Number} * @description * [en]Number of degrees to rotate the icon. Valid values are 90, 180, or 270.[/en] * [ja]アイコンを回転して表示します。90, 180, 270から指定できます。[/ja] */ /** * @ngdoc attribute * @name flip * @type {String} * @description * [en]Flip the icon. Valid values are "horizontal" and "vertical".[/en] * [ja]アイコンを反転します。horizontalもしくはverticalを指定できます。[/ja] */ /** * @ngdoc attribute * @name fixed-width * @type {Boolean} * @default false * @description * [en]When used in the list, you want the icons to have the same width so that they align vertically by setting the value to true. Valid values are true, false. Default is false.[/en] * [ja]等幅にするかどうかを指定します。trueもしくはfalseを指定できます。デフォルトはfalseです。[/ja] */ /** * @ngdoc attribute * @name spin * @type {Boolean} * @default false * @description * [en]Specify whether the icon should be spinning. Valid values are true and false.[/en] * [ja]アイコンを回転するかどうかを指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @ngdoc directive * @id if-orientation * @name ons-if-orientation * @category util * @extensionOf angular * @description * [en]Conditionally display content depending on screen orientation. Valid values are portrait and landscape. Different from other components, this component is used as attribute in any element.[/en] * [ja]画面の向きに応じてコンテンツの制御を行います。portraitもしくはlandscapeを指定できます。すべての要素の属性に使用できます。[/ja] * @seealso ons-if-platform [en]ons-if-platform component[/en][ja]ons-if-platformコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-orientation="portrait"> * <p>This will only be visible in portrait mode.</p> * </div> */ /** * @ngdoc attribute * @name ons-if-orientation * @initonly * @extensionOf angular * @type {String} * @description * [en]Either "portrait" or "landscape".[/en] * [ja]portraitもしくはlandscapeを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsIfOrientation', ['$onsen', '$onsGlobal', function($onsen, $onsGlobal) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element) { element.css('display', 'none'); return function(scope, element, attrs) { element.addClass('ons-if-orientation-inner'); attrs.$observe('onsIfOrientation', update); $onsGlobal.orientation.on('change', update); update(); $onsen.cleaner.onDestroy(scope, function() { $onsGlobal.orientation.off('change', update); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { var userOrientation = ('' + attrs.onsIfOrientation).toLowerCase(); var orientation = getLandscapeOrPortrait(); if (userOrientation === 'portrait' || userOrientation === 'landscape') { if (userOrientation === orientation) { element.css('display', ''); } else { element.css('display', 'none'); } } } function getLandscapeOrPortrait() { return $onsGlobal.orientation.isPortrait() ? 'portrait' : 'landscape'; } }; } }; }]); })(); /** * @ngdoc directive * @id if-platform * @name ons-if-platform * @category util * @extensionOf angular * @description * [en]Conditionally display content depending on the platform / browser. Valid values are "opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios" and "wp".[/en] * [ja]プラットフォームやブラウザーに応じてコンテンツの制御をおこないます。opera, firefox, safari, chrome, ie, edge, android, blackberry, ios, wpのいずれかの値を空白区切りで複数指定できます。[/ja] * @seealso ons-if-orientation [en]ons-if-orientation component[/en][ja]ons-if-orientationコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-platform="android"> * ... * </div> */ /** * @ngdoc attribute * @name ons-if-platform * @type {String} * @initonly * @extensionOf angular * @description * [en]One or multiple space separated values: "opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios" or "wp".[/en] * [ja]"opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios", "wp"のいずれか空白区切りで複数指定できます。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsIfPlatform', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element) { element.addClass('ons-if-platform-inner'); element.css('display', 'none'); var platform = getPlatformString(); return function(scope, element, attrs) { attrs.$observe('onsIfPlatform', function(userPlatform) { if (userPlatform) { update(); } }); update(); $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { var userPlatforms = attrs.onsIfPlatform.toLowerCase().trim().split(/\s+/); if (userPlatforms.indexOf(platform.toLowerCase()) >= 0) { element.css('display', 'block'); } else { element.css('display', 'none'); } } }; function getPlatformString() { if (navigator.userAgent.match(/Android/i)) { return 'android'; } if ((navigator.userAgent.match(/BlackBerry/i)) || (navigator.userAgent.match(/RIM Tablet OS/i)) || (navigator.userAgent.match(/BB10/i))) { return 'blackberry'; } if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { return 'ios'; } if (navigator.userAgent.match(/Windows Phone|IEMobile|WPDesktop/i)) { return 'wp'; } // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera) var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; if (isOpera) { return 'opera'; } var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+ if (isFirefox) { return 'firefox'; } var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]" if (isSafari) { return 'safari'; } var isEdge = navigator.userAgent.indexOf(' Edge/') >= 0; if (isEdge) { return 'edge'; } var isChrome = !!window.chrome && !isOpera && !isEdge; // Chrome 1+ if (isChrome) { return 'chrome'; } var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6 if (isIE) { return 'ie'; } return 'unknown'; } } }; }]); })(); /** * @ngdoc directive * @id ons-keyboard-active * @name ons-keyboard-active * @category input * @extensionOf angular * @description * [en] * Conditionally display content depending on if the software keyboard is visible or hidden. * This component requires cordova and that the com.ionic.keyboard plugin is installed. * [/en] * [ja] * ソフトウェアキーボードが表示されているかどうかで、コンテンツを表示するかどうかを切り替えることが出来ます。 * このコンポーネントは、Cordovaやcom.ionic.keyboardプラグインを必要とします。 * [/ja] * @guide UtilityAPIs * [en]Other utility APIs[/en] * [ja]他のユーティリティAPI[/ja] * @example * <div ons-keyboard-active> * This will only be displayed if the software keyboard is open. * </div> * <div ons-keyboard-inactive> * There is also a component that does the opposite. * </div> */ /** * @ngdoc attribute * @name ons-keyboard-active * @description * [en]The content of tags with this attribute will be visible when the software keyboard is open.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが表示された時に初めて表示されます。[/ja] */ /** * @ngdoc attribute * @name ons-keyboard-inactive * @description * [en]The content of tags with this attribute will be visible when the software keyboard is hidden.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが隠れている時のみ表示されます。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); var compileFunction = function(show, $onsen) { return function(element) { return function(scope, element, attrs) { var dispShow = show ? 'block' : 'none', dispHide = show ? 'none' : 'block'; var onShow = function() { element.css('display', dispShow); }; var onHide = function() { element.css('display', dispHide); }; var onInit = function(e) { if (e.visible) { onShow(); } else { onHide(); } }; ons.softwareKeyboard.on('show', onShow); ons.softwareKeyboard.on('hide', onHide); ons.softwareKeyboard.on('init', onInit); if (ons.softwareKeyboard._visible) { onShow(); } else { onHide(); } $onsen.cleaner.onDestroy(scope, function() { ons.softwareKeyboard.off('show', onShow); ons.softwareKeyboard.off('hide', onHide); ons.softwareKeyboard.off('init', onInit); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); }; }; }; module.directive('onsKeyboardActive', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(true, $onsen) }; }]); module.directive('onsKeyboardInactive', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(false, $onsen) }; }]); })(); /** * @ngdoc directive * @id lazy-repeat * @name ons-lazy-repeat * @extensionOf angular * @category control * @description * [en] * Using this component a list with millions of items can be rendered without a drop in performance. * It does that by "lazily" loading elements into the DOM when they come into view and * removing items from the DOM when they are not visible. * [/en] * [ja] * このコンポーネント内で描画されるアイテムのDOM要素の読み込みは、画面に見えそうになった時まで自動的に遅延され、 * 画面から見えなくなった場合にはその要素は動的にアンロードされます。 * このコンポーネントを使うことで、パフォーマンスを劣化させること無しに巨大な数の要素を描画できます。 * [/ja] * @codepen QwrGBm * @guide UsingLazyRepeat * [en]How to use Lazy Repeat[/en] * [ja]レイジーリピートの使い方[/ja] * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope) { * $scope.MyDelegate = { * countItems: function() { * // Return number of items. * return 1000000; * }, * * calculateItemHeight: function(index) { * // Return the height of an item in pixels. * return 45; * }, * * configureItemScope: function(index, itemScope) { * // Initialize scope * itemScope.item = 'Item #' + (index + 1); * }, * * destroyItemScope: function(index, itemScope) { * // Optional method that is called when an item is unloaded. * console.log('Destroyed item with index: ' + index); * } * }; * }); * </script> * * <ons-list ng-controller="MyController"> * <ons-list-item ons-lazy-repeat="MyDelegate"> * {{ item }} * </ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name ons-lazy-repeat * @type {Expression} * @initonly * @extensionOf angular * @description * [en]A delegate object, can be either an object attached to the scope (when using AngularJS) or a normal JavaScript variable.[/en] * [ja]要素のロード、アンロードなどの処理を委譲するオブジェクトを指定します。AngularJSのスコープの変数名や、通常のJavaScriptの変数名を指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Lazy repeat directive. */ module.directive('onsLazyRepeat', ['$onsen', 'LazyRepeatView', function($onsen, LazyRepeatView) { return { restrict: 'A', replace: false, priority: 1000, terminal: true, compile: function(element, attrs) { return function(scope, element, attrs) { var lazyRepeat = new LazyRepeatView(scope, element, attrs); scope.$on('$destroy', function() { scope = element = attrs = lazyRepeat = null; }); }; } }; }]); })(); /** * @ngdoc directive * @id list * @name ons-list * @category list * @modifier inset * [en]Inset list that doesn't cover the whole width of the parent.[/en] * [ja]親要素の画面いっぱいに広がらないリストを表示します。[/ja] * @modifier noborder * [en]A list with no borders at the top and bottom.[/en] * [ja]リストの上下のボーダーが無いリストを表示します。[/ja] * @description * [en]Component to define a list, and the container for ons-list-item(s).[/en] * [ja]リストを表現するためのコンポーネント。ons-list-itemのコンテナとして使用します。[/ja] * @seealso ons-list-item * [en]ons-list-item component[/en] * [ja]ons-list-itemコンポーネント[/ja] * @seealso ons-list-header * [en]ons-list-header component[/en] * [ja]ons-list-headerコンポーネント[/ja] * @guide UsingList * [en]Using lists[/en] * [ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list.[/en] * [ja]リストの表現を指定します。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsList', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, {viewKey: 'ons-list'}); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id list-header * @name ons-list-header * @category list * @description * [en]Header element for list items. Must be put inside ons-list component.[/en] * [ja]リスト要素に使用するヘッダー用コンポーネント。ons-listと共に使用します。[/ja] * @seealso ons-list * [en]ons-list component[/en] * [ja]ons-listコンポーネント[/ja] * @seealso ons-list-item [en]ons-list-item component[/en][ja]ons-list-itemコンポーネント[/ja] * @guide UsingList [en]Using lists[/en][ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list header.[/en] * [ja]ヘッダーの表現を指定します。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsListHeader', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, {viewKey: 'ons-listHeader'}); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id list-item * @name ons-list-item * @category list * @modifier tight * [en]Remove the space above and below the item content. This is useful for multi-line content.[/en] * [ja]行間のスペースを取り除きます。複数行の内容をリストで扱う場合に便利です。[/ja] * @modifier tappable * [en]Make the list item change appearance when it's tapped.[/en] * [ja]タップやクリックした時に効果が表示されるようになります。[/ja] * @modifier chevron * [en]Display a chevron at the right end of the list item and make it change appearance when tapped.[/en] * [ja]要素の右側に右矢印が表示されます。また、タップやクリックした時に効果が表示されるようになります。[/ja] * @description * [en]Component that represents each item in the list. Must be put inside the ons-list component.[/en] * [ja]リストの各要素を表現するためのコンポーネントです。ons-listコンポーネントと共に使用します。[/ja] * @seealso ons-list * [en]ons-list component[/en] * [ja]ons-listコンポーネント[/ja] * @seealso ons-list-header * [en]ons-list-header component[/en] * [ja]ons-list-headerコンポーネント[/ja] * @guide UsingList * [en]Using lists[/en] * [ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list item.[/en] * [ja]各要素の表現を指定します。[/ja] */ /** * @ngdoc attribute * @name lock-on-drag * @type {String} * @description * [en]Prevent vertical scrolling when the user drags horizontally.[/en] * [ja]この属性があると、ユーザーがこの要素を横方向にドラッグしている時に、縦方向のスクロールが起きないようになります。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsListItem', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, {viewKey: 'ons-list-item'}); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id loading-placeholder * @name ons-loading-placeholder * @category util * @description * [en]Display a placeholder while the content is loading.[/en] * [ja]Onsen UIが読み込まれるまでに表示するプレースホルダーを表現します。[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-loading-placeholder="page.html"> * Loading... * </div> */ /** * @ngdoc attribute * @name ons-loading-placeholder * @initonly * @type {String} * @description * [en]The url of the page to load.[/en] * [ja]読み込むページのURLを指定します。[/ja] */ (function(){ 'use strict'; angular.module('onsen').directive('onsLoadingPlaceholder', function() { return { restrict: 'A', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); if (attrs.onsLoadingPlaceholder) { ons._resolveLoadingPlaceholder(element[0], attrs.onsLoadingPlaceholder, function(contentElement, done) { CustomElements.upgrade(contentElement); ons.compile(contentElement); scope.$evalAsync(function() { setImmediate(done); }); }); } } }; }); })(); /** * @ngdoc directive * @id material-input * @name ons-material-input * @category form * @description * [en]Material Design input component.[/en] * [ja]Material Designのinputコンポ―ネントです。[/ja] * @codepen ojQxLj * @guide UsingFormComponents * [en]Using form components[/en] * [ja]フォームを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @example * <ons-material-input label="Username"></ons-material-input> */ /** * @ngdoc attribute * @name label * @type {String} * @description * [en]Text for animated floating label.[/en] * [ja]アニメーションさせるフローティングラベルのテキストを指定します。[/ja] */ /** * @ngdoc attribute * @name no-float * @description * [en]If this attribute is present, the label will not be animated.[/en] * [ja]この属性が設定された時、ラベルはアニメーションしないようになります。[/ja] */ /** * @ngdoc attribute * @name ng-model * @extensionOf angular * @description * [en]Bind the value to a model. Works just like for normal input elements.[/en] * [ja]この要素の値をモデルに紐付けます。通常のinput要素の様に動作します。[/ja] */ /** * @ngdoc attribute * @name ng-change * @extensionOf angular * @description * [en]Executes an expression when the value changes. Works just like for normal input elements.[/en] * [ja]値が変わった時にこの属性で指定したexpressionが実行されます。通常のinput要素の様に動作します。[/ja] */ (function(){ 'use strict'; angular.module('onsen').directive('onsMaterialInput', ['$parse', function($parse) { return { restrict: 'E', replace: false, scope: true, link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); if (attrs.ngModel) { var set = $parse(attrs.ngModel).assign; scope.$parent.$watch(attrs.ngModel, function(value) { element[0].value = value; }); element[0]._input.addEventListener('input', function() { set(scope.$parent, element[0].value); if (attrs.ngChange) { scope.$eval(attrs.ngChange); } scope.$parent.$evalAsync(); }.bind(this)); } } }; }]); })(); /** * @ngdoc directive * @id modal * @name ons-modal * @category modal * @description * [en] * Modal component that masks current screen. * Underlying components are not subject to any events while the modal component is shown. * [/en] * [ja] * 画面全体をマスクするモーダル用コンポーネントです。下側にあるコンポーネントは、 * モーダルが表示されている間はイベント通知が行われません。 * [/ja] * @guide UsingModal * [en]Using ons-modal component[/en] * [ja]モーダルの使い方[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @codepen devIg * @example * <ons-modal> * ... * </ons-modal> */ /** * @ngdoc attribute * @name var * @type {String} * @extensionOf angular * @initonly * @description * [en]Variable name to refer this modal.[/en] * [ja]このモーダルを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]The animation used when showing and hiding the modal. Can be either "none" or "fade".[/en] * [ja]モーダルを表示する際のアニメーション名を指定します。"none"もしくは"fade"を指定できます。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc method * @signature toggle([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none" and "fade".[/en] * [ja]アニメーション名を指定します。"none", "fade"のいずれかを指定します。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @description * [en]Toggle modal visibility.[/en] * [ja]モーダルの表示を切り替えます。[/ja] */ /** * @ngdoc method * @signature show([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none" and "fade".[/en] * [ja]アニメーション名を指定します。"none", "fade"のいずれかを指定します。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @description * [en]Show modal.[/en] * [ja]モーダルを表示します。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none" and "fade".[/en] * [ja]アニメーション名を指定します。"none", "fade"のいずれかを指定します。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @description * [en]Hide modal.[/en] * [ja]モーダルを非表示にします。[/ja] */ /** * @ngdoc method * @signature isShown() * @return {Boolean} * [en]true if the modal is visible.[/en] * [ja]モーダルが表示されている場合にtrueとなります。[/ja] * @description * [en]Returns whether the modal is visible or not.[/en] * [ja]モーダルが表示されているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler.[/en] * [ja]ons-modalに紐付いているバックボタンハンドラを取得します。[/ja] */ (function() { 'use strict'; /** * Modal directive. */ angular.module('onsen').directive('onsModal', ['$onsen', 'ModalView', function($onsen, ModalView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, link: { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var modal = new ModalView(scope, element, attrs); $onsen.addModifierMethodsForCustomElements(modal, element); $onsen.declareVarAttribute(attrs, modal); element.data('ons-modal', modal); element[0]._ensureNodePosition(); scope.$on('$destroy', function() { $onsen.removeModifierMethods(modal); element.data('ons-modal', undefined); modal = element = scope = attrs = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); /** * @ngdoc directive * @id navigator * @name ons-navigator * @category navigation * @description * [en]A component that provides page stack management and navigation. This component does not have a visible content.[/en] * [ja]ページスタックの管理とナビゲーション機能を提供するコンポーネント。画面上への出力はありません。[/ja] * @codepen yrhtv * @guide PageNavigation * [en]Guide for page navigation[/en] * [ja]ページナビゲーションの概要[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @example * <ons-navigator animation="slide" var="app.navi"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.pushPage('page.html');">Push</ons-button> * </p> * </ons-page> * </ons-navigator> * * <ons-template id="page.html"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.popPage();">Pop</ons-button> * </p> * </ons-page> * </ons-template> */ /** * @ngdoc event * @name prepush * @description * [en]Fired just before a page is pushed.[/en] * [ja]pageがpushされる直前に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.currentPage * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the push.[/en] * [ja]この関数を呼び出すと、push処理がキャンセルされます。[/ja] */ /** * @ngdoc event * @name prepop * @description * [en]Fired just before a page is popped.[/en] * [ja]pageがpopされる直前に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.currentPage * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the pop.[/en] * [ja]この関数を呼び出すと、pageのpopがキャンセルされます。[/ja] */ /** * @ngdoc event * @name postpush * @description * [en]Fired just after a page is pushed.[/en] * [ja]pageがpushされてアニメーションが終了してから発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.enterPage * [en]Object of the next page.[/en] * [ja]pushされたpageオブジェクト。[/ja] * @param {Object} event.leavePage * [en]Object of the previous page.[/en] * [ja]以前のpageオブジェクト。[/ja] */ /** * @ngdoc event * @name postpop * @description * [en]Fired just after a page is popped.[/en] * [ja]pageがpopされてアニメーションが終わった後に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.enterPage * [en]Object of the next page.[/en] * [ja]popされて表示されるページのオブジェクト。[/ja] * @param {Object} event.leavePage * [en]Object of the previous page.[/en] * [ja]popされて消えるページのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name page * @initonly * @type {String} * @description * [en]First page to show when navigator is initialized.[/en] * [ja]ナビゲーターが初期化された時に表示するページを指定します。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this navigator.[/en] * [ja]このナビゲーターを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name ons-prepush * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepush" event is fired.[/en] * [ja]"prepush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prepop * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepop" event is fired.[/en] * [ja]"prepop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postpush * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpush" event is fired.[/en] * [ja]"postpush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postpop * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpop" event is fired.[/en] * [ja]"postpop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-init * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-show * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-hide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]Specify the transition animation. Use one of "slide", "simpleslide", "fade", "lift", "none" and "default".[/en] * [ja]画面遷移する際のアニメーションを指定します。"slide", "simpleslide", "fade", "lift", "none", "default"のいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc method * @signature pushPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or a <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]pushPage()による画面遷移が終了した時に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Pushes the specified pageUrl into the page stack.[/en] * [ja]指定したpageUrlを新しいページスタックに追加します。新しいページが表示されます。[/ja] */ /** * @ngdoc method * @signature bringPageTop(item, [options]) * @param {String|Number} item * [en]Page URL or index of an existing page in navigator's stack.[/en] * [ja]ページのURLかもしくはons-navigatorのページスタックのインデックス値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]pushPage()による画面遷移が終了した時に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Brings the given page to the top of the page-stack if already exists or pushes it into the stack if doesn't.[/en] * [ja]指定したページをページスタックの一番上に移動します。もし指定したページが無かった場合新しくpushされます。[/ja] */ /** * @ngdoc method * @signature insertPage(index, pageUrl, [options]) * @param {Number} index * [en]The index where it should be inserted.[/en] * [ja]スタックに挿入する位置のインデックスを指定します。[/ja] * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or a <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @description * [en]Insert the specified pageUrl into the page stack with specified index.[/en] * [ja]指定したpageUrlをページスタックのindexで指定した位置に追加します。[/ja] */ /** * @ngdoc method * @signature popPage([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Boolean} [options.refresh] * [en]The previous page will be refreshed (destroyed and created again) before popPage action.[/en] * [ja]popPageする前に、前にあるページを生成しなおして更新する場合にtrueを指定します。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Pops the current page from the page stack. The previous page will be displayed.[/en] * [ja]現在表示中のページをページスタックから取り除きます。一つ前のページに戻ります。[/ja] */ /** * @ngdoc method * @signature replacePage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Replaces the current page with the specified one.[/en] * [ja]現在表示中のページをを指定したページに置き換えます。[/ja] */ /** * @ngdoc method * @signature resetToPage(pageUrl, [options]) * @param {String/undefined} pageUrl * [en]Page URL. Can be either a HTML document or an <code>&lt;ons-template&gt;</code>. If the value is undefined or '', the navigator will be reset to the page that was first displayed.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。undefinedや''を指定すると、ons-navigatorが最初に表示したページを指定したことになります。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Clears page stack and adds the specified pageUrl to the page stack.[/en] * [ja]ページスタックをリセットし、指定したページを表示します。[/ja] */ /** * @ngdoc method * @signature getCurrentPage() * @return {Object} * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @description * [en]Get current page's navigator item. Use this method to access options passed by pushPage() or resetToPage() method.[/en] * [ja]現在のページを取得します。pushPage()やresetToPage()メソッドの引数を取得できます。[/ja] */ /** * @ngdoc method * @signature getPages() * @return {List} * [en]List of page objects.[/en] * [ja]pageオブジェクトの配列。[/ja] * @description * [en]Retrieve the entire page stack of the navigator.[/en] * [ja]ナビゲーターの持つページスタックの一覧を取得します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler for overriding the default behavior.[/en] * [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var lastReady = window.OnsNavigatorElement.rewritables.ready; window.OnsNavigatorElement.rewritables.ready = ons._waitDiretiveInit('ons-navigator', lastReady); var lastLink = window.OnsNavigatorElement.rewritables.link; window.OnsNavigatorElement.rewritables.link = function(navigatorElement, target, callback) { var view = angular.element(navigatorElement).data('ons-navigator'); view._compileAndLink(target, function(target) { lastLink(navigatorElement, target, callback); }); }; angular.module('onsen').directive('onsNavigator', ['NavigatorView', '$onsen', function(NavigatorView, $onsen) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function(element) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs, controller) { CustomElements.upgrade(element[0]); var navigator = new NavigatorView(scope, element, attrs); $onsen.declareVarAttribute(attrs, navigator); $onsen.registerEventHandlers(navigator, 'prepush prepop postpush postpop init show hide destroy'); element.data('ons-navigator', navigator); scope.$on('$destroy', function() { navigator._events = undefined; element.data('ons-navigator', undefined); element = null; }); }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id page * @name ons-page * @category page * @description * [en]Should be used as root component of each page. The content inside page component is scrollable.[/en] * [ja]ページ定義のためのコンポーネントです。このコンポーネントの内容はスクロールが許可されます。[/ja] * @guide ManagingMultiplePages * [en]Managing multiple pages[/en] * [ja]複数のページを管理する[/ja] * @guide Pagelifecycle * [en]Page life cycle events[/en] * [ja]ページライフサイクルイベント[/ja] * @guide HandlingBackButton * [en]Handling back button[/en] * [ja]バックボタンに対応する[/ja] * @guide OverridingCSSstyles * [en]Overriding CSS styles[/en] * [ja]CSSスタイルのオーバーライド[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * ... * </ons-page> */ /** * @ngdoc event * @name init * @description * [en]Fired right after the page is attached.[/en] * [ja]ページがアタッチされた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.page * [en]Page object.[/en] * [ja]ページのオブジェクト。[/ja] */ /** * @ngdoc event * @name show * @description * [en]Fired right after the page is shown.[/en] * [ja]ページが表示された後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.page * [en]Page object.[/en] * [ja]ページのオブジェクト。[/ja] */ /** * @ngdoc event * @name hide * @description * [en]Fired right after the page is hidden.[/en] * [ja]ページが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.page * [en]Page object.[/en] * [ja]ページのオブジェクト。[/ja] */ /** * @ngdoc event * @name destroy * @description * [en]Fired right before the page is destroyed.[/en] * [ja]ページが破棄される前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.page * [en]Page object.[/en] * [ja]ページのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this page.[/en] * [ja]このページを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]Specify modifier name to specify custom styles.[/en] * [ja]スタイル定義をカスタマイズするための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name on-device-backbutton * @type {Expression} * @extensionOf angular * @description * [en]Allows you to specify custom behavior when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。[/ja] */ /** * @ngdoc attribute * @name ng-device-backbutton * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior with an AngularJS expression when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。AngularJSのexpressionを指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-init * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "init" event is fired.[/en] * [ja]"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-show * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "show" event is fired.[/en] * [ja]"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-hide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "hide" event is fired.[/en] * [ja]"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Get the associated back button handler. This method may return null if no handler is assigned.[/en] * [ja]バックボタンハンドラを取得します。このメソッドはnullを返す場合があります。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsPage', ['$onsen', 'PageView', function($onsen, PageView) { function firePageInitEvent(element) { // TODO: remove dirty fix var i = 0, f = function() { if (i++ < 15) { if (isAttached(element)) { element._tryToFillStatusBar(); $onsen.fireComponentEvent(element, 'init'); fireActualPageInitEvent(element); } else { if (i > 10) { setTimeout(f, 1000 / 60); } else { setImmediate(f); } } } else { throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.'); } }; f(); } function fireActualPageInitEvent(element) { var event = document.createEvent('HTMLEvents'); event.initEvent('pageinit', true, true); element.dispatchEvent(event); } function isAttached(element) { if (document.documentElement === element) { return true; } return element.parentNode ? isAttached(element.parentNode) : false; } return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var page = new PageView(scope, element, attrs); $onsen.declareVarAttribute(attrs, page); $onsen.registerEventHandlers(page, 'init show hide destroy'); element.data('ons-page', page); $onsen.addModifierMethodsForCustomElements(page, element); element.data('_scope', scope); $onsen.cleaner.onDestroy(scope, function() { page._events = undefined; $onsen.removeModifierMethods(page); element.data('ons-page', undefined); element.data('_scope', undefined); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); scope = element = attrs = null; }); }, post: function postLink(scope, element, attrs) { firePageInitEvent(element[0]); } }; } }; }]); })(); /** * @ngdoc directive * @id popover * @name ons-popover * @category popover * @modifier android * [en]Display an Android style popover.[/en] * [ja]Androidライクなポップオーバーを表示します。[/ja] * @description * [en]A component that displays a popover next to an element.[/en] * [ja]ある要素を対象とするポップオーバーを表示するコンポーネントです。[/ja] * @codepen ZYYRKo * @example * <script> * ons.ready(function() { * ons.createPopover('popover.html').then(function(popover) { * popover.show('#mybutton'); * }); * }); * </script> * * <script type="text/ons-template" id="popover.html"> * <ons-popover cancelable> * <p style="text-align: center; opacity: 0.5;">This popover will choose which side it's displayed on automatically.</p> * </ons-popover> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the popover is displayed.[/en] * [ja]ポップオーバーが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to stop the popover from being shown.[/en] * [ja]この関数を呼び出すと、ポップオーバーの表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the popover is displayed.[/en] * [ja]ポップオーバーが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the popover is hidden.[/en] * [ja]ポップオーバーが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to stop the popover from being hidden.[/en] * [ja]この関数を呼び出すと、ポップオーバーが隠れる処理をキャンセルします。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the popover is hidden.[/en] * [ja]ポップオーバーが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this popover.[/en] * [ja]このポップオーバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the popover.[/en] * [ja]ポップオーバーの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en] * A space separated list of directions. If more than one direction is specified, * it will be chosen automatically. Valid directions are "up", "down", "left" and "right". * [/en] * [ja] * ポップオーバーを表示する方向を空白区切りで複数指定できます。 * 指定できる方向は、"up", "down", "left", "right"の4つです。空白区切りで複数指定することもできます。 * 複数指定された場合、対象とする要素に合わせて指定した値から自動的に選択されます。 * [/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the popover can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ポップオーバーが表示された時に、背景やバックボタンをタップした時にをポップオーバー閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the popover is disabled.[/en] * [ja]この属性がある時、ポップオーバーはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @description * [en]The animation used when showing an hiding the popover. Can be either "none" or "fade".[/en] * [ja]ポップオーバーを表示する際のアニメーション名を指定します。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {Color} * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。デフォルトは"rgba(0, 0, 0, 0.2)"です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show(target, [options]) * @param {String|Event|HTMLElement} target * [en]Target element. Can be either a CSS selector, an event object or a DOM element.[/en] * [ja]ポップオーバーのターゲットとなる要素を指定します。CSSセレクタかeventオブジェクトかDOM要素のいずれかを渡せます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade" and "none".[/en] * [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @description * [en]Open the popover and point it at a target. The target can be either an event, a css selector or a DOM element..[/en] * [ja]対象とする要素にポップオーバーを表示します。target引数には、$eventオブジェクトやDOMエレメントやCSSセレクタを渡すことが出来ます。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade" and "none".[/en] * [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @description * [en]Close the popover.[/en] * [ja]ポップオーバーを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @return {Boolean} * [en]true if the popover is visible.[/en] * [ja]ポップオーバーが表示されている場合にtrueとなります。[/ja] * @description * [en]Returns whether the popover is visible or not.[/en] * [ja]ポップオーバーが表示されているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the popover and remove it from the DOM tree.[/en] * [ja]ポップオーバーを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @param {Boolean} cancelable * [en]If true the popover will be cancelable.[/en] * [ja]ポップオーバーがキャンセル可能にしたい場合にtrueを指定します。[/ja] * @description * [en]Set whether the popover can be canceled by the user when it is shown.[/en] * [ja]ポップオーバーを表示した際に、ユーザがそのポップオーバーをキャンセルできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @return {Boolean} * [en]true if the popover is cancelable.[/en] * [ja]ポップオーバーがキャンセル可能であればtrueとなります。[/ja] * @description * [en]Returns whether the popover is cancelable or not.[/en] * [ja]このポップオーバーがキャンセル可能かどうかを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the popover will be disabled.[/en] * [ja]ポップオーバーをdisabled状態にしたい場合にはtrueを指定します。[/ja] * @description * [en]Disable or enable the popover.[/en] * [ja]このポップオーバーをdisabled状態にするかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the popover is disabled.[/en] * [ja]ポップオーバーがdisabled状態であればtrueとなります。[/ja] * @description * [en]Returns whether the popover is disabled or enabled.[/en] * [ja]このポップオーバーがdisabled状態かどうかを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsPopover', ['$onsen', 'PopoverView', function($onsen, PopoverView) { return { restrict: 'E', replace: false, scope: true, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var popover = new PopoverView(scope, element, attrs); $onsen.declareVarAttribute(attrs, popover); $onsen.registerEventHandlers(popover, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(popover, element); element.data('ons-popover', popover); scope.$on('$destroy', function() { popover._events = undefined; $onsen.removeModifierMethods(popover); element.data('ons-popover', undefined); element = null; }); if ($onsen.isAndroid()) { setImmediate(function() { popover.addModifier('android'); }); } }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id progress * @name ons-progress * @category progress * @description * [en]A material design progress component. Can be displayed both as a linear or circular progress indicator.[/en] * [ja]マテリアルデザインのprgoressコンポーネントです。linearもしくはcircularなプログレスインジケータを表示できます。[/ja] * @codepen VvVaZv * @example * <ons-progress * type="circular" * value="55" * secondary-value="87"> * </ons-progress> */ /** * @ngdoc attribute * @name type * @initonly * @type {String} * @description * [en]The type of indicator. Can be one of either "bar" or "circular". Defaults to "bar".[/en] * [ja]indicatorのタイプを指定します。"bar"もしくは"circular"を指定できます。デフォルトは"bar"です。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]Change the appearance of the progress indicator.[/en] * [ja]プログレスインジケータの見た目を変更します。[/ja] */ /** * @ngdoc attribute * @name value * @type {Number} * @description * [en]Current progress. Should be a value between 0 and 100.[/en] * [ja]現在の進行状況の値を指定します。0から100の間の値を指定して下さい。[/ja] */ /** * @ngdoc attribute * @name secondary-value * @type {Number} * @description * [en]Current secondary progress. Should be a value between 0 and 100.[/en] * [ja]現在の2番目の進行状況の値を指定します。0から100の間の値を指定して下さい。[/ja] */ /** * @ngdoc attribute * @name indeterminate * @description * [en]If this attribute is set, an infinite looping animation will be shown.[/en] * [ja]この属性が設定された場合、ループするアニメーションが表示されます。[/ja] */ /** * @ngdoc directive * @id pull-hook * @name ons-pull-hook * @category control * @description * [en]Component that adds "pull-to-refresh" to an <ons-page> element.[/en] * [ja]ons-page要素以下でいわゆるpull to refreshを実装するためのコンポーネントです。[/ja] * @codepen WbJogM * @guide UsingPullHook * [en]How to use Pull Hook[/en] * [ja]プルフックを使う[/ja] * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope, $timeout) { * $scope.items = [3, 2 ,1]; * * $scope.load = function($done) { * $timeout(function() { * $scope.items.unshift($scope.items.length + 1); * $done(); * }, 1000); * }; * }); * </script> * * <ons-page ng-controller="MyController"> * <ons-pull-hook var="loader" ng-action="load($done)"> * <span ng-switch="loader.getCurrentState()"> * <span ng-switch-when="initial">Pull down to refresh</span> * <span ng-switch-when="preaction">Release to refresh</span> * <span ng-switch-when="action">Loading data. Please wait...</span> * </span> * </ons-pull-hook> * <ons-list> * <ons-list-item ng-repeat="item in items"> * Item #{{ item }} * </ons-list-item> * </ons-list> * </ons-page> */ /** * @ngdoc event * @name changestate * @description * [en]Fired when the state is changed. The state can be either "initial", "preaction" or "action".[/en] * [ja]コンポーネントの状態が変わった場合に発火します。状態は、"initial", "preaction", "action"のいずれかです。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.pullHook * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {String} event.state * [en]Current state.[/en] * [ja]現在の状態名を参照できます。[/ja] */ /** * @ngdoc attribute * @name var * @extensionOf angular * @initonly * @type {String} * @description * [en]Variable name to refer this component.[/en] * [ja]このコンポーネントを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the "pull-to-refresh" functionality is disabled.[/en] * [ja]この属性がある時、disabled状態になりアクションが実行されなくなります[/ja] */ /** * @ngdoc attribute * @name ng-action * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Use to specify custom behavior when the page is pulled down. A <code>$done</code> function is available to tell the component that the action is completed.[/en] * [ja]pull downしたときの振る舞いを指定します。アクションが完了した時には<code>$done</code>関数を呼び出します。[/ja] */ /** * @ngdoc attribute * @name on-action * @type {Expression} * @description * [en]Same as <code>ng-action</code> but can be used without AngularJS. A function called <code>done</code> is available to call when action is complete.[/en] * [ja]<code>ng-action</code>と同じですが、AngularJS無しで利用する場合に利用できます。アクションが完了した時には<code>done</code>関数を呼び出します。[/ja] */ /** * @ngdoc attribute * @name height * @type {String} * @description * [en]Specify the height of the component. When pulled down further than this value it will switch to the "preaction" state. The default value is "64px".[/en] * [ja]コンポーネントの高さを指定します。この高さ以上にpull downすると"preaction"状態に移行します。デフォルトの値は"64px"です。[/ja] */ /** * @ngdoc attribute * @name threshold-height * @type {String} * @description * [en]Specify the threshold height. The component automatically switches to the "action" state when pulled further than this value. The default value is "96px". A negative value or a value less than the height will disable this property.[/en] * [ja]閾値となる高さを指定します。この値で指定した高さよりもpull downすると、このコンポーネントは自動的に"action"状態に移行します。[/ja] */ /** * @ngdoc attribute * @name fixed-content * @description * [en]If this attribute is set the content of the page will not move when pulling.[/en] * [ja]この属性がある時、プルフックが引き出されている時にもコンテンツは動きません。[/ja] */ /** * @ngdoc attribute * @name ons-changestate * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "changestate" event is fired.[/en] * [ja]"changestate"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the pull hook will be disabled.[/en] * [ja]trueを指定すると、プルフックがdisabled状態になります。[/ja] * @description * [en]Disable or enable the component.[/en] * [ja]disabled状態にするかどうかを設定できます。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the pull hook is disabled.[/en] * [ja]プルフックがdisabled状態の場合、trueを返します。[/ja] * @description * [en]Returns whether the component is disabled or enabled.[/en] * [ja]disabled状態になっているかを得ることが出来ます。[/ja] */ /** * @ngdoc method * @signature getHeight() * @description * [en]Returns the height of the pull hook in pixels.[/en] * [ja]プルフックの高さをピクセル数で返します。[/ja] */ /** * @ngdoc method * @signature setHeight(height) * @param {Number} height * [en]Desired height.[/en] * [ja]要素の高さを指定します。[/ja] * @description * [en]Specify the height.[/en] * [ja]高さを指定できます。[/ja] */ /** * @ngdoc method * @signature getThresholdHeight() * @description * [en]Returns the height of the threshold in pixels.[/en] * [ja]閾値、となる高さをピクセル数で返します。[/ja] */ /** * @ngdoc method * @signature setThresholdHeight(thresholdHeight) * @param {Number} thresholdHeight * [en]Desired threshold height.[/en] * [ja]プルフックのアクションを起こす閾値となる高さを指定します。[/ja] * @description * [en]Specify the threshold height.[/en] * [ja]閾値となる高さを指定できます。[/ja] */ /** * @ngdoc method * @signature getPullDistance() * @description * [en]Returns the current number of pixels the pull hook has moved.[/en] * [ja]現在のプルフックが引き出された距離をピクセル数で返します。[/ja] */ /** * @ngdoc method * @signature getCurrentState() * @description * [en]Returns the current state of the element.[/en] * [ja]要素の現在の状態を返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; /** * Pull hook directive. */ angular.module('onsen').directive('onsPullHook', ['$onsen', 'PullHookView', function($onsen, PullHookView) { return { restrict: 'E', replace: false, scope: true, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var pullHook = new PullHookView(scope, element, attrs); $onsen.declareVarAttribute(attrs, pullHook); $onsen.registerEventHandlers(pullHook, 'changestate destroy'); element.data('ons-pull-hook', pullHook); scope.$on('$destroy', function() { pullHook._events = undefined; element.data('ons-pull-hook', undefined); scope = element = attrs = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id ripple * @name ons-ripple * @category form * @description * [en]Adds a Material Design "ripple" effect to an element.[/en] * [ja]マテリアルデザインのリップル効果をDOM要素に追加します。[/ja] * @codepen wKQWdZ * @example * <ons-list> * <ons-list-item> * <ons-ripple color="rgba(0, 0, 0, 0.3)"></ons-ripple> * Click me! * </ons-list-item> * </ons-list> * * <ons-ripple target="children" color="rgba(0, 0, 0, 0.3)"> * <p>Click me!</p> * </ons-ripple> */ /** * @ngdoc attribute * @name color * @type {String} * @description * [en]Color of the ripple effect.[/en] * [ja]リップルエフェクトの色を指定します。[/ja] */ /** * @ngdoc attribute * @name center * @description * [en]If this attribute is set, the effect will originate from the center.[/en] * [ja]この属性が設定された場合、その効果は要素の中央から始まります。[/ja] */ /** * @ngdoc attribute * @name target * @type {String} * @description * [en]If this attribute is set to children, the effect will be applied to the children of the component instead of the parent.[/en] * [ja]この属性に"children"を設定されたとき、リップルエフェクトはこのコンポーネントの子要素に適用されます。そうでなければ、親要素に適用されます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set, the ripple effect will be disabled.[/en] * [ja]この属性が設定された場合、リップルエフェクトは無効になります。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsRipple', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, {viewKey: 'ons-ripple'}); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id row * @name ons-row * @category grid * @description * [en]Represents a row in the grid system. Use with ons-col to layout components.[/en] * [ja]グリッドシステムにて行を定義します。ons-colとともに使用し、コンポーネントの配置に使用します。[/ja] * @codepen GgujC {wide} * @guide Layouting * [en]Layouting guide[/en] * [ja]レイアウト調整[/ja] * @seealso ons-col * [en]ons-col component[/en] * [ja]ons-colコンポーネント[/ja] * @note * [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-col, they may not be displayed correctly. You can use only one vertical-align.[/en] * [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-colを組み合わせてそれぞれのons-col要素のvertical-align属性の値に別々の値を指定すると、描画が崩れる場合があります。vertical-align属性の値には一つの値だけを指定できます。[/ja] * @example * <ons-row> * <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col> * <ons-col>Text</ons-col> * </ons-row> */ /** * @ngdoc attribute * @name vertical-align * @type {String} * @description * [en]Short hand attribute for aligning vertically. Valid values are top, bottom, and center.[/en] * [ja]縦に整列するために指定します。top、bottom、centerのいずれかを指定できます。[/ja] */ /** * @ngdoc directive * @id scope * @name ons-scope * @category util * @extensionOf angular * @description * [en]All child elements using the "var" attribute will be attached to the scope of this element.[/en] * [ja]"var"属性を使っている全ての子要素のviewオブジェクトは、この要素のAngularJSスコープに追加されます。[/ja] * @example * <ons-list> * <ons-list-item ons-scope ng-repeat="item in items"> * <ons-carousel var="carousel"> * <ons-carousel-item ng-click="carousel.next()"> * {{ item }} * </ons-carousel-item> * </ons-carousel-item ng-click="carousel.prev()"> * ... * </ons-carousel-item> * </ons-carousel> * </ons-list-item> * </ons-list> */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsScope', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, link: function(scope, element) { element.data('_scope', scope); scope.$on('$destroy', function() { element.data('_scope', undefined); }); } }; }]); })(); /** * @ngdoc directive * @id scroller * @name ons-scroller * @category page * @description * [en]Makes the content inside this tag scrollable.[/en] * [ja]要素内をスクロール可能にします。[/ja] * @example * <ons-scroller style="height: 200px; width: 100%"> * ... * </ons-scroller> */ /** * @ngdoc directive * @id sliding_menu * @name ons-sliding-menu * @category navigation * @extensionOf angular * @description * [en]Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind.[/en] * [ja]スライディングメニューを表現するためのコンポーネントで、片方のページが別のページの上にオーバーレイで表示されます。above-pageで指定されたページは、横からスライドして表示します。[/ja] * @codepen IDvFJ * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @guide UsingSlidingMenu * [en]Using sliding menu[/en] * [ja]スライディングメニューを使う[/ja] * @guide EventHandling * [en]Using events[/en] * [ja]イベントの利用[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-sliding-menu var="app.menu" main-page="page.html" menu-page="menu.html" max-slide-distance="200px" type="reveal" side="left"> * </ons-sliding-menu> * * <ons-template id="page.html"> * <ons-page> * <p style="text-align: center"> * <ons-button ng-click="app.menu.toggleMenu()">Toggle</ons-button> * </p> * </ons-page> * </ons-template> * * <ons-template id="menu.html"> * <ons-page> * <!-- menu page's contents --> * </ons-page> * </ons-template> * */ /** * @ngdoc event * @name preopen * @description * [en]Fired just before the sliding menu is opened.[/en] * [ja]スライディングメニューが開く前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name postopen * @description * [en]Fired just after the sliding menu is opened.[/en] * [ja]スライディングメニューが開き終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name preclose * @description * [en]Fired just before the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name postclose * @description * [en]Fired just after the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じ終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @type {String} * @description * [en]Variable name to refer this sliding menu.[/en] * [ja]このスライディングメニューを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name menu-page * @initonly * @type {String} * @description * [en]The url of the menu page.[/en] * [ja]左に位置するメニューページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name main-page * @initonly * @type {String} * @description * [en]The url of the main page.[/en] * [ja]右に位置するメインページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name swipeable * @initonly * @type {Boolean} * @description * [en]Whether to enable swipe interaction.[/en] * [ja]スワイプ操作を有効にする場合に指定します。[/ja] */ /** * @ngdoc attribute * @name swipe-target-width * @initonly * @type {String} * @description * [en]The width of swipeable area calculated from the left (in pixels). Use this to enable swipe only when the finger touch on the screen edge.[/en] * [ja]スワイプの判定領域をピクセル単位で指定します。画面の端から指定した距離に達するとページが表示されます。[/ja] */ /** * @ngdoc attribute * @name max-slide-distance * @initonly * @type {String} * @description * [en]How far the menu page will slide open. Can specify both in px and %. eg. 90%, 200px[/en] * [ja]menu-pageで指定されたページの表示幅を指定します。ピクセルもしくは%の両方で指定できます(例: 90%, 200px)[/ja] */ /** * @ngdoc attribute * @name side * @initonly * @type {String} * @description * [en]Specify which side of the screen the menu page is located on. Possible values are "left" and "right".[/en] * [ja]menu-pageで指定されたページが画面のどちら側から表示されるかを指定します。leftもしくはrightのいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name type * @initonly * @type {String} * @description * [en]Sliding menu animator. Possible values are reveal (default), push and overlay.[/en] * [ja]スライディングメニューのアニメーションです。"reveal"(デフォルト)、"push"、"overlay"のいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en] * [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en] * [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en] * [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en] * [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setMainPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]Function that is executed after the page has been set.[/en] * [ja]ページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the main contents pane.[/en] * [ja]中央部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature setMenuPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed after the menu page has been set.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]This function will be executed after the menu page has been set.[/en] * [ja]メニューページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the side menu pane.[/en] * [ja]メニュー部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature openMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to reveal the layer behind.[/en] * [ja]メニューページを表示します。[/ja] */ /** * @ngdoc method * @signature closeMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じられた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to hide the layer behind.[/en] * [ja]メニューページを非表示にします。[/ja] */ /** * @ngdoc method * @signature toggleMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened or closed.[/en] * [ja]メニューが開き終わった後か、閉じ終わった後に呼び出される関数オブジェクトです。[/ja] * @description * [en]Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind.[/en] * [ja]現在の状況に合わせて、メニューページを表示もしくは非表示にします。[/ja] */ /** * @ngdoc method * @signature isMenuOpened() * @return {Boolean} * [en]true if the menu is currently open.[/en] * [ja]メニューが開いていればtrueとなります。[/ja] * @description * [en]Returns true if the menu page is open, otherwise false.[/en] * [ja]メニューページが開いている場合はtrue、そうでない場合はfalseを返します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back-button handler.[/en] * [ja]ons-sliding-menuに紐付いているバックボタンハンドラを取得します。[/ja] */ /** * @ngdoc method * @signature setSwipeable(swipeable) * @param {Boolean} swipeable * [en]If true the menu will be swipeable.[/en] * [ja]スワイプで開閉できるようにする場合にはtrueを指定します。[/ja] * @description * [en]Specify if the menu should be swipeable or not.[/en] * [ja]スワイプで開閉するかどうかを設定する。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsSlidingMenu', ['$compile', 'SlidingMenuView', '$onsen', function($compile, SlidingMenuView, $onsen) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function(element, attrs) { var main = element[0].querySelector('.main'), menu = element[0].querySelector('.menu'); if (main) { var mainHtml = angular.element(main).remove().html().trim(); } if (menu) { var menuHtml = angular.element(menu).remove().html().trim(); } return function(scope, element, attrs) { element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__menu ons-sliding-menu-inner')); element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__main ons-sliding-menu-inner')); var slidingMenu = new SlidingMenuView(scope, element, attrs); $onsen.registerEventHandlers(slidingMenu, 'preopen preclose postopen postclose init show hide destroy'); if (mainHtml && !attrs.mainPage) { slidingMenu._appendMainPage(null, mainHtml); } if (menuHtml && !attrs.menuPage) { slidingMenu._appendMenuPage(menuHtml); } $onsen.declareVarAttribute(attrs, slidingMenu); element.data('ons-sliding-menu', slidingMenu); scope.$on('$destroy', function(){ slidingMenu._events = undefined; element.data('ons-sliding-menu', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id speed-dial * @name ons-speed-dial * @category speeddial * @description * [en]Element that displays a Material Design Speed Dialog component.[/en] * [ja]Material DesignのSpeed dialコンポーネントを表現する要素です。[/ja] * @codepen dYQYLg * @seealso ons-speed-dial-item * [en]ons-speed-dial-item component[/en] * [ja]ons-speed-dial-itemコンポーネント[/ja] * @example * <ons-speed-dial position="left bottom"> * <ons-icon * icon="fa-twitter" * size="26px" * fixed-width="false" * style="vertical-align:middle;"> * </ons-icon> * <ons-speed-dial-item><ons-ripple></ons-ripple>C</ons-speed-dial-item> * <ons-speed-dial-item><ons-ripple></ons-ripple>B</ons-speed-dial-item> * <ons-speed-dial-item><ons-ripple></ons-ripple>A</ons-speed-dial-item> * </ons-speed-dial> */ /** * @ngdoc attribute * @name position * @type {String} * @description * [en] * Specify the vertical and horizontal position of the component. * I.e. to display it in the top right corner specify "right top". * Choose from "right", "left", "top" and "bottom". * [/en] * [ja] * この要素を表示する左右と上下の位置を指定します。 * 例えば、右上に表示する場合には"right top"を指定します。 * 左右と上下の位置の指定には、rightとleft、topとbottomがそれぞれ指定できます。 * [/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en]Specify the direction the items are displayed. Possible values are "up", "down", "left" and "right".[/en] * [ja] * 要素が表示する方向を指定します。up, down, left, rightが指定できます。 * [/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Specify if button should be disabled.[/en] * [ja]無効化する場合に指定します。[/ja] */ /** * @ngdoc method * @signature show() * @description * [en]Show the speed dial.[/en] * [ja]Speed dialを表示します。[/ja] */ /** * @ngdoc method * @signature hide() * @description * [en]Hide the speed dial.[/en] * [ja]Speed dialを非表示にします。[/ja] */ /** * @ngdoc method * @signature showItems() * @description * [en]Show the speed dial items.[/en] * [ja]Speed dialの子要素を表示します。[/ja] */ /** * @ngdoc method * @signature hideItems() * @description * [en]Hide the speed dial items.[/en] * [ja]Speed dialの子要素を非表示にします。[/ja] */ /** * @ngdoc method * @signature toggle() * @description * [en]Toggle visibility.[/en] * [ja]Speed dialの表示非表示を切り替えます。[/ja] */ /** * @ngdoc method * @signature toggleItems() * @description * [en]Toggle item visibility.[/en] * [ja]Speed dialの子要素の表示非表示を切り替えます。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the element.[/en] * [ja]disabled状態にするかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the element is disabled.[/en] * [ja]disabled状態になっているかどうかを返します。[/ja] * @description * [en]Returns whether the component is enabled or not.[/en] * [ja]この要素を無効化するかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isInline() * @description * [en]Returns whether the component is inline or not.[/en] * [ja]この要素がインライン要素かどうかを返します。[/ja] */ /** * @ngdoc method * @signature isShown() * @return {Boolean} * [en]True if the component is visible.[/en] * [ja]表示されているかどうかを返します。[/ja] * @description * [en]Return whether the component is visible or not.[/en] * [ja]表示されているかどうかを返します。[/ja] */ /** * @ngdoc directive * @id speed-dial-item * @name ons-speed-dial-item * @category speeddial * @description * [en]This component displays the child elements of the Material Design Speed dial component.[/en] * [ja]Material DesignのSpeed dialの子要素を表現する要素です。[/ja] * @codepen dYQYLg * @seealso ons-speed-dial * [en]ons-speed-dial component[/en] * [ja]ons-speed-dialコンポーネント[/ja] * @example * <ons-speed-dial position="left bottom"> * <ons-icon * icon="fa-twitter" * size="26px" * fixed-width="false" * style="vertical-align:middle;"> * </ons-icon> * <ons-speed-dial-item><ons-ripple></ons-ripple>C</ons-speed-dial-item> * <ons-speed-dial-item><ons-ripple></ons-ripple>B</ons-speed-dial-item> * <ons-speed-dial-item><ons-ripple></ons-ripple>A</ons-speed-dial-item> * </ons-speed-dial> */ /** * @ngdoc directive * @id split-view * @name ons-split-view * @extensionOf angular * @category control * @description * [en]Divides the screen into a left and right section.[/en] * [ja]画面を左右に分割するコンポーネントです。[/ja] * @codepen nKqfv {wide} * @guide Usingonssplitviewcomponent * [en]Using ons-split-view.[/en] * [ja]ons-split-viewコンポーネントを使う[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @example * <ons-split-view * secondary-page="secondary.html" * main-page="main.html" * main-page-width="70%" * collapse="portrait"> * </ons-split-view> */ /** * @ngdoc event * @name update * @description * [en]Fired when the split view is updated.[/en] * [ja]split viewの状態が更新された際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Boolean} event.shouldCollapse * [en]True if the view should collapse.[/en] * [ja]collapse状態の場合にtrueになります。[/ja] * @param {String} event.currentMode * [en]Current mode.[/en] * [ja]現在のモード名を返します。"collapse"か"split"かのいずれかです。[/ja] * @param {Function} event.split * [en]Call to force split.[/en] * [ja]この関数を呼び出すと強制的にsplitモードにします。[/ja] * @param {Function} event.collapse * [en]Call to force collapse.[/en] * [ja]この関数を呼び出すと強制的にcollapseモードにします。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewの幅を返します。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"かもしくは"landscape"です。 [/ja] */ /** * @ngdoc event * @name presplit * @description * [en]Fired just before the view is split.[/en] * [ja]split状態にる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name postsplit * @description * [en]Fired just after the view is split.[/en] * [ja]split状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name precollapse * @description * [en]Fired just before the view is collapsed.[/en] * [ja]collapse状態になる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name postcollapse * @description * [en]Fired just after the view is collapsed.[/en] * [ja]collapse状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @type {String} * @description * [en]Variable name to refer this split view.[/en] * [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @initonly * @name main-page * @type {String} * @description * [en]The url of the page on the right.[/en] * [ja]右側に表示するページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name main-page-width * @initonly * @type {Number} * @description * [en]Main page width percentage. The secondary page width will be the remaining percentage.[/en] * [ja]右側のページの幅をパーセント単位で指定します。[/ja] */ /** * @ngdoc attribute * @name secondary-page * @initonly * @type {String} * @description * [en]The url of the page on the left.[/en] * [ja]左側に表示するページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name collapse * @initonly * @type {String} * @description * [en] * Specify the collapse behavior. Valid values are portrait, landscape, width #px or a media query. * "portrait" or "landscape" means the view will collapse when device is in landscape or portrait orientation. * "width #px" means the view will collapse when the window width is smaller than the specified #px. * If the value is a media query, the view will collapse when the media query is true. * [/en] * [ja] * 左側のページを非表示にする条件を指定します。portrait, landscape、width #pxもしくはメディアクエリの指定が可能です。 * portraitもしくはlandscapeを指定すると、デバイスの画面が縦向きもしくは横向きになった時に適用されます。 * width #pxを指定すると、画面が指定した横幅よりも短い場合に適用されます。 * メディアクエリを指定すると、指定したクエリに適合している場合に適用されます。 * [/ja] */ /** * @ngdoc attribute * @name ons-update * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "update" event is fired.[/en] * [ja]"update"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-presplit * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "presplit" event is fired.[/en] * [ja]"presplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-precollapse * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "precollapse" event is fired.[/en] * [ja]"precollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postsplit * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postsplit" event is fired.[/en] * [ja]"postsplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postcollapse * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postcollapse" event is fired.[/en] * [ja]"postcollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setMainPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the right section[/en] * [ja]指定したURLをメインページを読み込みます。[/ja] */ /** * @ngdoc method * @signature setSecondaryPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the left section[/en] * [ja]指定したURLを左のページの読み込みます。[/ja] */ /** * @ngdoc method * @signature update() * @description * [en]Trigger an 'update' event and try to determine if the split behavior should be changed.[/en] * [ja]splitモードを変えるべきかどうかを判断するための'update'イベントを発火します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsSplitView', ['$compile', 'SplitView', '$onsen', function($compile, SplitView, $onsen) { return { restrict: 'E', replace: false, transclude: false, scope: true, compile: function(element, attrs) { var mainPage = element[0].querySelector('.main-page'), secondaryPage = element[0].querySelector('.secondary-page'); if (mainPage) { var mainHtml = angular.element(mainPage).remove().html().trim(); } if (secondaryPage) { var secondaryHtml = angular.element(secondaryPage).remove().html().trim(); } return function(scope, element, attrs) { element.append(angular.element('<div></div>').addClass('onsen-split-view__secondary full-screen ons-split-view-inner')); element.append(angular.element('<div></div>').addClass('onsen-split-view__main full-screen ons-split-view-inner')); var splitView = new SplitView(scope, element, attrs); if (mainHtml && !attrs.mainPage) { splitView._appendMainPage(mainHtml); } if (secondaryHtml && !attrs.secondaryPage) { splitView._appendSecondPage(secondaryHtml); } $onsen.declareVarAttribute(attrs, splitView); $onsen.registerEventHandlers(splitView, 'update presplit precollapse postsplit postcollapse init show hide destroy'); element.data('ons-split-view', splitView); scope.$on('$destroy', function() { splitView._events = undefined; element.data('ons-split-view', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id splitter * @name ons-splitter * @category control * @description * [en]A component that enables responsive layout by implementing both a two-column layout and a sliding menu layout.[/en] * [ja]sliding-menuとsplit-view両方の機能を持つレイアウトです。[/ja] * @codepen rOQOML * @guide CallingComponentAPIsfromJavaScript * [en]Using components from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @example * <ons-splitter> * <ons-splitter-content> * ... * </ons-splitter-content> * * <ons-splitter-side side="left" width="80%" collapse> * ... * </ons-splitter-side> * </ons-splitter> */ /** * @ngdoc attribute * @name var * @extensionOf angular * @initonly * @type {String} * @description * [en]Variable name to refer this split view.[/en] * [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature openRight([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Open right ons-splitter-side menu on collapse mode.[/en] * [ja]右のcollapseモードになっているons-splitter-side要素を開きます。[/ja] */ /** * @ngdoc method * @signature openLeft([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Open left ons-splitter-side menu on collapse mode.[/en] * [ja]左のcollapseモードになっているons-splitter-side要素を開きます。[/ja] */ /** * @ngdoc method * @signature closeRight([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Close right ons-splitter-side menu on collapse mode.[/en] * [ja]右のcollapseモードになっているons-splitter-side要素を閉じます。[/ja] */ /** * @ngdoc method * @signature closeLeft([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Close left ons-splitter-side menu on collapse mode.[/en] * [ja]左のcollapseモードになっているons-splitter-side要素を閉じます。[/ja] */ /** * @ngdoc method * @signature loadContentPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the ons-splitter-content pane.[/en] * [ja]ons-splitter-content用紙に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature loadContentPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the ons-splitter-content pane.[/en] * [ja]ons-splitter-content用紙に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature leftIsOpened() * @return {Boolean} * [en]Whether the left ons-splitter-side on collapse mode is opened.[/en] * [ja]左のons-splitter-sideが開いているかどうかを返します。[/ja] * @description * [en]Determines whether the left ons-splitter-side on collapse mode is opened.[/en] * [ja]左のons-splitter-side要素が開いているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature rightIsOpened() * @return {Boolean} * [en]Whether the right ons-splitter-side on collapse mode is opened.[/en] * [ja]右のons-splitter-sideが開いているかどうかを返します。[/ja] * @description * [en]Determines whether the right ons-splitter-side on collapse mode is opened.[/en] * [ja]右のons-splitter-side要素が開いているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back-button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back-button handler.[/en] * [ja]ons-splitter要素に紐付いているバックボタンハンドラを取得します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsSplitter', ['$compile', 'Splitter', '$onsen', function($compile, Splitter, $onsen) { return { restrict: 'E', scope: true, compile: function(element, attrs) { CustomElements.upgrade(element[0]); return function(scope, element, attrs) { CustomElements.upgrade(element[0]); var splitter = new Splitter(scope, element, attrs); $onsen.declareVarAttribute(attrs, splitter); $onsen.registerEventHandlers(splitter, 'destroy'); element.data('ons-splitter', splitter); scope.$on('$destroy', function() { splitter._events = undefined; element.data('ons-splitter', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id splitter-content * @name ons-splitter-content * @category control * @description * [en]The "ons-splitter-content" element is used as a child element of "ons-splitter".[/en] * [ja]ons-splitter-content要素は、ons-splitter要素の子要素として利用します。[/ja] * @codepen rOQOML * @example * <ons-splitter> * <ons-splitter-content> * ... * </ons-splitter-content> * * <ons-splitter-side side="left" width="80%" collapse> * ... * </ons-splitter-side> * </ons-splitter> */ /** * @ngdoc attribute * @name ons-destroy * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name page * @initonly * @type {String} * @description * [en]The url of the menu page.[/en] * [ja]ons-splitter-side要素に表示するページのURLを指定します。[/ja] */ /** * @ngdoc method * @signature load(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the right section[/en] * [ja]指定したURLをメインページを読み込みます。[/ja] */ (function() { 'use strict'; var lastReady = window.OnsSplitterContentElement.rewritables.ready; window.OnsSplitterContentElement.rewritables.ready = ons._waitDiretiveInit('ons-splitter-content', lastReady); var lastLink = window.OnsSplitterContentElement.rewritables.link; window.OnsSplitterContentElement.rewritables.link = function(element, target, callback) { var view = angular.element(element).data('ons-splitter-content'); lastLink(element, target, function(target) { view._link(target, callback); }); }; angular.module('onsen').directive('onsSplitterContent', ['$compile', 'SplitterContent', '$onsen', function($compile, SplitterContent, $onsen) { return { restrict: 'E', compile: function(element, attrs) { CustomElements.upgrade(element[0]); return function(scope, element, attrs) { CustomElements.upgrade(element[0]); var view = new SplitterContent(scope, element, attrs); $onsen.declareVarAttribute(attrs, view); $onsen.registerEventHandlers(view, 'destroy'); element.data('ons-splitter-content', view); scope.$on('$destroy', function() { view._events = undefined; element.data('ons-splitter-content', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id splitter-side * @name ons-splitter-side * @category control * @description * [en]The "ons-splitter-side" element is used as a child element of "ons-splitter".[/en] * [ja]ons-splitter-side要素は、ons-splitter要素の子要素として利用します。[/ja] * @codepen rOQOML * @example * <ons-splitter> * <ons-splitter-content> * ... * </ons-splitter-content> * * <ons-splitter-side side="left" width="80%" collapse> * ... * </ons-splitter-side> * </ons-splitter> */ /** * @ngdoc event * @name modechange * @description * [en]Fired just after the component's mode changes.[/en] * [ja]この要素のモードが変化した際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.side * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {String} event.mode * [en]Returns the current mode. Can be either "collapse" or "split".[/en] * [ja]現在のモードを返します。[/ja] */ /** * @ngdoc event * @name preopen * @description * [en]Fired just before the sliding menu is opened.[/en] * [ja]スライディングメニューが開く前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Function} event.cancel * [en]Call to cancel opening sliding menu.[/en] * [ja]スライディングメニューが開くのをキャンセルします。[/ja] * @param {Object} event.side * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name postopen * @description * [en]Fired just after the sliding menu is opened.[/en] * [ja]スライディングメニューが開いた後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.side * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name preclose * @description * [en]Fired just before the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.side * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call to cancel opening sliding-menu.[/en] * [ja]スライディングメニューが閉じるのをキャンセルします。[/ja] */ /** * @ngdoc event * @name postclose * @description * [en]Fired just after the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じた後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.side * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name animation * @initonly * @type {String} * @description * [en]Specify the animation. Use one of "overlay", and "default".[/en] * [ja]アニメーションを指定します。"overlay", "default"のいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc attribute * @name threshold-ratio-should-open * @type {Number} * @description * [en]Specify how much the menu needs to be swiped before opening. A value between 0 and 1. Default is 0.3.[/en] * [ja]どのくらいスワイプすればスライディングメニューを開くかどうかの割合を指定します。0から1の間の数値を指定します。スワイプの距離がここで指定した数値掛けるこの要素の幅よりも大きければ、スワイプが終わった時にこの要素を開きます。デフォルトは0.3です。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preopen * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en] * [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preclose * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en] * [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postopen * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en] * [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postclose * @extensionOf angular * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en] * [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name collapse * @type {String} * @description * [en] * Specify the collapse behavior. Valid values are "portrait", "landscape" or a media query. * "portrait" or "landscape" means the view will collapse when device is in landscape or portrait orientation. * If the value is a media query, the view will collapse when the media query is true. * If the value is not defined, the view always be in "collapse" mode. * [/en] * [ja] * 左側のページを非表示にする条件を指定します。portrait, landscape、width #pxもしくはメディアクエリの指定が可能です。 * portraitもしくはlandscapeを指定すると、デバイスの画面が縦向きもしくは横向きになった時に適用されます。 * メディアクエリを指定すると、指定したクエリに適合している場合に適用されます。 * 値に何も指定しない場合には、常にcollapseモードになります。 * [/ja] */ /** * @ngdoc attribute * @name swipe-target-width * @type {String} * @description * [en]The width of swipeable area calculated from the edge (in pixels). Use this to enable swipe only when the finger touch on the screen edge.[/en] * [ja]スワイプの判定領域をピクセル単位で指定します。画面の端から指定した距離に達するとページが表示されます。[/ja] */ /** * @ngdoc attribute * @name width * @type {String} * @description * [en]Can be specified in either pixels or as a percentage, e.g. "90%" or "200px".[/en] * [ja]この要素の横幅を指定します。pxと%での指定が可能です。eg. 90%, 200px[/ja] */ /** * @ngdoc attribute * @name side * @type {String} * @description * [en]Specify which side of the screen the ons-splitter-side element is located on. Possible values are "left" and "right".[/en] * [ja]この要素が左か右かを指定します。指定できる値は"left"か"right"のみです。[/ja] */ /** * @ngdoc attribute * @name mode * @type {String} * @description * [en]Current mode. Possible values are "collapse" or "split". This attribute is read only.[/en] * [ja]現在のモードが設定されます。"collapse"もしくは"split"が指定されます。この属性は読み込み専用です。[/ja] */ /** * @ngdoc attribute * @name page * @initonly * @type {String} * @description * [en]The url of the menu page.[/en] * [ja]ons-splitter-side要素に表示するページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name swipeable * @type {Boolean} * @description * [en]Whether to enable swipe interaction on collapse mode.[/en] * [ja]collapseモード時にスワイプ操作を有効にする場合に指定します。[/ja] */ /** * @ngdoc method * @signature load(page) * @param {String} page * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the right section[/en] * [ja]指定したURLをメインページを読み込みます。[/ja] */ /** * @ngdoc method * @signature open([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Open menu in collapse mode.[/en] * [ja]collapseモードになっているons-splitterside要素を開きます。[/ja] */ /** * @ngdoc method * @signature close([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Close menu in collapse mode.[/en] * [ja]collapseモードになっているons-splitter-side要素を閉じます。[/ja] */ /** * @ngdoc method * @signature getCurrentMode() * @return {String} * [en]Get current mode. Possible values are "collapse" or "split".[/en] * [ja]このons-splitter-side要素の現在のモードを返します。"split"かもしくは"collapse"のどちらかです。[/ja] */ (function() { 'use strict'; var lastReady = window.OnsSplitterSideElement.rewritables.ready; window.OnsSplitterSideElement.rewritables.ready = ons._waitDiretiveInit('ons-splitter-side', lastReady); var lastLink = window.OnsSplitterSideElement.rewritables.link; window.OnsSplitterSideElement.rewritables.link = function(element, target, callback) { var view = angular.element(element).data('ons-splitter-side'); lastLink(element, target, function(target) { view._link(target, callback); }); }; angular.module('onsen').directive('onsSplitterSide', ['$compile', 'SplitterSide', '$onsen', function($compile, SplitterSide, $onsen) { return { restrict: 'E', compile: function(element, attrs) { CustomElements.upgrade(element[0]); return function(scope, element, attrs) { CustomElements.upgrade(element[0]); var view = new SplitterSide(scope, element, attrs); $onsen.declareVarAttribute(attrs, view); $onsen.registerEventHandlers(view, 'destroy'); element.data('ons-splitter-side', view); scope.$on('$destroy', function() { view._events = undefined; element.data('ons-splitter-side', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id switch * @name ons-switch * @category form * @description * [en]Switch component. Can display either an iOS flat switch or a Material Design switch.[/en] * [ja]スイッチを表示するコンポーネントです。[/ja] * @codepen LpXZQQ * @guide UsingFormComponents * [en]Using form components[/en] * [ja]フォームを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @seealso ons-button * [en]ons-button component[/en] * [ja]ons-buttonコンポーネント[/ja] * @example * <ons-switch checked></ons-switch> * <ons-switch modifier="material"></ons-switch> */ /** * @ngdoc event * @name change * @description * [en]Fired when the value is changed.[/en] * [ja]ON/OFFが変わった時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.switch * [en]Switch object.[/en] * [ja]イベントが発火したSwitchオブジェクトを返します。[/ja] * @param {Boolean} event.value * [en]Current value.[/en] * [ja]現在の値を返します。[/ja] * @param {Boolean} event.isInteractive * [en]True if the change was triggered by the user clicking on the switch.[/en] * [ja]タップやクリックなどのユーザの操作によって変わった場合にはtrueを返します。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this switch.[/en] * [ja]JavaScriptから参照するための変数名を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the switch.[/en] * [ja]スイッチの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Whether the switch should be disabled.[/en] * [ja]スイッチを無効の状態にする場合に指定します。[/ja] */ /** * @ngdoc attribute * @name checked * @description * [en]Whether the switch is checked.[/en] * [ja]スイッチがONの状態にするときに指定します。[/ja] */ /** * @ngdoc method * @signature isChecked() * @return {Boolean} * [en]true if the switch is on.[/en] * [ja]ONになっている場合にはtrueになります。[/ja] * @description * [en]Returns true if the switch is ON.[/en] * [ja]スイッチがONの場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature setChecked(checked) * @param {Boolean} checked * [en]If true the switch will be set to on.[/en] * [ja]ONにしたい場合にはtrueを指定します。[/ja] * @description * [en]Set the value of the switch. isChecked can be either true or false.[/en] * [ja]スイッチの値を指定します。isCheckedにはtrueもしくはfalseを指定します。[/ja] */ /** * @ngdoc method * @signature getCheckboxElement() * @return {HTMLElement} * [en]The underlying checkbox element.[/en] * [ja]コンポーネント内部のcheckbox要素になります。[/ja] * @description * [en]Get inner input[type=checkbox] element.[/en] * [ja]スイッチが内包する、input[type=checkbox]の要素を取得します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function(){ 'use strict'; angular.module('onsen').directive('onsSwitch', ['$onsen', 'SwitchView', function($onsen, SwitchView) { return { restrict: 'E', replace: false, scope: true, link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } var switchView = new SwitchView(element, scope, attrs); $onsen.addModifierMethodsForCustomElements(switchView, element); $onsen.declareVarAttribute(attrs, switchView); element.data('ons-switch', switchView); $onsen.cleaner.onDestroy(scope, function() { switchView._events = undefined; $onsen.removeModifierMethods(switchView); element.data('ons-switch', undefined); $onsen.clearComponent({ element : element, scope : scope, attrs : attrs }); element = attrs = scope = null; }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id tabbar_item * @name ons-tab * @category navigation * @description * [en]Represents a tab inside tabbar. Each ons-tab represents a page.[/en] * [ja] * タブバーに配置される各アイテムのコンポーネントです。それぞれのons-tabはページを表します。 * ons-tab要素の中には、タブに表示されるコンテンツを直接記述することが出来ます。 * [/ja] * @codepen pGuDL * @guide UsingTabBar * [en]Using tab bar[/en] * [ja]タブバーを使う[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-tabbar * [en]ons-tabbar component[/en] * [ja]ons-tabbarコンポーネント[/ja] * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @seealso ons-icon * [en]ons-icon component[/en] * [ja]ons-iconコンポーネント[/ja] * @example * <ons-tabbar> * <ons-tab page="home.html" active="true"> * <ons-icon icon="ion-home"></ons-icon> * <span style="font-size: 14px">Home</span> * </ons-tab> * <ons-tab page="fav.html" active="true"> * <ons-icon icon="ion-star"></ons-icon> * <span style="font-size: 14px">Favorites</span> * </ons-tab> * <ons-tab page="settings.html" active="true"> * <ons-icon icon="ion-gear-a"></ons-icon> * <span style="font-size: 14px">Settings</span> * </ons-tab> * </ons-tabbar> * * <ons-template id="home.html"> * ... * </ons-template> * * <ons-template id="fav.html"> * ... * </ons-template> * * <ons-template id="settings.html"> * ... * </ons-template> */ /** * @ngdoc attribute * @name page * @initonly * @type {String} * @description * [en]The page that this <code>&lt;ons-tab&gt;</code> points to.[/en] * [ja]<code>&lt;ons-tab&gt;</code>が参照するページへのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name icon * @type {String} * @description * [en] * The icon name for the tab. Can specify the same icon name as <code>&lt;ons-icon&gt;</code>. * If you need to use your own icon, create a css class with background-image or any css properties and specify the name of your css class here. * [/en] * [ja] * アイコン名を指定します。<code>&lt;ons-icon&gt;</code>と同じアイコン名を指定できます。 * 個別にアイコンをカスタマイズする場合は、background-imageなどのCSSスタイルを用いて指定できます。 * [/ja] */ /** * @ngdoc attribute * @name active-icon * @type {String} * @description * [en]The name of the icon when the tab is active.[/en] * [ja]アクティブの際のアイコン名を指定します。[/ja] */ /** * @ngdoc attribute * @name label * @type {String} * @description * [en]The label of the tab item.[/en] * [ja]アイコン下に表示されるラベルを指定します。[/ja] */ /** * @ngdoc attribute * @name active * @type {Boolean} * @default false * @description * [en]Set whether this item should be active or not. Valid values are true and false.[/en] * [ja]このタブアイテムをアクティブ状態にするかどうかを指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @ngdoc attribute * @name no-reload * @description * [en]Set if the page shouldn't be reloaded when clicking on the same tab twice.[/en] * [ja]すでにアクティブになったタブを再びクリックするとページの再読み込みは発生しません。[/ja] */ /** * @ngdoc attribute * @name persistent * @description * [en] * Set to make the tab content persistent. * If this attribute it set the DOM will not be destroyed when navigating to another tab. * [/en] * [ja] * このタブで読み込んだページを永続化します。 * この属性があるとき、別のタブのページに切り替えても、 * 読み込んだページのDOM要素は破棄されずに単に非表示になります。 * [/ja] */ (function() { 'use strict'; angular.module('onsen') .directive('onsTab', tab) .directive('onsTabbarItem', tab); // for BC function tab($onsen) { return { restrict: 'E', link: function(scope, element, attrs) { CustomElements.upgrade(element[0]); $onsen.fireComponentEvent(element[0], 'init'); } }; } tab.$inject = ['$onsen']; })(); /** * @ngdoc directive * @id tabbar * @name ons-tabbar * @category navigation * @description * [en]A component to display a tab bar on the bottom of a page. Used with ons-tab to manage pages using tabs.[/en] * [ja]タブバーをページ下部に表示するためのコンポーネントです。ons-tabと組み合わせて使うことで、ページを管理できます。[/ja] * @codepen pGuDL * @guide UsingTabBar * [en]Using tab bar[/en] * [ja]タブバーを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-tab * [en]ons-tab component[/en] * [ja]ons-tabコンポーネント[/ja] * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @example * <ons-tabbar> * <ons-tab page="home.html" active="true"> * <ons-icon icon="ion-home"></ons-icon> * <span style="font-size: 14px">Home</span> * </ons-tab> * <ons-tab page="fav.html" active="true"> * <ons-icon icon="ion-star"></ons-icon> * <span style="font-size: 14px">Favorites</span> * </ons-tab> * <ons-tab page="settings.html" active="true"> * <ons-icon icon="ion-gear-a"></ons-icon> * <span style="font-size: 14px">Settings</span> * </ons-tab> * </ons-tabbar> * * <ons-template id="home.html"> * ... * </ons-template> * * <ons-template id="fav.html"> * ... * </ons-template> * * <ons-template id="settings.html"> * ... * </ons-template> */ /** * @ngdoc event * @name prechange * @description * [en]Fires just before the tab is changed.[/en] * [ja]アクティブなタブが変わる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the change event.[/en] * [ja]この関数を呼び出すと、アクティブなタブの変更がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postchange * @description * [en]Fires just after the tab is changed.[/en] * [ja]アクティブなタブが変わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] */ /** * @ngdoc event * @name reactive * @description * [en]Fires if the already open tab is tapped again.[/en] * [ja]すでにアクティブになっているタブがもう一度タップやクリックされた場合に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this tab bar.[/en] * [ja]このタブバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name hide-tabs * @initonly * @extensionOf angular * @type {Boolean} * @default false * @description * [en]Whether to hide the tabs. Valid values are true/false.[/en] * [ja]タブを非表示にする場合に指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default none * @description * [en]Animation name. Preset values are "none", "slide" and "fade". Default is "none".[/en] * [ja]ページ読み込み時のアニメーションを指定します。"none"、"fade"、"slide"のいずれかを選択できます。デフォルトは"none"です。[/ja] */ /** * @ngdoc attribute * @name animation-options * @type {Expression} * @description * [en]Specify the animation's duration, timing and delay with an object literal. E.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja] */ /** * @ngdoc attribute * @name position * @initonly * @type {String} * @default bottom * @description * [en]Tabbar's position. Preset values are "bottom" and "top". Default is "bottom".[/en] * [ja]タブバーの位置を指定します。"bottom"もしくは"top"を選択できます。デフォルトは"bottom"です。[/ja] */ /** * @ngdoc attribute * @name ons-reactive * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "reactive" event is fired.[/en] * [ja]"reactive"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prechange * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prechange" event is fired.[/en] * [ja]"prechange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postchange * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-init * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-show * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-hide * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @initonly * @extensionOf angular * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setActiveTab(index, [options]) * @param {Number} index * [en]Tab index.[/en] * [ja]タブのインデックスを指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.keepPage] * [en]If true the page will not be changed.[/en] * [ja]タブバーが現在表示しているpageを変えない場合にはtrueを指定します。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade", "slide" and "none".[/en] * [ja]アニメーション名を指定します。"fade"、"slide"、"none"のいずれかを指定できます。[/ja] * @param {String} [options.animationOptions] * [en]Specify the animation's duration, delay and timing. E.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code>[/en] * [ja]アニメーション時のduration, delay, timingを指定します。e.g. <code>{duration: 0.2, delay: 0.4, timing: 'ease-in'}</code> [/ja] * @return {Boolean} * [en]true if the change was successful.[/en] * [ja]変更が成功した場合にtrueを返します。[/ja] * @description * [en]Show specified tab page. Animations and other options can be specified by the second parameter.[/en] * [ja]指定したインデックスのタブを表示します。アニメーションなどのオプションを指定できます。[/ja] */ /** * @ngdoc method * @signature getActiveTabIndex() * @return {Number} * [en]The index of the currently active tab.[/en] * [ja]現在アクティブになっているタブのインデックスを返します。[/ja] * @description * [en]Returns tab index on current active tab. If active tab is not found, returns -1.[/en] * [ja]現在アクティブになっているタブのインデックスを返します。現在アクティブなタブがない場合には-1を返します。[/ja] */ /** * @ngdoc method * @signature loadPage(url) * @param {String} url * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくは<code>&lt;ons-template&gt;</code>で宣言したid属性の値を利用できます。[/ja] * @description * [en]Displays a new page without changing the active index.[/en] * [ja]現在のアクティブなインデックスを変更せずに、新しいページを表示します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @extensionOf angular * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @extensionOf angular * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var lastReady = window.OnsTabbarElement.rewritables.ready; window.OnsTabbarElement.rewritables.ready = ons._waitDiretiveInit('ons-tabbar', lastReady); var lastLink = window.OnsTabbarElement.rewritables.link; window.OnsTabbarElement.rewritables.link = function(tabbarElement, target, callback) { var view = angular.element(tabbarElement).data('ons-tabbar'); view._compileAndLink(target, function(target) { lastLink(tabbarElement, target, callback); }); }; var lastUnlink = window.OnsTabbarElement.rewritables.unlink; window.OnsTabbarElement.rewritables.unlink = function(tabbarElement, target, callback) { angular.element(target).data('_scope').$destroy(); lastUnlink(tabbarElement, target, callback); }; angular.module('onsen').directive('onsTabbar', ['$onsen', '$compile', '$parse', 'TabbarView', function($onsen, $compile, $parse, TabbarView) { return { restrict: 'E', replace: false, scope: true, link: function(scope, element, attrs, controller) { CustomElements.upgrade(element[0]); scope.$watch(attrs.hideTabs, function(hide) { if (typeof hide === 'string') { hide = hide === 'true'; } element[0].setTabbarVisibility(!hide); }); var tabbarView = new TabbarView(scope, element, attrs); $onsen.addModifierMethodsForCustomElements(tabbarView, element); $onsen.registerEventHandlers(tabbarView, 'reactive prechange postchange init show hide destroy'); element.data('ons-tabbar', tabbarView); $onsen.declareVarAttribute(attrs, tabbarView); scope.$on('$destroy', function() { tabbarView._events = undefined; $onsen.removeModifierMethods(tabbarView); element.data('ons-tabbar', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id template * @name ons-template * @category util * @description * [en]Define a separate HTML fragment and use as a template.[/en] * [ja]テンプレートとして使用するためのHTMLフラグメントを定義します。この要素でHTMLを宣言すると、id属性に指定した名前をpageのURLとしてons-navigatorなどのコンポーネントから参照できます。[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-template id="foobar.html"> * ... * </ons-template> */ (function(){ 'use strict'; angular.module('onsen').directive('onsTemplate', ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element) { CustomElements.upgrade(element[0]); var content = element[0].template || element.html(); $templateCache.put(element.attr('id'), content); } }; }]); })(); /** * @ngdoc directive * @id toolbar * @name ons-toolbar * @category page * @modifier transparent * [en]Transparent toolbar[/en] * [ja]透明な背景を持つツールバーを表示します。[/ja] * @modifier android * [en]Android style toolbar. Title is left-aligned.[/en] * [ja]Androidライクなツールバーを表示します。タイトルが左に寄ります。[/ja] * @description * [en]Toolbar component that can be used with navigation. Left, center and right container can be specified by class names.[/en] * [ja]ナビゲーションで使用するツールバー用コンポーネントです。クラス名により、左、中央、右のコンテナを指定できます。[/ja] * @codepen aHmGL * @guide Addingatoolbar [en]Adding a toolbar[/en][ja]ツールバーの追加[/ja] * @seealso ons-bottom-toolbar * [en]ons-bottom-toolbar component[/en] * [ja]ons-bottom-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @seealso ons-toolbar-button * [en]ons-toolbar-button component[/en] * [ja]ons-toolbar-buttonコンポーネント[/ja] * @example * <ons-page> * <ons-toolbar> * <div class="left"><ons-back-button>Back</ons-back-button></div> * <div class="center">Title</div> * <div class="right">Label</div> * </ons-toolbar> * </ons-page> */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this toolbar.[/en] * [ja]このツールバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name inline * @initonly * @description * [en]Display the toolbar as an inline element.[/en] * [ja]ツールバーをインラインに置きます。スクロール領域内にそのまま表示されます。[/ja] */ /** * @ngdoc attribute * @name modifier * @description * [en]The appearance of the toolbar.[/en] * [ja]ツールバーの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name fixed-style * @initonly * @description * [en] * By default the center element will be left-aligned on Android and center-aligned on iOS. * Use this attribute to override this behavior so it's always displayed in the center. * [/en] * [ja] * このコンポーネントは、Androidではタイトルを左寄せ、iOSでは中央配置します。 * この属性を使用すると、要素はAndroidとiOSともに中央配置となります。 * [/ja] */ (function() { 'use strict'; angular.module('onsen').directive('onsToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function(element) { CustomElements.upgrade(element[0]); return { pre: function(scope, element, attrs) { // TODO: Remove this dirty fix! if (element[0].nodeName === 'ons-toolbar') { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, {viewKey: 'ons-toolbar'}); element[0]._ensureNodePosition(); } }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id toolbar_button * @name ons-toolbar-button * @category page * @modifier outline * [en]A button with an outline.[/en] * [ja]アウトラインをもったボタンを表示します。[/ja] * @description * [en]Button component for ons-toolbar and ons-bottom-toolbar.[/en] * [ja]ons-toolbarあるいはons-bottom-toolbarに設置できるボタン用コンポーネントです。[/ja] * @codepen aHmGL * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @seealso ons-toolbar-button * [en]ons-toolbar-button component[/en] * [ja]ons-toolbar-buttonコンポーネント[/ja] * @example * <ons-toolbar> * <div class="left"><ons-toolbar-button>Button</ons-toolbar-button></div> * <div class="center">Title</div> * <div class="right"><ons-toolbar-button><ons-icon icon="ion-navicon" size="28px"></ons-icon></ons-toolbar-button></div> * </ons-toolbar> */ /** * @ngdoc attribute * @name var * @initonly * @extensionOf angular * @type {String} * @description * [en]Variable name to refer this button.[/en] * [ja]このボタンを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the button.[/en] * [ja]ボタンの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Specify if button should be disabled.[/en] * [ja]ボタンを無効化する場合は指定してください。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsToolbarButton', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', scope: false, link: { pre: function(scope, element, attrs) { CustomElements.upgrade(element[0]); var toolbarButton = new GenericView(scope, element, attrs); element.data('ons-toolbar-button', toolbarButton); $onsen.declareVarAttribute(attrs, toolbarButton); $onsen.addModifierMethodsForCustomElements(toolbarButton, element); $onsen.cleaner.onDestroy(scope, function() { toolbarButton._events = undefined; $onsen.removeModifierMethods(toolbarButton); element.data('ons-toolbar-button', undefined); element = null; $onsen.clearComponent({ scope: scope, attrs: attrs, element: element, }); scope = element = attrs = null; }); }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; var module = angular.module('onsen'); var ComponentCleaner = { /** * @param {jqLite} element */ decomposeNode: function(element) { var children = element.remove().children(); for (var i = 0; i < children.length; i++) { ComponentCleaner.decomposeNode(angular.element(children[i])); } }, /** * @param {Attributes} attrs */ destroyAttributes: function(attrs) { attrs.$$element = null; attrs.$$observers = null; }, /** * @param {jqLite} element */ destroyElement: function(element) { element.remove(); }, /** * @param {Scope} scope */ destroyScope: function(scope) { scope.$$listeners = {}; scope.$$watchers = null; scope = null; }, /** * @param {Scope} scope * @param {Function} fn */ onDestroy: function(scope, fn) { var clear = scope.$on('$destroy', function() { clear(); fn.apply(null, arguments); }); } }; module.factory('ComponentCleaner', function() { return ComponentCleaner; }); // override builtin ng-(eventname) directives (function() { var ngEventDirectives = {}; 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' ').forEach( function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return { compile: function($element, attr) { var fn = $parse(attr[directiveName]); return function(scope, element, attr) { var listener = function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }; element.on(name, listener); ComponentCleaner.onDestroy(scope, function() { element.off(name, listener); element = null; ComponentCleaner.destroyScope(scope); scope = null; ComponentCleaner.destroyAttributes(attr); attr = null; }); }; } }; }]; function directiveNormalize(name) { return name.replace(/-([a-z])/g, function(matches) { return matches[1].toUpperCase(); }); } } ); module.config(['$provide', function($provide) { var shift = function($delegate) { $delegate.shift(); return $delegate; }; Object.keys(ngEventDirectives).forEach(function(directiveName) { $provide.decorator(directiveName + 'Directive', ['$delegate', shift]); }); }]); Object.keys(ngEventDirectives).forEach(function(directiveName) { module.directive(directiveName, ngEventDirectives[directiveName]); }); })(); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; var module = angular.module('onsen'); /** * Internal service class for framework implementation. */ module.factory('$onsen', ['$rootScope', '$window', '$cacheFactory', '$document', '$templateCache', '$http', '$q', '$onsGlobal', 'ComponentCleaner', function($rootScope, $window, $cacheFactory, $document, $templateCache, $http, $q, $onsGlobal, ComponentCleaner) { var $onsen = createOnsenService(); var ModifierUtil = $onsGlobal._internal.ModifierUtil; return $onsen; function createOnsenService() { return { DIRECTIVE_TEMPLATE_URL: 'templates', cleaner: ComponentCleaner, DeviceBackButtonHandler: $onsGlobal._deviceBackButtonDispatcher, _defaultDeviceBackButtonHandler: $onsGlobal._defaultDeviceBackButtonHandler, /** * @return {Object} */ getDefaultDeviceBackButtonHandler: function() { return this._defaultDeviceBackButtonHandler; }, /** * @param {Object} view * @param {Element} element * @param {Array} methodNames * @return {Function} A function that dispose all driving methods. */ deriveMethods: function(view, element, methodNames) { methodNames.forEach(function(methodName) { view[methodName] = function() { return element[methodName].apply(element, arguments); }; }); return function() { methodNames.forEach(function(methodName) { view[methodName] = null; }); view = element = null; }; }, /** * @param {Object} view * @param {Element} element * @param {Array} eventNames * @param {Function} [map] * @return {Function} A function that clear all event listeners */ deriveEvents: function(view, element, eventNames, map) { map = map || function(detail) { return detail; }; eventNames = [].concat(eventNames); var listeners = []; eventNames.forEach(function(eventName) { var listener = function(event) { view.emit(eventName, map(Object.create(event.detail))); }; listeners.push(listener); element.addEventListener(eventName, listener, false); }); return function() { eventNames.forEach(function(eventName, index) { element.removeEventListener(eventName, listeners[index], false); }); view = element = listeners = map = null; }; }, /** * @return {Boolean} */ isEnabledAutoStatusBarFill: function() { return !!$onsGlobal._config.autoStatusBarFill; }, /** * @param {HTMLElement} element * @return {Boolean} */ shouldFillStatusBar: function(element) { return $onsGlobal.shouldFillStatusBar(element); }, /** * @param {Object} params * @param {Scope} [params.scope] * @param {jqLite} [params.element] * @param {Array} [params.elements] * @param {Attributes} [params.attrs] */ clearComponent: function(params) { if (params.scope) { ComponentCleaner.destroyScope(params.scope); } if (params.attrs) { ComponentCleaner.destroyAttributes(params.attrs); } if (params.element) { ComponentCleaner.destroyElement(params.element); } if (params.elements) { params.elements.forEach(function(element) { ComponentCleaner.destroyElement(element); }); } }, /** * @param {jqLite} element * @param {String} name */ findElementeObject: function(element, name) { return element.inheritedData(name); }, /** * @param {String} page * @return {Promise} */ getPageHTMLAsync: function(page) { var cache = $templateCache.get(page); if (cache) { var deferred = $q.defer(); var html = typeof cache === 'string' ? cache : cache[1]; deferred.resolve(this.normalizePageHTML(html)); return deferred.promise; } else { return $http({ url: page, method: 'GET' }).then(function(response) { var html = response.data; return this.normalizePageHTML(html); }.bind(this)); } }, /** * @param {String} html * @return {String} */ normalizePageHTML: function(html) { html = ('' + html).trim(); if (!html.match(/^<ons-page/)) { html = '<ons-page _muted>' + html + '</ons-page>'; } return html; }, /** * Create modifier templater function. The modifier templater generate css classes bound modifier name. * * @param {Object} attrs * @param {Array} [modifiers] an array of appendix modifier * @return {Function} */ generateModifierTemplater: function(attrs, modifiers) { var attrModifiers = attrs && typeof attrs.modifier === 'string' ? attrs.modifier.trim().split(/ +/) : []; modifiers = angular.isArray(modifiers) ? attrModifiers.concat(modifiers) : attrModifiers; /** * @return {String} template eg. 'ons-button--*', 'ons-button--*__item' * @return {String} */ return function(template) { return modifiers.map(function(modifier) { return template.replace('*', modifier); }).join(' '); }; }, /** * Add modifier methods to view object for custom elements. * * @param {Object} view object * @param {jqLite} element */ addModifierMethodsForCustomElements: function(view, element) { var methods = { hasModifier: function(needle) { var tokens = ModifierUtil.split(element.attr('modifier')); needle = typeof needle === 'string' ? needle.trim() : ''; return ModifierUtil.split(needle).some(function(needle) { return tokens.indexOf(needle) != -1; }); }, removeModifier: function(needle) { needle = typeof needle === 'string' ? needle.trim() : ''; var modifier = ModifierUtil.split(element.attr('modifier')).filter(function(token) { return token !== needle; }).join(' '); element.attr('modifier', modifier); }, addModifier: function(modifier) { element.attr('modifier', element.attr('modifier') + ' ' + modifier); }, setModifier: function(modifier) { element.attr('modifier', modifier); }, toggleModifier: function(modifier) { if (this.hasModifier(modifier)) { this.removeModifier(modifier); } else { this.addModifier(modifier); } } }; for (var method in methods) { if (methods.hasOwnProperty(method)) { view[method] = methods[method]; } } }, /** * Add modifier methods to view object. * * @param {Object} view object * @param {String} template * @param {jqLite} element */ addModifierMethods: function(view, template, element) { var _tr = function(modifier) { return template.replace('*', modifier); }; var fns = { hasModifier: function(modifier) { return element.hasClass(_tr(modifier)); }, removeModifier: function(modifier) { element.removeClass(_tr(modifier)); }, addModifier: function(modifier) { element.addClass(_tr(modifier)); }, setModifier: function(modifier) { var classes = element.attr('class').split(/\s+/), patt = template.replace('*', '.'); for (var i=0; i < classes.length; i++) { var cls = classes[i]; if (cls.match(patt)) { element.removeClass(cls); } } element.addClass(_tr(modifier)); }, toggleModifier: function(modifier) { var cls = _tr(modifier); if (element.hasClass(cls)) { element.removeClass(cls); } else { element.addClass(cls); } } }; var append = function(oldFn, newFn) { if (typeof oldFn !== 'undefined') { return function() { return oldFn.apply(null, arguments) || newFn.apply(null, arguments); }; } else { return newFn; } }; view.hasModifier = append(view.hasModifier, fns.hasModifier); view.removeModifier = append(view.removeModifier, fns.removeModifier); view.addModifier = append(view.addModifier, fns.addModifier); view.setModifier = append(view.setModifier, fns.setModifier); view.toggleModifier = append(view.toggleModifier, fns.toggleModifier); }, /** * Remove modifier methods. * * @param {Object} view object */ removeModifierMethods: function(view) { view.hasModifier = view.removeModifier = view.addModifier = view.setModifier = view.toggleModifier = undefined; }, /** * Define a variable to JavaScript global scope and AngularJS scope as 'var' attribute name. * * @param {Object} attrs * @param object */ declareVarAttribute: function(attrs, object) { if (typeof attrs['var'] === 'string') { var varName = attrs['var']; this._defineVar(varName, object); } }, _registerEventHandler: function(component, eventName) { var capitalizedEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1); component.on(eventName, function(event) { $onsen.fireComponentEvent(component._element[0], eventName, event); var handler = component._attrs['ons' + capitalizedEventName]; if (handler) { component._scope.$eval(handler, {$event: event}); component._scope.$evalAsync(); } }); }, /** * Register event handlers for attributes. * * @param {Object} component * @param {String} eventNames */ registerEventHandlers: function(component, eventNames) { eventNames = eventNames.trim().split(/\s+/); for (var i = 0, l = eventNames.length; i < l; i ++) { var eventName = eventNames[i]; this._registerEventHandler(component, eventName); } }, /** * @return {Boolean} */ isAndroid: function() { return !!window.navigator.userAgent.match(/android/i); }, /** * @return {Boolean} */ isIOS: function() { return !!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i); }, /** * @return {Boolean} */ isWebView: function() { return window.ons.isWebView(); }, /** * @return {Boolean} */ isIOS7above: (function() { var ua = window.navigator.userAgent; var match = ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i); var result = match ? parseFloat(match[2] + '.' + match[3]) >= 7 : false; return function() { return result; }; })(), /** * Fire a named event for a component. The view object, if it exists, is attached to event.component. * * @param {HTMLElement} [dom] * @param {String} event name */ fireComponentEvent: function(dom, eventName, data) { data = data || {}; var event = document.createEvent('HTMLEvents'); for (var key in data) { if (data.hasOwnProperty(key)) { event[key] = data[key]; } } event.component = dom ? angular.element(dom).data(dom.nodeName.toLowerCase()) || null : null; event.initEvent(dom.nodeName.toLowerCase() + ':' + eventName, true, true); dom.dispatchEvent(event); }, /** * Define a variable to JavaScript global scope and AngularJS scope. * * Util.defineVar('foo', 'foo-value'); * // => window.foo and $scope.foo is now 'foo-value' * * Util.defineVar('foo.bar', 'foo-bar-value'); * // => window.foo.bar and $scope.foo.bar is now 'foo-bar-value' * * @param {String} name * @param object */ _defineVar: function(name, object) { var names = name.split(/\./); function set(container, names, object) { var name; for (var i = 0; i < names.length - 1; i++) { name = names[i]; if (container[name] === undefined || container[name] === null) { container[name] = {}; } container = container[name]; } container[names[names.length - 1]] = object; if (container[names[names.length -1]] !== object) { throw new Error('Cannot set var="' + object._attrs.var + '" because it will overwrite a read-only variable.'); } } if (ons.componentBase) { set(ons.componentBase, names, object); } // Attach to ancestor with ons-scope attribute. var element = object._element[0]; while (element.parentNode) { if (element.hasAttribute('ons-scope')) { set(angular.element(element).data('_scope'), names, object); element = null; return; } element = element.parentNode; } element = null; // If no ons-scope element was found, attach to $rootScope. set($rootScope, names, object); } }; } }]); })(); // confirm to use jqLite 'use strict'; if (window.jQuery && angular.element === window.jQuery) { console.warn('Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.'); } /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @ngdoc object * @name ons.GestureDetector * @category util * @description * [en]Utility class for gesture detection.[/en] * [ja]ジェスチャを検知するためのユーティリティクラスです。[/ja] */ /** * @ngdoc method * @signature constructor(element[, options]) * @description * [en]Create a new GestureDetector instance.[/en] * [ja]GestureDetectorのインスタンスを生成します。[/ja] * @param {Element} element * [en]Name of the event.[/en] * [ja]ジェスチャを検知するDOM要素を指定します。[/ja] * @param {Object} [options] * [en]Options object.[/en] * [ja]オプションを指定します。[/ja] */ /** * @ngdoc method * @signature on(gestures, handler) * @description * [en]Adds an event handler for a gesture. Available gestures are: drag, dragleft, dragright, dragup, dragdown, hold, release, swipe, swipeleft, swiperight, swipeup, swipedown, tap, doubletap, touch, transform, pinch, pinchin, pinchout and rotate. [/en] * [ja]ジェスチャに対するイベントハンドラを追加します。指定できるジェスチャ名は、drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate です。[/ja] * @param {String} gestures * [en]A space separated list of gestures.[/en] * [ja]検知するジェスチャ名を指定します。スペースで複数指定することができます。[/ja] * @param {Function} handler * [en]An event handling function.[/en] * [ja]イベントハンドラとなる関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(gestures, handler) * @description * [en]Remove an event listener.[/en] * [ja]イベントリスナーを削除します。[/ja] * @param {String} gestures * [en]A space separated list of gestures.[/en] * [ja]ジェスチャ名を指定します。スペースで複数指定することができます。[/ja] * @param {Function} handler * [en]An event handling function.[/en] * [ja]イベントハンドラとなる関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature enable(state) * @description * [en]Enable or disable gesture detection.[/en] * [ja]ジェスチャ検知を有効化/無効化します。[/ja] * @param {Boolean} state * [en]Specify if it should be enabled or not.[/en] * [ja]有効にするかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature dispose() * @description * [en]Remove and destroy all event handlers for this instance.[/en] * [ja]このインスタンスでのジェスチャの検知や、イベントハンドラを全て解除して廃棄します。[/ja] */ /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @ngdoc object * @name ons.notification * @category dialog * @codepen Qwwxyp * @description * [en]Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt.[/en] * [ja]いくつかの種類のアラートダイアログを作成するためのユーティリティメソッドを収めたオブジェクトです。[/ja] * @example * <script> * ons.notification.alert({ * message: 'Hello, world!' * }); * * // Show a Material Design alert dialog. * ons.notification.alert({ * message: 'Hello, world!', * modifier: 'material' * }); * * ons.notification.confirm({ * message: 'Are you ready?', * callback: function(answer) { * // Do something here. * } * }); * * ons.notification.prompt({ * message: 'How old are you?', * callback: function(age) { * ons.notification.alert({ * message: 'You are ' + age + ' years old.' * }); * }); * }); * </script> */ /** * @ngdoc method * @signature alert(options) * @param {Object} options * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.message] * [en]Alert message.[/en] * [ja]アラートダイアログに表示する文字列を指定します。[/ja] * @param {String} [options.messageHTML] * [en]Alert message in HTML.[/en] * [ja]アラートダイアログに表示するHTMLを指定します。[/ja] * @param {String} [options.buttonLabel] * [en]Label for confirmation button. Default is "OK".[/en] * [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アラートダイアログを表示する際のアニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Alert".[/en] * [ja]アラートダイアログの上部に表示するタイトルを指定します。"Alert"がデフォルトです。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]アラートダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en]Function that executes after dialog has been closed.[/en] * [ja]アラートダイアログが閉じられた時に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en] * Display an alert dialog to show the user a message. * The content of the message can be either simple text or HTML. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザーへメッセージを見せるためのアラートダイアログを表示します。 * 表示するメッセージは、テキストかもしくはHTMLを指定できます。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ /** * @ngdoc method * @signature confirm(options) * @param {Object} options * [en]Parameter object.[/en] * @param {String} [options.message] * [en]Confirmation question.[/en] * [ja]確認ダイアログに表示するメッセージを指定します。[/ja] * @param {String} [options.messageHTML] * [en]Dialog content in HTML.[/en] * [ja]確認ダイアログに表示するHTMLを指定します。[/ja] * @param {Array} [options.buttonLabels] * [en]Labels for the buttons. Default is ["Cancel", "OK"].[/en] * [ja]ボタンのラベルの配列を指定します。["Cancel", "OK"]がデフォルトです。[/ja] * @param {Number} [options.primaryButtonIndex] * [en]Index of primary button. Default is 1.[/en] * [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja] * @param {Boolean} [options.cancelable] * [en]Whether the dialog is cancelable or not. Default is false.[/en] * [ja]ダイアログがキャンセル可能かどうかを指定します。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Confirm".[/en] * [ja]ダイアログのタイトルを指定します。"Confirm"がデフォルトです。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]ダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en] * Function that executes after the dialog has been closed. * Argument for the function is the index of the button that was pressed or -1 if the dialog was canceled. * [/en] * [ja] * ダイアログが閉じられた後に呼び出される関数オブジェクトを指定します。 * この関数の引数として、押されたボタンのインデックス値が渡されます。 * もしダイアログがキャンセルされた場合には-1が渡されます。 * [/ja] * @description * [en] * Display a dialog to ask the user for confirmation. * The default button labels are "Cancel" and "OK" but they can be customized. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザに確認を促すダイアログを表示します。 * デオルとのボタンラベルは、"Cancel"と"OK"ですが、これはこのメソッドの引数でカスタマイズできます。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ /** * @ngdoc method * @signature prompt(options) * @param {Object} options * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.message] * [en]Prompt question.[/en] * [ja]ダイアログに表示するメッセージを指定します。[/ja] * @param {String} [options.messageHTML] * [en]Dialog content in HTML.[/en] * [ja]ダイアログに表示するHTMLを指定します。[/ja] * @param {String} [options.buttonLabel] * [en]Label for confirmation button. Default is "OK".[/en] * [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja] * @param {Number} [options.primaryButtonIndex] * [en]Index of primary button. Default is 1.[/en] * [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja] * @param {Boolean} [options.cancelable] * [en]Whether the dialog is cancelable or not. Default is false.[/en] * [ja]ダイアログがキャンセル可能かどうかを指定します。デフォルトは false です。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Alert".[/en] * [ja]ダイアログのタイトルを指定します。デフォルトは "Alert" です。[/ja] * @param {String} [options.placeholder] * [en]Placeholder for the text input.[/en] * [ja]テキスト欄のプレースホルダに表示するテキストを指定します。[/ja] * @param {String} [options.defaultValue] * [en]Default value for the text input.[/en] * [ja]テキスト欄のデフォルトの値を指定します。[/ja] * @param {Boolean} [options.autofocus] * [en]Autofocus the input element. Default is true.[/en] * [ja]input要素に自動的にフォーカスするかどうかを指定します。デフォルトはtrueです。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]ダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en] * Function that executes after the dialog has been closed. * Argument for the function is the value of the input field or null if the dialog was canceled. * [/en] * [ja] * ダイアログが閉じられた後に実行される関数オブジェクトを指定します。 * 関数の引数として、インプット要素の中の値が渡されます。ダイアログがキャンセルされた場合には、nullが渡されます。 * [/ja] * @param {Boolean} [options.submitOnEnter] * [en]Submit automatically when enter is pressed. Default is "true".[/en] * [ja]Enterが押された際にそのformをsubmitするかどうかを指定します。デフォルトはtrueです。[/ja] * @description * [en] * Display a dialog with a prompt to ask the user a question. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザーに入力を促すダイアログを表示します。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ ons.notification.alert = function(options) { var originalCompile = options.compile || function(element) { return element; }; options.compile = function(element) { ons.compile(originalCompile(element)); }; return ons.notification._alertOriginal(options); }; ons.notification.confirm = function(options) { var originalCompile = options.compile || function(element) { return element; }; options.compile = function(element) { ons.compile(originalCompile(element)); }; return ons.notification._confirmOriginal(options); }; ons.notification.prompt = function(options) { var originalCompile = options.compile || function(element) { return element; }; options.compile = function(element) { ons.compile(originalCompile(element)); }; return ons.notification._promptOriginal(options); }; /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @ngdoc object * @name ons.orientation * @category util * @description * [en]Utility methods for orientation detection.[/en] * [ja]画面のオリエンテーション検知のためのユーティリティメソッドを収めているオブジェクトです。[/ja] */ /** * @ngdoc event * @name change * @description * [en]Fired when the device orientation changes.[/en] * [ja]デバイスのオリエンテーションが変化した際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Boolean} event.isPortrait * [en]Will be true if the current orientation is portrait mode.[/en] * [ja]現在のオリエンテーションがportraitの場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature isPortrait() * @return {Boolean} * [en]Will be true if the current orientation is portrait mode.[/en] * [ja]オリエンテーションがportraitモードの場合にtrueになります。[/ja] * @description * [en]Returns whether the current screen orientation is portrait or not.[/en] * [ja]オリエンテーションがportraitモードかどうかを返します。[/ja] */ /** * @ngdoc method * @signature isLandscape() * @return {Boolean} * [en]Will be true if the current orientation is landscape mode.[/en] * [ja]オリエンテーションがlandscapeモードの場合にtrueになります。[/ja] * @description * [en]Returns whether the current screen orientation is landscape or not.[/en] * [ja]オリエンテーションがlandscapeモードかどうかを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @ngdoc object * @name ons.platform * @category util * @description * [en]Utility methods to detect current platform.[/en] * [ja]現在実行されているプラットフォームを検知するためのユーティリティメソッドを収めたオブジェクトです。[/ja] */ /** * @ngdoc method * @signature select(platform) * @param {string} platform Name of the platform. * [en]Possible values are: "opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios" or "wp".[/en] * [ja]"opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios", "wp"のいずれかを指定します。[/ja] * @description * [en]Sets the platform used to render the elements. Useful for testing.[/en] * [ja]要素を描画するために利用するプラットフォーム名を設定します。テストに便利です。[/ja] */ /** * @ngdoc method * @signature isWebView() * @description * [en]Returns whether app is running in Cordova.[/en] * [ja]Cordova内で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIOS() * @description * [en]Returns whether the OS is iOS.[/en] * [ja]iOS上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isAndroid() * @description * [en]Returns whether the OS is Android.[/en] * [ja]Android上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isAndroidPhone() * @description * [en]Returns whether the device is Android phone.[/en] * [ja]Android携帯上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isAndroidTablet() * @description * [en]Returns whether the device is Android tablet.[/en] * [ja]Androidタブレット上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIPhone() * @description * [en]Returns whether the device is iPhone.[/en] * [ja]iPhone上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIPad() * @description * [en]Returns whether the device is iPad.[/en] * [ja]iPad上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isBlackBerry() * @description * [en]Returns whether the device is BlackBerry.[/en] * [ja]BlackBerry上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isOpera() * @description * [en]Returns whether the browser is Opera.[/en] * [ja]Opera上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isFirefox() * @description * [en]Returns whether the browser is Firefox.[/en] * [ja]Firefox上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isSafari() * @description * [en]Returns whether the browser is Safari.[/en] * [ja]Safari上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isChrome() * @description * [en]Returns whether the browser is Chrome.[/en] * [ja]Chrome上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIE() * @description * [en]Returns whether the browser is Internet Explorer.[/en] * [ja]Internet Explorer上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isEdge() * @description * [en]Returns whether the browser is Edge.[/en] * [ja]Edge上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIOS7above() * @description * [en]Returns whether the iOS version is 7 or above.[/en] * [ja]iOS7以上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /* Copyright 2013-2015 ASIAL CORPORATION 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. */ (function(){ 'use strict'; angular.module('onsen').run(['$templateCache', function($templateCache) { var templates = window.document.querySelectorAll('script[type="text/ons-template"]'); for (var i = 0; i < templates.length; i++) { var template = angular.element(templates[i]); var id = template.attr('id'); if (typeof id === 'string') { $templateCache.put(id, template.text()); } } }]); })();
src/dumb/buttons/IconButton.js
jeckhummer/wf-constructor
import React from 'react'; import {Icon, Popup} from "semantic-ui-react"; export class IconButton extends React.Component{ render() { const icon = ( <Icon circular inverted disabled={this.props.disabled} name={this.props.name} link={!this.props.disabled} color={this.props.color} onClick={this.props.onClick} /> ); return ( <Popup trigger={icon} content={this.props.tooltip} size="tiny" inverted /> ); } }
ajax/libs/forerunnerdb/1.4.4/fdb-core+views+persist.min.js
cdnjs/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View"),a("../lib/Persist");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Persist":29,"../lib/View":36,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":8,"../lib/Shim.IE8":35}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),g<0&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;f<l;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(g.value===-1)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],!!b&&(c=this._data.indexOf(b),c>-1&&(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0))},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;b<g;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":28,"./Shared":34}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a&&(this._store.push(a),this)},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):d.value===-1&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):b===-1?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b&&(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0)):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),b===-1&&this._right?this._right.remove(a):!(1!==b||!this._left)&&this._left.remove(a))},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),e===-1&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),g===-1&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&j!==-1))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":28,"./Shared":34}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){b=b||{},this.sharedPathSolver=o,this._primaryKey=b.primaryKey||"_id",this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()}),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),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=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;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],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=!a||void 0===a.$ensureKeys||a.$ensureKeys,g=!a||void 0===a.$violationCheck||a.$violationCheck,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){var a;if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()});for(a in this._indexByName)this._indexByName.hasOwnProperty(a)&&this._indexByName[a].rebuild();return this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){var d;return"function"==typeof a&&(c=a,a={},b={}),"function"==typeof b&&(c&&(d=c),c=b,b=d||{}),this.find(a,b).filter(c)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b.$replace&&(c=c||{},c.$replace=!0,b=b.$replace),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(g._removeFromIndexes(d),i=g.updateObject(d,e,f.query,f.options,""),g._insertIntoIndexes(d),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):(g._removeFromIndexes(d),i=g.updateObject(d,b,a,c,""),g._insertIntoIndexes(d)),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b,c,d){var e,f={};return f[this._primaryKey]=a,d&&(e=function(a){d(a[0])}),this.update(f,b,c,e)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;if(d&&d.$replace===!0){g=!0,n=b,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);return t}for(s in b)if(b.hasOwnProperty(s)){if(g=!1,!g&&"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;j<k;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(!g&&this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;j<k;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;j<k;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(k<0)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;w<B;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$splicePull":if(void 0!==a[s]){if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePull from a key that is not an array! ("+s+")";if(l=b[s].$index,void 0===l)throw this.logIdentifier()+" Cannot splicePull without a $index integer value!";l<a[s].length&&(this._updateSplicePull(a[s],l),t=!0)}break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else a[s]instanceof Date?this._updateProperty(a,s,b[s]):(u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u);else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;c<f;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0===a.$decouple||a.$decouple,a.$explain=void 0!==a.$explain&&a.$explain,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=[].concat(c.indexMatch[0].lookup)||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&D.indexOf(o)===-1&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e), x.time("group")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b&&(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c))},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):f.value===-1&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(f.value!==-1)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=[].concat(this._primaryIndex.lookup(a,b,c)),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=[].concat(m.lookup(a,b,c)),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;e<j;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return!!b&&b.name()},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){if(this._indexByName)return this._indexByName[a]},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;c<e;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;c<e;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.deferEmit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":7,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":32,"./Shared":34}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&this._collections.indexOf(a)===-1){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);c!==-1&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),b!==-1&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.deferEmit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":34}],7:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":34}],8:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.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"},b.exports=i},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":34}],9:[function(a,b,c){"use strict";var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a,b){this.init.apply(this,arguments)};i.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",i),i.prototype.moduleLoaded=new h({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.shared=d,i.prototype.shared=d,d.addModule("Db",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),d.mixin(i.prototype,"Mixin.Tags"),d.mixin(i.prototype,"Mixin.Events"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"core"),d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new f).setData(a)},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=new h({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;a<c;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},function:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},boolean:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;c<e;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof i?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new i(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=i},{"./Collection.js":5,"./Metrics.js":15,"./Overload":27,"./Shared":34}],10:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;e<=n;e++)for(d=p[e],f=0;f<o;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return g[b][d].indexOf(c)!==-1&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;g<5;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,j<4?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return!!this._btree.insert(a)&&(this._size++,!0)},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),q<=o&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f]; return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":34}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),!!this._btree.insert(a)&&(this._size++,!0)},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":4,"./Path":28,"./Shared":34}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];c.indexOf(b)===-1&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;b<f;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],c.indexOf(b)===-1&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":28,"./Shared":34}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b){this.init.apply(this,arguments)};e.prototype.init=function(a,b){b=b||{},this._name=a,this._data={},this._primaryKey=b.primaryKey||"_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=!b||b,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;b<c;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]&&(this._data[a]=b,!0)},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":34}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":26,"./Shared":34}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);b===-1&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;e<g;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e,f=0,g=a("./Overload"),h=a("./Serialiser"),i=new h;e=function(){var a,b,c,d=[];for(b=0;b<256;b++){for(a=b,c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),d={serialiser:i,make:function(a){return i.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;c<b;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,i.reviver())},jStringify:JSON.stringify,objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,e=0,g=a.length;for(d=0;d<g;d++)e+=a.charCodeAt(d)*c;b=e.toString(16)}else f++,b=(f+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new g([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d},checksum:function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^e[255&(c^a.charCodeAt(b))];return(c^-1)>>>0}},b.exports=d},{"./Overload":27,"./Serialiser":33}],19:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(a,b)})):this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;c<d;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;c<d;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;i<h;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":27}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return b<c;case"$lte":return b<=c;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;h<j;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;k<m;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$fastIn":return c instanceof Array?c.indexOf(b)!==-1:(console.log(this.logIdentifier()+" Cannot use an $fastIn operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},!e.$rootData["//distinctLookup"][n][b[n]]&&(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:a<b?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:a<b?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),e===-1&&(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0)},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b.export,e=b.import,d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g.export,c=g.import,b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1&&(d._trigger[b][c][e].enabled=!0,!0)}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1&&(d._trigger[b][c][e].enabled=!1,!0)}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;g<h;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;f<e;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":27}],25:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updateSplicePull:function(a,b,c){c||(c=1),a.splice(b,c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;c<b;c++)a.pop();d=!0}else if(b<0){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":28,"./Shared":34}],27:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),f.indexOf("*")===-1)e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;c<d;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."), this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&b.indexOf(".")===-1)return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;k<f;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;i<e;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":34}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.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 o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){return this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){return this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},function:function(a){this.isDropped()||this.drop(!0,a)},boolean:function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,f,g){c.deferEmit("save",e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"}),a&&a(b,e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"})})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?(b.deferEmit("load",e),a&&a(c)):b.remove({},function(){d=d||[],b.insert(d,function(){b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),b.deferEmit("load",e,f),a&&a(c,e,f)})})})}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({function:function(a){this.$main.call(this,void 0,a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e,f,g,h=this;if(c=this._collection,d=Object.keys(c),e=d.length,e<=0)return b(!1);f=function(a){a?b&&b(a):(e--,e<=0&&(h.deferEmit("load"),b&&b(!1)))};for(g in c)c.hasOwnProperty(g)&&(a?c[g].loadCustom(a,f):c[g].load(f))}}),d.prototype.save=new l({function:function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e,f,g,h=this;if(c=this._collection,d=Object.keys(c),e=d.length,e<=0)return b(!1);f=function(a){a?b&&b(a):(e--,e<=0&&(h.deferEmit("save"),b&&b(!1)))};for(g in c)c.hasOwnProperty(g)&&(a.custom?c[g].saveCustom(f):c[g].save(f))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":30,"./PersistCrypto":31,"./Shared":34,async:38,localforage:77}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,f<d&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":34,pako:79}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":34,"crypto-js":47}],32:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":34}],33:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date&&(a.toJSON=function(){return"$date:"+this.toISOString()},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$date:"))return a.convert(new Date(b.substr(6)))}),this.registerHandler("$regexp",function(a){return a instanceof RegExp&&(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],34:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.935",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],35:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);c<e;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],36:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return("setData"===g||"insert"===g||"update"===g||"remove"===g)&&(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,!!(c||d||e)&&(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),!f.dataArr.length&&!f.removeArr.length||(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0)))},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(a,b,c,d){var e={$and:[this.query(),a]};this._from.update.call(this._from,e,b,c,d)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;d<c;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.addTrigger=function(){return this._data.addTrigger.apply(this._data,arguments)},o.prototype.removeTrigger=function(){return this._data.removeTrigger.apply(this._data,arguments)},o.prototype.ignoreTriggers=function(){return this._data.ignoreTriggers.apply(this._data,arguments)},o.prototype.addLinkIO=function(){return this._data.addLinkIO.apply(this._data,arguments)},o.prototype.removeLinkIO=function(){return this._data.removeLinkIO.apply(this._data,arguments)},o.prototype.willTrigger=function(){return this._data.willTrigger.apply(this._data,arguments)},o.prototype.processTrigger=function(){return this._data.processTrigger.apply(this._data,arguments)},o.prototype._triggerIndexOf=function(){return this._data._triggerIndexOf.apply(this._data,arguments)},o.prototype.drop=function(a){return!this.isDropped()&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this.decouple(this._querySettings.query)},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,d<0&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;d<c;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange); }return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.deferEmit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":32,"./Shared":34}],37:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(a){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),a;setTimeout(function(){throw a},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:73}],38:[function(a,b,c){(function(a,d){!function(a,d){"object"==typeof c&&"undefined"!=typeof b?d(c):"function"==typeof define&&define.amd?define(["exports"],d):d(a.async=a.async||{})}(this,function(c){"use strict";function e(a){return a}function f(a,b,c){switch(c.length){case 0:return a.call(b);case 1:return a.call(b,c[0]);case 2:return a.call(b,c[0],c[1]);case 3:return a.call(b,c[0],c[1],c[2])}return a.apply(b,c)}function g(a,b,c){return b=hb(void 0===b?a.length-1:b,0),function(){for(var d=arguments,e=-1,g=hb(d.length-b,0),h=Array(g);++e<g;)h[e]=d[b+e];e=-1;for(var i=Array(b+1);++e<b;)i[e]=d[e];return i[b]=c(h),f(a,this,i)}}function h(a){return function(){return a}}function i(a){var b=typeof a;return null!=a&&("object"==b||"function"==b)}function j(a){var b=i(a)?mb.call(a):"";return b==ib||b==jb||b==kb}function k(a){return!!rb&&rb in a}function l(a){if(null!=a){try{return tb.call(a)}catch(a){}try{return a+""}catch(a){}}return""}function m(a){if(!i(a)||k(a))return!1;var b=j(a)?Ab:vb;return b.test(l(a))}function n(a,b){return null==a?void 0:a[b]}function o(a,b){var c=n(a,b);return m(c)?c:void 0}function p(a){var b=0,c=0;return function(){var d=Fb(),e=Eb-(d-c);if(c=d,e>0){if(++b>=Db)return arguments[0]}else b=0;return a.apply(void 0,arguments)}}function q(a,b){return Gb(g(a,b,e),a+"")}function r(a){return q(function(b,c){var d=Hb(function(c,d){var e=this;return a(b,function(a,b){a.apply(e,c.concat([b]))},d)});return c.length?d.apply(this,c):d})}function s(a){return"number"==typeof a&&a>-1&&a%1==0&&a<=Ib}function t(a){return null!=a&&s(a.length)&&!j(a)}function u(){}function v(a){return function(){if(null!==a){var b=a;a=null,b.apply(this,arguments)}}}function w(a,b){for(var c=-1,d=Array(a);++c<a;)d[c]=b(c);return d}function x(a){return null!=a&&"object"==typeof a}function y(a){return x(a)&&Nb.call(a)==Lb}function z(){return!1}function A(a,b){return b=null==b?Zb:b,!!b&&("number"==typeof a||$b.test(a))&&a>-1&&a%1==0&&a<b}function B(a){return x(a)&&s(a.length)&&!!xc[Ac.call(a)]}function C(a){return function(b){return a(b)}}function D(a,b){var c=Sb(a),d=!c&&Rb(a),e=!c&&!d&&Yb(a),f=!c&&!d&&!e&&Hc(a),g=c||d||e||f,h=g?w(a.length,String):[],i=h.length;for(var j in a)!b&&!Jc.call(a,j)||g&&("length"==j||e&&("offset"==j||"parent"==j)||f&&("buffer"==j||"byteLength"==j||"byteOffset"==j)||A(j,i))||h.push(j);return h}function E(a){var b=a&&a.constructor,c="function"==typeof b&&b.prototype||Kc;return a===c}function F(a,b){return function(c){return a(b(c))}}function G(a){if(!E(a))return Lc(a);var b=[];for(var c in Object(a))Nc.call(a,c)&&"constructor"!=c&&b.push(c);return b}function H(a){return t(a)?D(a):G(a)}function I(a){var b=-1,c=a.length;return function(){return++b<c?{value:a[b],key:b}:null}}function J(a){var b=-1;return function(){var c=a.next();return c.done?null:(b++,{value:c.value,key:b})}}function K(a){var b=H(a),c=-1,d=b.length;return function(){var e=b[++c];return c<d?{value:a[e],key:e}:null}}function L(a){if(t(a))return I(a);var b=Kb(a);return b?J(b):K(a)}function M(a){return function(){if(null===a)throw new Error("Callback was already called.");var b=a;a=null,b.apply(this,arguments)}}function N(a){return function(b,c,d){function e(a,b){if(i-=1,a)h=!0,d(a);else{if(b===Oc||h&&i<=0)return h=!0,d(null);f()}}function f(){for(;i<a&&!h;){var b=g();if(null===b)return h=!0,void(i<=0&&d(null));i+=1,c(b.value,b.key,M(e))}}if(d=v(d||u),a<=0||!b)return d(null);var g=L(b),h=!1,i=0;f()}}function O(a,b,c,d){N(b)(a,c,d)}function P(a,b){return function(c,d,e){return a(c,b,d,e)}}function Q(a,b,c){function d(a){a?c(a):++f===g&&c(null)}c=v(c||u);var e=0,f=0,g=a.length;for(0===g&&c(null);e<g;e++)b(a[e],e,M(d))}function R(a){return function(b,c,d){return a(Qc,b,c,d)}}function S(a,b,c,d){d=v(d||u),b=b||[];var e=[],f=0;a(b,function(a,b,d){var g=f++;c(a,function(a,b){e[g]=b,d(a)})},function(a){d(a,e)})}function T(a){return function(b,c,d,e){return a(N(c),b,d,e)}}function U(a){return Hb(function(b,c){var d;try{d=a.apply(this,b)}catch(a){return c(a)}i(d)&&"function"==typeof d.then?d.then(function(a){c(null,a)},function(a){c(a.message?a:new Error(a))}):c(null,d)})}function V(a,b){for(var c=-1,d=a?a.length:0;++c<d&&b(a[c],c,a)!==!1;);return a}function W(a){return function(b,c,d){for(var e=-1,f=Object(b),g=d(b),h=g.length;h--;){var i=g[a?h:++e];if(c(f[i],i,f)===!1)break}return b}}function X(a,b){return a&&Xc(a,b,H)}function Y(a,b,c,d){for(var e=a.length,f=c+(d?1:-1);d?f--:++f<e;)if(b(a[f],f,a))return f;return-1}function Z(a){return a!==a}function $(a,b,c){for(var d=c-1,e=a.length;++d<e;)if(a[d]===b)return d;return-1}function _(a,b,c){return b===b?$(a,b,c):Y(a,Z,c)}function aa(a,b){for(var c=-1,d=a?a.length:0,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function ba(a,b){var c=-1,d=a.length;for(b||(b=Array(d));++c<d;)b[c]=a[c];return b}function ca(a){return"symbol"==typeof a||x(a)&&ad.call(a)==$c}function da(a){if("string"==typeof a)return a;if(Sb(a))return aa(a,da)+"";if(ca(a))return dd?dd.call(a):"";var b=a+"";return"0"==b&&1/a==-bd?"-0":b}function ea(a,b,c){var d=-1,e=a.length;b<0&&(b=-b>e?0:e+b),c=c>e?e:c,c<0&&(c+=e),e=b>c?0:c-b>>>0,b>>>=0;for(var f=Array(e);++d<e;)f[d]=a[d+b];return f}function fa(a,b,c){var d=a.length;return c=void 0===c?d:c,!b&&c>=d?a:ea(a,b,c)}function ga(a,b){for(var c=a.length;c--&&_(b,a[c],0)>-1;);return c}function ha(a,b){for(var c=-1,d=a.length;++c<d&&_(b,a[c],0)>-1;);return c}function ia(a){return a.split("")}function ja(a){return jd.test(a)}function ka(a){return a.match(Bd)||[]}function la(a){return ja(a)?ka(a):ia(a)}function ma(a){return null==a?"":da(a)}function na(a,b,c){if(a=ma(a),a&&(c||void 0===b))return a.replace(Cd,"");if(!a||!(b=da(b)))return a;var d=la(a),e=la(b),f=ha(d,e),g=ga(d,e)+1;return fa(d,f,g).join("")}function oa(a){return a=a.toString().replace(Gd,""),a=a.match(Dd)[2].replace(" ",""),a=a?a.split(Ed):[],a=a.map(function(a){return na(a.replace(Fd,""))})}function pa(a,b){var c={};X(a,function(a,b){function d(b,c){var d=aa(e,function(a){return b[a]});d.push(c),a.apply(null,d)}var e;if(Sb(a))e=ba(a),a=e.pop(),c[b]=e.concat(e.length>0?d:a);else if(1===a.length)c[b]=a;else{if(e=oa(a),0===a.length&&0===e.length)throw new Error("autoInject task functions require explicit parameters.");e.pop(),c[b]=e.concat(d)}}),Yc(c,b)}function qa(a){setTimeout(a,0)}function ra(a){return q(function(b,c){a(function(){b.apply(null,c)})})}function sa(){this.head=this.tail=null,this.length=0}function ta(a,b){a.length=1,a.head=a.tail=b}function ua(a,b,c){function d(a,b,c){if(null!=c&&"function"!=typeof c)throw new Error("task callback must be a function");if(h.started=!0,Sb(a)||(a=[a]),0===a.length&&h.idle())return Jd(function(){h.drain()});for(var d=0,e=a.length;d<e;d++){var f={data:a[d],callback:c||u};b?h._tasks.unshift(f):h._tasks.push(f)}Jd(h.process)}function e(a){return q(function(b){f-=1;for(var c=0,d=a.length;c<d;c++){var e=a[c],i=_(g,e,0);i>=0&&g.splice(i),e.callback.apply(e,b),null!=b[0]&&h.error(b[0],e.data)}f<=h.concurrency-h.buffer&&h.unsaturated(),h.idle()&&h.drain(),h.process()})}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var f=0,g=[],h={_tasks:new sa,concurrency:b,payload:c,saturated:u,unsaturated:u,buffer:b/4,empty:u,drain:u,error:u,started:!1,paused:!1,push:function(a,b){d(a,!1,b)},kill:function(){h.drain=u,h._tasks.empty()},unshift:function(a,b){d(a,!0,b)},process:function(){for(;!h.paused&&f<h.concurrency&&h._tasks.length;){var b=[],c=[],d=h._tasks.length;h.payload&&(d=Math.min(d,h.payload));for(var i=0;i<d;i++){var j=h._tasks.shift();b.push(j),c.push(j.data)}0===h._tasks.length&&h.empty(),f+=1,g.push(b[0]),f===h.concurrency&&h.saturated();var k=M(e(b));a(c,k)}},length:function(){return h._tasks.length},running:function(){return f},workersList:function(){return g},idle:function(){return h._tasks.length+f===0},pause:function(){h.paused=!0},resume:function(){if(h.paused!==!1){h.paused=!1;for(var a=Math.min(h.concurrency,h._tasks.length),b=1;b<=a;b++)Jd(h.process)}}};return h}function va(a,b){return ua(a,1,b)}function wa(a,b,c,d){d=v(d||u),Ld(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})}function xa(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function ya(a){return function(b,c,d){return a(Ld,b,c,d)}}function za(a,b,c){return function(d,e,f,g){function h(){g&&g(null,c(!1))}function i(a,d,e){return g?void f(a,function(d,h){g&&(d||b(h))?(d?g(d):g(d,c(!0,a)),g=f=!1,e(d,Oc)):e()}):e()}arguments.length>3?(g=g||u,a(d,e,i,h)):(g=f,g=g||u,f=e,a(d,i,h))}}function Aa(a,b){return b}function Ba(a){return q(function(b,c){b.apply(null,c.concat([q(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&V(c,function(b){console[a](b)}))})]))})}function Ca(a,b,c){function d(b,d){return b?c(b):d?void a(e):c(null)}c=M(c||u);var e=q(function(a,e){return a?c(a):(e.push(d),void b.apply(this,e))});d(null,!0)}function Da(a,b,c){c=M(c||u);var d=q(function(e,f){return e?c(e):b.apply(this,f)?a(d):void c.apply(null,[null].concat(f))});a(d)}function Ea(a,b,c){Da(a,function(){return!b.apply(this,arguments)},c)}function Fa(a,b,c){function d(b){return b?c(b):void a(e)}function e(a,e){return a?c(a):e?void b(d):c(null)}c=M(c||u),a(e)}function Ga(a){return function(b,c,d){return a(b,d)}}function Ha(a,b,c){Qc(a,Ga(b),c)}function Ia(a,b,c,d){N(b)(a,Ga(c),d)}function Ja(a){return Hb(function(b,c){var d=!0;b.push(function(){var a=arguments;d?Jd(function(){c.apply(null,a)}):c.apply(null,a)}),a.apply(this,b),d=!1})}function Ka(a){return!a}function La(a){return function(b){return null==b?void 0:b[a]}}function Ma(a,b,c,d){d=v(d||u);var e=[];a(b,function(a,b,d){c(a,function(c,f){c?d(c):(f&&e.push({index:b,value:a}),d())})},function(a){a?d(a):d(null,aa(e.sort(function(a,b){return a.index-b.index}),La("value")))})}function Na(a,b){function c(a){return a?d(a):void e(c)}var d=M(b||u),e=Ja(a);c()}function Oa(a,b,c,d){d=v(d||u);var e={};O(a,b,function(a,b,d){c(a,b,function(a,c){return a?d(a):(e[b]=c,void d())})},function(a){d(a,e)})}function Pa(a,b){return b in a}function Qa(a,b){var c=Object.create(null),d=Object.create(null);b=b||e;var f=Hb(function(e,f){var g=b.apply(null,e);Pa(c,g)?Jd(function(){f.apply(null,c[g])}):Pa(d,g)?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([q(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;e<f;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f}function Ra(a,b,c){c=c||u;var d=t(b)?[]:{};a(b,function(a,b,c){a(q(function(a,e){e.length<=1&&(e=e[0]),d[b]=e,c(a)}))},function(a){c(a,d)})}function Sa(a,b){Ra(Qc,a,b)}function Ta(a,b,c){Ra(N(b),a,c)}function Ua(a,b){if(b=v(b||u),!Sb(a))return b(new TypeError("First argument to race must be an array of functions"));if(!a.length)return b();for(var c=0,d=a.length;c<d;c++)a[c](b)}function Va(a,b,c,d){var e=ge.call(a).reverse();wa(e,b,c,d)}function Wa(a){return Hb(function(b,c){return b.push(q(function(a,b){if(a)c(null,{error:a});else{var d=null;1===b.length?d=b[0]:b.length>1&&(d=b),c(null,{value:d})}})),a.apply(this,b)})}function Xa(a,b,c,d){Ma(a,b,function(a,b){c(a,function(a,c){a?b(a):b(null,!c)})},d)}function Ya(a){var b;return Sb(a)?b=aa(a,Wa):(b={},X(a,function(a,c){b[c]=Wa.call(this,a)})),b}function Za(a,b,c){function d(a,b){if("object"==typeof b)a.times=+b.times||f,a.intervalFunc="function"==typeof b.interval?b.interval:h(+b.interval||g),a.errorFilter=b.errorFilter;else{if("number"!=typeof b&&"string"!=typeof b)throw new Error("Invalid arguments for async.retry");a.times=+b||f}}function e(){b(function(a){a&&j++<i.times&&("function"!=typeof i.errorFilter||i.errorFilter(a))?setTimeout(e,i.intervalFunc(j)):c.apply(null,arguments)})}var f=5,g=0,i={times:f,intervalFunc:h(g)};if(arguments.length<3&&"function"==typeof a?(c=b||u,b=a):(d(i,a),c=c||u),"function"!=typeof b)throw new Error("Invalid arguments for async.retry");var j=1;e()}function $a(a,b){Ra(Ld,a,b)}function _a(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}Rc(a,function(a,c){b(a,function(b,d){return b?c(b):void c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,aa(b.sort(d),La("value")))})}function ab(a,b,c){function d(){h||(f.apply(null,arguments),clearTimeout(g))}function e(){var b=a.name||"anonymous",d=new Error('Callback function "'+b+'" timed out.');d.code="ETIMEDOUT",c&&(d.info=c),h=!0,f(d)}var f,g,h=!1;return Hb(function(c,h){f=h,g=setTimeout(e,b),a.apply(null,c.concat(d))})}function bb(a,b,c,d){for(var e=-1,f=pe(oe((b-a)/(c||1)),0),g=Array(f);f--;)g[d?f:++e]=a,a+=c;return g}function cb(a,b,c,d){Tc(bb(0,a,1),b,c,d)}function db(a,b,c,d){3===arguments.length&&(d=c,c=b,b=Sb(a)?[]:{}),d=v(d||u),Qc(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})}function eb(a){return function(){return(a.unmemoized||a).apply(null,arguments)}}function fb(a,b,c){if(c=M(c||u),!a())return c(null);var d=q(function(e,f){return e?c(e):a()?b(d):void c.apply(null,[null].concat(f))});b(d)}function gb(a,b,c){fb(function(){return!a.apply(this,arguments)},b,c)}var hb=Math.max,ib="[object Function]",jb="[object GeneratorFunction]",kb="[object Proxy]",lb=Object.prototype,mb=lb.toString,nb="object"==typeof d&&d&&d.Object===Object&&d,ob="object"==typeof self&&self&&self.Object===Object&&self,pb=nb||ob||Function("return this")(),qb=pb["__core-js_shared__"],rb=function(){var a=/[^.]+$/.exec(qb&&qb.keys&&qb.keys.IE_PROTO||"");return a?"Symbol(src)_1."+a:""}(),sb=Function.prototype,tb=sb.toString,ub=/[\\^$.*+?()[\]{}|]/g,vb=/^\[object .+?Constructor\]$/,wb=Function.prototype,xb=Object.prototype,yb=wb.toString,zb=xb.hasOwnProperty,Ab=RegExp("^"+yb.call(zb).replace(ub,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bb=function(){try{var a=o(Object,"defineProperty");return a({},"",{}),a}catch(a){}}(),Cb=Bb?function(a,b){return Bb(a,"toString",{configurable:!0,enumerable:!1,value:h(b),writable:!0})}:e,Db=500,Eb=16,Fb=Date.now,Gb=p(Cb),Hb=function(a){return q(function(b){var c=b.pop();a.call(this,b,c)})},Ib=9007199254740991,Jb="function"==typeof Symbol&&Symbol.iterator,Kb=function(a){return Jb&&a[Jb]&&a[Jb]()},Lb="[object Arguments]",Mb=Object.prototype,Nb=Mb.toString,Ob=Object.prototype,Pb=Ob.hasOwnProperty,Qb=Ob.propertyIsEnumerable,Rb=y(function(){return arguments}())?y:function(a){return x(a)&&Pb.call(a,"callee")&&!Qb.call(a,"callee")},Sb=Array.isArray,Tb="object"==typeof c&&c&&!c.nodeType&&c,Ub=Tb&&"object"==typeof b&&b&&!b.nodeType&&b,Vb=Ub&&Ub.exports===Tb,Wb=Vb?pb.Buffer:void 0,Xb=Wb?Wb.isBuffer:void 0,Yb=Xb||z,Zb=9007199254740991,$b=/^(?:0|[1-9]\d*)$/,_b="[object Arguments]",ac="[object Array]",bc="[object Boolean]",cc="[object Date]",dc="[object Error]",ec="[object Function]",fc="[object Map]",gc="[object Number]",hc="[object Object]",ic="[object RegExp]",jc="[object Set]",kc="[object String]",lc="[object WeakMap]",mc="[object ArrayBuffer]",nc="[object DataView]",oc="[object Float32Array]",pc="[object Float64Array]",qc="[object Int8Array]",rc="[object Int16Array]",sc="[object Int32Array]",tc="[object Uint8Array]",uc="[object Uint8ClampedArray]",vc="[object Uint16Array]",wc="[object Uint32Array]",xc={};xc[oc]=xc[pc]=xc[qc]=xc[rc]=xc[sc]=xc[tc]=xc[uc]=xc[vc]=xc[wc]=!0,xc[_b]=xc[ac]=xc[mc]=xc[bc]=xc[nc]=xc[cc]=xc[dc]=xc[ec]=xc[fc]=xc[gc]=xc[hc]=xc[ic]=xc[jc]=xc[kc]=xc[lc]=!1;var yc,zc=Object.prototype,Ac=zc.toString,Bc="object"==typeof c&&c&&!c.nodeType&&c,Cc=Bc&&"object"==typeof b&&b&&!b.nodeType&&b,Dc=Cc&&Cc.exports===Bc,Ec=Dc&&nb.process,Fc=function(){try{return Ec&&Ec.binding("util")}catch(a){}}(),Gc=Fc&&Fc.isTypedArray,Hc=Gc?C(Gc):B,Ic=Object.prototype,Jc=Ic.hasOwnProperty,Kc=Object.prototype,Lc=F(Object.keys,Object),Mc=Object.prototype,Nc=Mc.hasOwnProperty,Oc={},Pc=P(O,1/0),Qc=function(a,b,c){var d=t(a)?Q:Pc;d(a,b,c)},Rc=R(S),Sc=r(Rc),Tc=T(S),Uc=P(Tc,1),Vc=r(Uc),Wc=q(function(a,b){return q(function(c){return a.apply(null,b.concat(c))})}),Xc=W(),Yc=function(a,b,c){function d(a,b){r.push(function(){h(a,b)})}function e(){if(0===r.length&&0===n)return c(null,m);for(;r.length&&n<b;){var a=r.shift();a()}}function f(a,b){var c=p[a];c||(c=p[a]=[]),c.push(b)}function g(a){var b=p[a]||[];V(b,function(a){a()}),e()}function h(a,b){if(!o){var d=M(q(function(b,d){if(n--,d.length<=1&&(d=d[0]),b){var e={};X(m,function(a,b){e[b]=a}),e[a]=d,o=!0,p=[],c(b,e)}else m[a]=d,g(a)}));n++;var e=b[b.length-1];b.length>1?e(m,d):e(d)}}function i(){for(var a,b=0;s.length;)a=s.pop(),b++,V(j(a),function(a){0===--t[a]&&s.push(a)});if(b!==l)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function j(b){var c=[];return X(a,function(a,d){Sb(a)&&_(a,b,0)>=0&&c.push(d)}),c}"function"==typeof b&&(c=b,b=null),c=v(c||u);var k=H(a),l=k.length;if(!l)return c(null);b||(b=l);var m={},n=0,o=!1,p={},r=[],s=[],t={};X(a,function(b,c){if(!Sb(b))return d(c,[b]),void s.push(c);var e=b.slice(0,b.length-1),g=e.length;return 0===g?(d(c,b),void s.push(c)):(t[c]=g,void V(e,function(h){if(!a[h])throw new Error("async.auto task `"+c+"` has a non-existent dependency in "+e.join(", "));f(h,function(){g--,0===g&&d(c,b)})}))}),i(),e()},Zc=pb.Symbol,$c="[object Symbol]",_c=Object.prototype,ad=_c.toString,bd=1/0,cd=Zc?Zc.prototype:void 0,dd=cd?cd.toString:void 0,ed="\\ud800-\\udfff",fd="\\u0300-\\u036f\\ufe20-\\ufe23",gd="\\u20d0-\\u20f0",hd="\\ufe0e\\ufe0f",id="\\u200d",jd=RegExp("["+id+ed+fd+gd+hd+"]"),kd="\\ud800-\\udfff",ld="\\u0300-\\u036f\\ufe20-\\ufe23",md="\\u20d0-\\u20f0",nd="\\ufe0e\\ufe0f",od="["+kd+"]",pd="["+ld+md+"]",qd="\\ud83c[\\udffb-\\udfff]",rd="(?:"+pd+"|"+qd+")",sd="[^"+kd+"]",td="(?:\\ud83c[\\udde6-\\uddff]){2}",ud="[\\ud800-\\udbff][\\udc00-\\udfff]",vd="\\u200d",wd=rd+"?",xd="["+nd+"]?",yd="(?:"+vd+"(?:"+[sd,td,ud].join("|")+")"+xd+wd+")*",zd=xd+wd+yd,Ad="(?:"+[sd+pd+"?",pd,td,ud,od].join("|")+")",Bd=RegExp(qd+"(?="+qd+")|"+Ad+zd,"g"),Cd=/^\s+|\s+$/g,Dd=/^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Ed=/,/,Fd=/(=.+)?(\s*)$/,Gd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Hd="function"==typeof setImmediate&&setImmediate,Id="object"==typeof a&&"function"==typeof a.nextTick;yc=Hd?setImmediate:Id?a.nextTick:qa;var Jd=ra(yc);sa.prototype.removeLink=function(a){return a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev,a.prev=a.next=null,this.length-=1,a},sa.prototype.empty=sa,sa.prototype.insertAfter=function(a,b){b.prev=a,b.next=a.next,a.next?a.next.prev=b:this.tail=b,a.next=b,this.length+=1},sa.prototype.insertBefore=function(a,b){b.prev=a.prev,b.next=a,a.prev?a.prev.next=b:this.head=b,a.prev=b,this.length+=1},sa.prototype.unshift=function(a){this.head?this.insertBefore(this.head,a):ta(this,a)},sa.prototype.push=function(a){this.tail?this.insertAfter(this.tail,a):ta(this,a)},sa.prototype.shift=function(){return this.head&&this.removeLink(this.head)},sa.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)};var Kd,Ld=P(O,1),Md=q(function(a){return q(function(b){var c=this,d=b[b.length-1];"function"==typeof d?b.pop():d=u,wa(a,b,function(a,b,d){b.apply(c,a.concat([q(function(a,b){d(a,b)})]))},function(a,b){d.apply(c,[a].concat(b))})})}),Nd=q(function(a){return Md.apply(null,a.reverse())}),Od=R(xa),Pd=ya(xa),Qd=q(function(a){var b=[null].concat(a);return Hb(function(a,c){return c.apply(this,b)})}),Rd=za(Qc,e,Aa),Sd=za(O,e,Aa),Td=za(Ld,e,Aa),Ud=Ba("dir"),Vd=P(Ia,1),Wd=za(Qc,Ka,Ka),Xd=za(O,Ka,Ka),Yd=P(Xd,1),Zd=R(Ma),$d=T(Ma),_d=P($d,1),ae=Ba("log"),be=P(Oa,1/0),ce=P(Oa,1);Kd=Id?a.nextTick:Hd?setImmediate:qa;var de=ra(Kd),ee=function(a,b){return ua(function(b,c){a(b[0],c)},b,1)},fe=function(a,b){var c=ee(a,b);return c.push=function(a,b,d){if(null==d&&(d=u),"function"!=typeof d)throw new Error("task callback must be a function");if(c.started=!0,Sb(a)||(a=[a]),0===a.length)return Jd(function(){c.drain()});b=b||0;for(var e=c._tasks.head;e&&b>=e.priority;)e=e.next;for(var f=0,g=a.length;f<g;f++){var h={data:a[f],priority:b,callback:d};e?c._tasks.insertBefore(e,h):c._tasks.push(h)}Jd(c.process)},delete c.unshift,c},ge=Array.prototype.slice,he=R(Xa),ie=T(Xa),je=P(ie,1),ke=function(a,b){return b||(b=a,a=null),Hb(function(c,d){function e(a){b.apply(null,c.concat([a]))}a?Za(a,e,d):Za(e,d)})},le=za(Qc,Boolean,e),me=za(O,Boolean,e),ne=P(me,1),oe=Math.ceil,pe=Math.max,qe=P(cb,1/0),re=P(cb,1),se=function(a,b){function c(e){if(d===a.length)return b.apply(null,[null].concat(e));var f=M(q(function(a,d){return a?b.apply(null,[a].concat(d)):void c(d)}));e.push(f);var g=a[d++];g.apply(null,e)}if(b=v(b||u),!Sb(a))return b(new Error("First argument to waterfall must be an array of functions"));if(!a.length)return b();var d=0;c([])},te={applyEach:Sc,applyEachSeries:Vc,apply:Wc,asyncify:U,auto:Yc,autoInject:pa,cargo:va,compose:Nd,concat:Od,concatSeries:Pd,constant:Qd,detect:Rd,detectLimit:Sd,detectSeries:Td,dir:Ud,doDuring:Ca,doUntil:Ea,doWhilst:Da,during:Fa,each:Ha,eachLimit:Ia,eachOf:Qc,eachOfLimit:O,eachOfSeries:Ld,eachSeries:Vd,ensureAsync:Ja,every:Wd,everyLimit:Xd,everySeries:Yd,filter:Zd,filterLimit:$d,filterSeries:_d,forever:Na,log:ae,map:Rc,mapLimit:Tc,mapSeries:Uc,mapValues:be,mapValuesLimit:Oa,mapValuesSeries:ce,memoize:Qa,nextTick:de,parallel:Sa,parallelLimit:Ta,priorityQueue:fe,queue:ee,race:Ua,reduce:wa,reduceRight:Va,reflect:Wa,reflectAll:Ya,reject:he,rejectLimit:ie,rejectSeries:je,retry:Za,retryable:ke,seq:Md,series:$a,setImmediate:Jd,some:le,someLimit:me,someSeries:ne,sortBy:_a,timeout:ab,times:qe,timesLimit:cb,timesSeries:re,transform:db,unmemoize:eb,until:gb,waterfall:se,whilst:fb,all:Wd,any:le,forEach:Ha,forEachSeries:Vd,forEachLimit:Ia,forEachOf:Qc,forEachOfSeries:Ld,forEachOfLimit:O,inject:wa,foldl:wa,foldr:Va,select:Zd,selectLimit:$d,selectSeries:_d,wrapSync:U};c.default=te,c.applyEach=Sc,c.applyEachSeries=Vc,c.apply=Wc,c.asyncify=U,c.auto=Yc,c.autoInject=pa,c.cargo=va,c.compose=Nd,c.concat=Od,c.concatSeries=Pd,c.constant=Qd,c.detect=Rd,c.detectLimit=Sd,c.detectSeries=Td,c.dir=Ud,c.doDuring=Ca,c.doUntil=Ea,c.doWhilst=Da,c.during=Fa,c.each=Ha,c.eachLimit=Ia,c.eachOf=Qc,c.eachOfLimit=O,c.eachOfSeries=Ld,c.eachSeries=Vd,c.ensureAsync=Ja,c.every=Wd,c.everyLimit=Xd,c.everySeries=Yd,c.filter=Zd,c.filterLimit=$d,c.filterSeries=_d,c.forever=Na,c.log=ae,c.map=Rc,c.mapLimit=Tc,c.mapSeries=Uc,c.mapValues=be,c.mapValuesLimit=Oa,c.mapValuesSeries=ce,c.memoize=Qa,c.nextTick=de,c.parallel=Sa,c.parallelLimit=Ta,c.priorityQueue=fe,c.queue=ee,c.race=Ua,c.reduce=wa,c.reduceRight=Va,c.reflect=Wa,c.reflectAll=Ya,c.reject=he,c.rejectLimit=ie,c.rejectSeries=je,c.retry=Za,c.retryable=ke,c.seq=Md,c.series=$a,c.setImmediate=Jd,c.some=le,c.someLimit=me,c.someSeries=ne,c.sortBy=_a,c.timeout=ab,c.times=qe,c.timesLimit=cb,c.timesSeries=re,c.transform=db,c.unmemoize=eb,c.until=gb,c.waterfall=se,c.whilst=fb,c.all=Wd,c.allLimit=Xd,c.allSeries=Yd,c.any=le,c.anyLimit=me,c.anySeries=ne,c.find=Rd,c.findLimit=Sd,c.findSeries=Td,c.forEach=Ha,c.forEachSeries=Vd,c.forEachLimit=Ia,c.forEachOf=Qc,c.forEachOfSeries=Ld,c.forEachOfLimit=O,c.inject=wa,c.foldl=wa,c.foldr=Va,c.select=Zd,c.selectLimit=$d,c.selectSeries=_d,c.wrapSync=U,Object.defineProperty(c,"__esModule",{value:!0})})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:73}],39:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;b<256;b++)b<128?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;b<256;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var a=this._keyPriorReset=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;h<e;h++)if(h<c)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;k<e;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];k<4||h<=4?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;o<i;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":40,"./core":41,"./enc-base64":42,"./evpkdf":44,"./md5":49}],40:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;g<d;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;h<d;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4)); c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":41}],41:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c=Object.create||function(){function a(){}return function(b){var c;return a.prototype=b,c=new a,a.prototype=null,c}}(),d={},e=d.lib={},f=e.Base=function(){return{extend:function(a){var b=c(this);return a&&b.mixIn(a),b.hasOwnProperty("init")&&this.init!==b.init||(b.init=function(){b.$super.init.apply(this,arguments)}),b.init.prototype=b,b.$super=this,b},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),g=e.WordArray=f.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||i).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;f<e;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;f<e;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=f.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},f=0;f<b;f+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new g.init(d,b)}}),h=d.enc={},i=h.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new g.init(c,b/2)}},j=h.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new g.init(c,b)}},k=h.Utf8={stringify:function(a){try{return decodeURIComponent(escape(j.stringify(a)))}catch(a){throw new Error("Malformed UTF-8 data")}},parse:function(a){return j.parse(unescape(encodeURIComponent(a)))}},l=e.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new g.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=k.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,f=this.blockSize,h=4*f,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*f,k=a.min(4*j,e);if(j){for(var l=0;l<j;l+=f)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new g.init(m,k)},clone:function(){var a=f.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),m=(e.Hasher=l.extend({cfg:f.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new m.HMAC.init(a,c).finalize(b)}}}),d.algo={});return d}(Math);return a})},{}],42:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b,c){for(var d=[],f=0,g=0;g<b;g++)if(g%4){var h=c[a.charCodeAt(g-1)]<<g%4*2,i=c[a.charCodeAt(g)]>>>6-g%4*2;d[f>>>2]|=(h|i)<<24-f%4*8,f++}return e.create(d,f)}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;f<c;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;k<4&&f+.75*k<c;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var c=a.length,d=this._map,e=this._reverseMap;if(!e){e=this._reverseMap=[];for(var f=0;f<d.length;f++)e[d.charCodeAt(f)]=f}var g=d.charAt(64);if(g){var h=a.indexOf(g);h!==-1&&(c=h)}return b(a,c,e)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":41}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;f<d;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;f<c;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":41}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;k<i;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":41,"./hmac":46,"./sha1":65}],45:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":40,"./core":41}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;j<c;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":41}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.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"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":39,"./cipher-core":40,"./core":41,"./enc-base64":42,"./enc-utf16":43,"./evpkdf":44,"./format-hex":45,"./hmac":46,"./lib-typedarrays":48,"./md5":49,"./mode-cfb":50,"./mode-ctr":52,"./mode-ctr-gladman":51,"./mode-ecb":53,"./mode-ofb":54,"./pad-ansix923":55,"./pad-iso10126":56,"./pad-iso97971":57,"./pad-nopadding":58,"./pad-zeropadding":59,"./pbkdf2":60,"./rabbit":62,"./rabbit-legacy":61,"./rc4":63,"./ripemd160":64,"./sha1":65,"./sha224":66,"./sha256":67,"./sha3":68,"./sha384":69,"./sha512":70,"./tripledes":71,"./x64-core":72}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;d<b;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":41}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;a<64;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;g<16;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;j<4;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":41}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;g<c;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":40,"./core":41}],51:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;i<e;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":40,"./core":41}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;h<d;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":40,"./core":41}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":40,"./core":41}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;g<d;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":40,"./core":41}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":40,"./core":41}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":40,"./core":41}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":40,"./core":41}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":40,"./core":41}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":40,"./core":41}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;q<l;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;s<o;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":41,"./hmac":46,"./sha1":65}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;c<8;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;c<8;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;f<4;f++)b.call(this);for(var f=0;f<8;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;f<4;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;e<4;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":40,"./core":41,"./enc-base64":42,"./evpkdf":44,"./md5":49}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;c<8;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;c<8;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;d<4;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;d<4;d++)b.call(this);for(var d=0;d<8;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;d<4;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;e<4;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":40,"./core":41,"./enc-base64":42,"./evpkdf":44,"./md5":49}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;e<4;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;e<256;e++)d[e]=e;for(var e=0,f=0;e<256;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":40,"./core":41,"./enc-base64":42,"./evpkdf":44,"./md5":49}],64:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.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]),o=k.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]),p=k.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]),q=k.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]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;i<16;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;i<80;i+=1)I=l+a[b+E[i]]|0,I+=i<16?c(m,t,u)+C[0]:i<32?d(m,t,u)+C[1]:i<48?e(m,t,u)+C[2]:i<64?f(m,t,u)+C[3]:g(m,t,u)+C[4],I|=0,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=i<16?g(x,y,z)+D[0]:i<32?f(x,y,z)+D[1]:i<48?e(x,y,z)+D[2]:i<64?d(x,y,z)+D[3]:c(x,y,z)+D[4],I|=0,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;g<5;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":41}],65:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;j<80;j++){if(j<16)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=j<20?(e&f|~e&h)+1518500249:j<40?(e^f^h)+1859775393:j<60?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":41}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":41,"./sha256":67}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;d<=c;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;e<64;)a(d)&&(e<8&&(h[e]=c(b.pow(d,.5))), i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;n<64;n++){if(n<16)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":41}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;c<24;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;a<5;a++)for(var b=0;b<5;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;g<24;g++){for(var i=0,m=0,n=0;n<7;n++){if(1&f){var o=(1<<n)-1;o<32?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;a<25;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;b<25;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;e<d;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;i<24;i++){for(var n=0;n<5;n++){for(var o=0,p=0,q=0;q<5;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;n<5;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;q<5;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;w<25;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(z<32)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;n<5;n++)for(var q=0;q<5;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;k<i;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;c<25;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":41,"./x64-core":72}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":41,"./sha512":70,"./x64-core":72}],70:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;a<80;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;T<80;T++){var U=k[T];if(T<16)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(W>>>0<_>>>0?1:0),W=W+ea,V=V+da+(W>>>0<ea>>>0?1:0),W=W+ka,V=V+ja+(W>>>0<ka>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(wa>>>0<S>>>0?1:0),wa=wa+ma,xa=xa+la+(wa>>>0<ma>>>0?1:0),wa=wa+va,xa=xa+ua+(wa>>>0<va>>>0?1:0),wa=wa+W,xa=xa+V+(wa>>>0<W>>>0?1:0),ya=qa+oa,za=pa+na+(ya>>>0<qa>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(M>>>0<K>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(E>>>0<wa>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(o>>>0<E>>>0?1:0),q=e.low=q+G,e.high=p+F+(q>>>0<G>>>0?1:0),s=f.low=s+I,f.high=r+H+(s>>>0<I>>>0?1:0),u=g.low=u+K,g.high=t+J+(u>>>0<K>>>0?1:0),w=h.low=w+M,h.high=v+L+(w>>>0<M>>>0?1:0),y=i.low=y+O,i.high=x+N+(y>>>0<O>>>0?1:0),A=l.low=A+Q,l.high=z+P+(A>>>0<Q>>>0?1:0),C=m.low=C+S,m.high=B+R+(C>>>0<S>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":41,"./x64-core":72}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[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],j=[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],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;d<56;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;g<16;g++){for(var h=f[g]=[],l=k[g],d=0;d<24;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;d<7;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;d<16;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;f<16;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;k<8;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":40,"./core":41,"./enc-base64":42,"./evpkdf":44,"./md5":49}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;d<b;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;d<c;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":41}],73:[function(a,b,c){function d(){throw new Error("setTimeout has not been defined")}function e(){throw new Error("clearTimeout has not been defined")}function f(a){if(l===setTimeout)return setTimeout(a,0);if((l===d||!l)&&setTimeout)return l=setTimeout,setTimeout(a,0);try{return l(a,0)}catch(b){try{return l.call(null,a,0)}catch(b){return l.call(this,a,0)}}}function g(a){if(m===clearTimeout)return clearTimeout(a);if((m===e||!m)&&clearTimeout)return m=clearTimeout,clearTimeout(a);try{return m(a)}catch(b){try{return m.call(null,a)}catch(b){return m.call(this,a)}}}function h(){q&&o&&(q=!1,o.length?p=o.concat(p):r=-1,p.length&&i())}function i(){if(!q){var a=f(h);q=!0;for(var b=p.length;b;){for(o=p,p=[];++r<b;)o&&o[r].run();r=-1,b=p.length}o=null,q=!1,g(a)}}function j(a,b){this.fun=a,this.array=b}function k(){}var l,m,n=b.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:d}catch(a){l=d}try{m="function"==typeof clearTimeout?clearTimeout:e}catch(a){m=e}}();var o,p=[],q=!1,r=-1;n.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];p.push(new j(a,b)),1!==p.length||q||f(i)},j.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=k,n.addListener=k,n.once=k,n.off=k,n.removeListener=k,n.removeAllListeners=k,n.emit=k,n.binding=function(a){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(a){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},{}],74:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(f){if("TypeError"!==f.name)throw f;for(var c=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,d=new c,e=0;e<a.length;e+=1)d.append(a[e]);return d.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;e<b;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){if(4===d.readyState)return 200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response})},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}}).catch(function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}}).catch(d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c.continue()}else b()},g.onerror=function(){d(g.error)}}).catch(d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}}).catch(e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g.delete(a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}}).catch(d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}}).catch(c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}}).catch(c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return a<0?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}}).catch(d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b.continue()):void a(g)},f.onerror=function(){c(f.error)}}).catch(c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:96}],75:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=1,g=0;g<e;g++){var h=p.key(g);if(0===h.indexOf(b)){var i=p.getItem(h);if(i&&(i=o.deserialize(i)),i=a(i,h.substring(d),f++),void 0!==i)return i}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(a){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;e<c;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(a){"QuotaExceededError"!==a.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==a.name||f(a),f(a)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(a){return}var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};r===q.EXPORT?b.exports=s:r===q.DEFINE?define("localStorageWrapper",function(){return s}):this.localStorageWrapper=s}).call(window)},{"./../utils/serializer":78,promise:96}],76:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(d){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a).catch(e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;g<f;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i); }b()},function(a,b){d(b)})})}).catch(d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})}).catch(e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})}).catch(d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})}).catch(c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})}).catch(c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})}).catch(d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})}).catch(c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":78,promise:96}],77:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(a){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(a){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(a){c(a)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)}).catch(c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":74,"./drivers/localstorage":75,"./drivers/websql":76,promise:96}],78:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(f){if("TypeError"!==f.name)throw f;for(var c=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,d=new c,e=0;e<a.length;e+=1)d.append(a[e]);return d.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;b<i;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],79:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":80,"./lib/inflate":81,"./lib/utils/common":82,"./lib/zlib/constants":85}],80:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);if(b.header&&h.deflateSetHeader(this.strm,b.header),b.dictionary){var e;if(e="string"==typeof b.dictionary?j.string2buf(b.dictionary):"[object ArrayBuffer]"===m.call(b.dictionary)?new Uint8Array(b.dictionary):b.dictionary,c=h.deflateSetDictionary(this.strm,e),c!==p)throw new Error(k[c]);this._dict_set=!0}}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d!==r||(this.onEnd(p),e.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":82,"./utils/strings":83,"./zlib/deflate":87,"./zlib/messages":92,"./zlib/zstream":94}],81:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l,m=this.strm,o=this.options.chunkSize,p=this.options.dictionary,q=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?m.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?m.input=new Uint8Array(a):m.input=a,m.next_in=0,m.avail_in=m.input.length;do{if(0===m.avail_out&&(m.output=new h.Buf8(o),m.next_out=0,m.avail_out=o),c=g.inflate(m,j.Z_NO_FLUSH),c===j.Z_NEED_DICT&&p&&(l="string"==typeof p?i.string2buf(p):"[object ArrayBuffer]"===n.call(p)?new Uint8Array(p):p,c=g.inflateSetDictionary(this.strm,l)),c===j.Z_BUF_ERROR&&q===!0&&(c=j.Z_OK,q=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;m.next_out&&(0!==m.avail_out&&c!==j.Z_STREAM_END&&(0!==m.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(m.output,m.next_out),f=m.next_out-e,k=i.buf2string(m.output,e),m.next_out=f,m.avail_out=o-f,f&&h.arraySet(m.output,m.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(m.output,m.next_out)))),0===m.avail_in&&0===m.avail_out&&(q=!0)}while((m.avail_in>0||0===m.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d!==j.Z_SYNC_FLUSH||(this.onEnd(j.Z_OK),m.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":82,"./utils/strings":83,"./zlib/constants":85,"./zlib/gzheader":88,"./zlib/inflate":90,"./zlib/messages":92,"./zlib/zstream":94}],82:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;b<c;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;b<c;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],83:[function(a,b,c){"use strict";function d(a,b){if(b<65537&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;d<b;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(a){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(a){g=!1}for(var h=new e.Buf8(256),i=0;i<256;i++)h[i]=i>=252?6:i>=248?5:i>=240?4:i>=224?3:i>=192?2:1;h[254]=h[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;f<h;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=new e.Buf8(i),g=0,f=0;g<i;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),c<128?b[g++]=c:c<2048?(b[g++]=192|c>>>6,b[g++]=128|63&c):c<65536?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;c<d;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,i=b||a.length,j=new Array(2*i);for(e=0,c=0;c<i;)if(f=a[c++],f<128)j[e++]=f;else if(g=h[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&c<i;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:f<65536?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+h[a[c]]>b?c:b}},{"./common":82}],84:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],85:[function(a,b,c){"use strict";b.exports={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,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,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,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],86:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;h<g;h++)a=a>>>8^e[255&(a^b[h])];return a^-1}var f=d();b.exports=e},{}],87:[function(a,b,c){"use strict";function d(a,b){return a.msg=I[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(E.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){F._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,E.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=G(a.adler,b,e,c):2===a.state.wrap&&(a.adler=H(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-la?a.strstart-(a.w_size-la):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ka,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&f<m);if(d=ka-(m-f),f=m-ka,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-la)){E.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ja)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ja-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ja)););}while(a.lookahead<la&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===J)return ua;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ua;if(a.strstart-a.block_start>=a.w_size-la&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ua:ua}function o(a,b){for(var c,d;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c)),a.match_length>=ja)if(d=F._tr_tally(a,a.strstart-a.match_start,a.match_length-ja),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ja){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function p(a,b){for(var c,d,e;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ja-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===U||a.match_length===ja&&a.strstart-a.match_start>4096)&&(a.match_length=ja-1)),a.prev_length>=ja&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ja,d=F._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ja),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ja-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ua}else if(a.match_available){if(d=F._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ua}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=F._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ka){if(m(a),a.lookahead<=ka&&b===J)return ua;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ja&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ka;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&e<f);a.match_length=ka-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ja?(c=F._tr_tally(a,1,a.match_length-ja),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===J)return ua;break}if(a.match_length=0,c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=D[a.level].max_lazy,a.good_match=D[a.level].good_length,a.nice_match=D[a.level].nice_length,a.max_chain_length=D[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ja-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*ha),this.dyn_dtree=new E.Buf16(2*(2*fa+1)),this.bl_tree=new E.Buf16(2*(2*ga+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(ia+1),this.heap=new E.Buf16(2*ea+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*ea+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Z,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?na:sa,a.adler=2===b.wrap?0:1,b.last_flush=J,F._tr_init(b),O):d(a,Q)}function w(a){var b=v(a);return b===O&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?Q:(a.state.gzhead=b,O):Q}function y(a,b,c,e,f,g){if(!a)return Q;var h=1;if(b===T&&(b=6),e<0?(h=0,e=-e):e>15&&(h=2,e-=16),f<1||f>_||c!==$||e<8||e>15||b<0||b>9||g<0||g>X)return d(a,Q);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ja-1)/ja),i.window=new E.Buf8(2*i.w_size),i.head=new E.Buf16(i.hash_size),i.prev=new E.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new E.Buf8(i.pending_buf_size),i.d_buf=1*i.lit_bufsize,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,$,aa,ba,Y)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>N||b<0)return a?d(a,Q):Q;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ta&&b!==M)return d(a,0===a.avail_out?S:Q);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===na)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=H(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=oa):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,ya),h.status=sa);else{var m=$+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=V||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ma),m+=31-m%31,h.status=sa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===oa)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=qa)}else h.status=qa;if(h.status===qa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=ra)}else h.status=ra;if(h.status===ra&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=sa)):h.status=sa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,O}else if(0===a.avail_in&&e(b)<=e(c)&&b!==M)return d(a,S);if(h.status===ta&&0!==a.avail_in)return d(a,S);if(0!==a.avail_in||0!==h.lookahead||b!==J&&h.status!==ta){var o=h.strategy===V?r(h,b):h.strategy===W?q(h,b):D[h.level].func(h,b);if(o!==wa&&o!==xa||(h.status=ta),o===ua||o===wa)return 0===a.avail_out&&(h.last_flush=-1),O;if(o===va&&(b===K?F._tr_align(h):b!==N&&(F._tr_stored_block(h,0,0,!1),b===L&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,O}return b!==M?O:h.wrap<=0?P:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?O:P)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa&&b!==ta?d(a,Q):(a.state=null,b===sa?d(a,R):O)):Q}function C(a,b){var c,d,e,g,h,i,j,k,l=b.length;if(!a||!a.state)return Q;if(c=a.state,g=c.wrap,2===g||1===g&&c.status!==na||c.lookahead)return Q;for(1===g&&(a.adler=G(a.adler,b,l,0)), c.wrap=0,l>=c.w_size&&(0===g&&(f(c.head),c.strstart=0,c.block_start=0,c.insert=0),k=new E.Buf8(c.w_size),E.arraySet(k,b,l-c.w_size,c.w_size,0),b=k,l=c.w_size),h=a.avail_in,i=a.next_in,j=a.input,a.avail_in=l,a.next_in=0,a.input=b,m(c);c.lookahead>=ja;){d=c.strstart,e=c.lookahead-(ja-1);do c.ins_h=(c.ins_h<<c.hash_shift^c.window[d+ja-1])&c.hash_mask,c.prev[d&c.w_mask]=c.head[c.ins_h],c.head[c.ins_h]=d,d++;while(--e);c.strstart=d,c.lookahead=ja-1,m(c)}return c.strstart+=c.lookahead,c.block_start=c.strstart,c.insert=c.lookahead,c.lookahead=0,c.match_length=c.prev_length=ja-1,c.match_available=0,a.next_in=i,a.input=j,a.avail_in=h,c.wrap=g,O}var D,E=a("../utils/common"),F=a("./trees"),G=a("./adler32"),H=a("./crc32"),I=a("./messages"),J=0,K=1,L=3,M=4,N=5,O=0,P=1,Q=-2,R=-3,S=-5,T=-1,U=1,V=2,W=3,X=4,Y=0,Z=2,$=8,_=9,aa=15,ba=8,ca=29,da=256,ea=da+1+ca,fa=30,ga=19,ha=2*ea+1,ia=15,ja=3,ka=258,la=ka+ja+1,ma=32,na=42,oa=69,pa=73,qa=91,ra=103,sa=113,ta=666,ua=1,va=2,wa=3,xa=4,ya=3;D=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateSetDictionary=C,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./messages":92,"./trees":93}],88:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],89:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(q<w&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,q<w&&(p+=B[f++]<<q,q+=8,q<w&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(n<w){if(z+=l+n-w,w-=n,w<x){x-=w;do C[h++]=o[z++];while(--w);if(z=0,n<x){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(f<g&&h<j);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=f<g?5+(g-f):5-(f-g),a.avail_out=h<j?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],90:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=L,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new s.Buf32(pa),b.distcode=b.distdyn=new s.Buf32(qa),b.sane=1,b.back=-1,D):G}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):G}function h(a,b){var c,d;return a&&a.state?(d=a.state,b<0?(c=0,b=-b):(c=(b>>4)+1,b<48&&(b&=15)),b&&(b<8||b>15)?G:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):G}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==D&&(a.state=null),c):G}function j(a){return i(a,sa)}function k(a){if(ta){var b;for(q=new s.Buf32(512),r=new s.Buf32(32),b=0;b<144;)a.lens[b++]=8;for(;b<256;)a.lens[b++]=9;for(;b<280;)a.lens[b++]=7;for(;b<288;)a.lens[b++]=8;for(w(y,a.lens,0,288,q,0,a.work,{bits:9}),b=0;b<32;)a.lens[b++]=5;w(z,a.lens,0,32,r,0,a.work,{bits:5}),ta=!1}a.lencode=q,a.lenbits=9,a.distcode=r,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new s.Buf8(f.wsize)),d>=f.wsize?(s.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),s.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(s.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,r,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new s.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return G;c=a.state,c.mode===W&&(c.mode=X),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=D;a:for(;;)switch(c.mode){case L:if(0===c.wrap){c.mode=X;break}for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0),m=0,n=0,c.mode=M;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=ma;break}if((15&m)!==K){a.msg="unknown compression method",c.mode=ma;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=ma;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?U:W,m=0,n=0;break;case M:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==K){a.msg="unknown compression method",c.mode=ma;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=ma;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=N;case N:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=u(c.check,Ba,4,0)),m=0,n=0,c.mode=O;case O:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=P;case P:if(1024&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=Q;case Q:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),s.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=R;case R:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=S;case S:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=T;case T:if(512&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=ma;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=W;break;case U:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=V;case V:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,F;a.adler=c.check=1,c.mode=W;case W:if(b===B||b===C)break a;case X:if(c.last){m>>>=7&n,n-=7&n,c.mode=ja;break}for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=Y;break;case 1:if(k(c),c.mode=ca,b===C){m>>>=2,n-=2;break a}break;case 2:c.mode=_;break;case 3:a.msg="invalid block type",c.mode=ma}m>>>=2,n-=2;break;case Y:for(m>>>=7&n,n-=7&n;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=ma;break}if(c.length=65535&m,m=0,n=0,c.mode=Z,b===C)break a;case Z:c.mode=$;case $:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;s.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=W;break;case _:for(;n<14;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=ma;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.ncode;){for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=w(x,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=ma;break}c.have=0,c.mode=ba;case ba:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(sa<16)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=ma;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=ma;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===ma)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=ma;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=w(y,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=ma;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=w(z,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=ma;break}if(c.mode=ca,b===C)break a;case ca:c.mode=da;case da:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,v(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===W&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ia;break}if(32&ra){c.back=-1,c.mode=W;break}if(64&ra){a.msg="invalid literal/length code",c.mode=ma;break}c.extra=15&ra,c.mode=ea;case ea:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=fa;case fa:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=ma;break}c.offset=sa,c.extra=15&ra,c.mode=ga;case ga:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=ma;break}c.mode=ha;case ha:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=ma;break}q>c.wnext?(q-=c.wnext,r=c.wsize-q):r=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,r=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[r++];while(--q);0===c.length&&(c.mode=da);break;case ia:if(0===j)break a;f[h++]=c.length,j--,c.mode=da;break;case ja:if(c.wrap){for(;n<32;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?u(c.check,f,p,h-p):t(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=ma;break}m=0,n=0}c.mode=ka;case ka:if(c.wrap&&c.flags){for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=ma;break}m=0,n=0}c.mode=la;case la:xa=E;break a;case ma:xa=H;break a;case na:return I;case oa:default:return G}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<ma&&(c.mode<ja||b!==A))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=na,I):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?u(c.check,f,p,a.next_out-p):t(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===W?128:0)+(c.mode===ca||c.mode===Z?256:0),(0===o&&0===p||b===A)&&xa===D&&(xa=J),xa)}function n(a){if(!a||!a.state)return G;var b=a.state;return b.window&&(b.window=null),a.state=null,D}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?G:(c.head=b,b.done=!1,D)):G}function p(a,b){var c,d,e,f=b.length;return a&&a.state?(c=a.state,0!==c.wrap&&c.mode!==V?G:c.mode===V&&(d=1,d=t(d,b,f,0),d!==c.check)?H:(e=l(a,b,f,f))?(c.mode=na,I):(c.havedict=1,D)):G}var q,r,s=a("../utils/common"),t=a("./adler32"),u=a("./crc32"),v=a("./inffast"),w=a("./inftrees"),x=0,y=1,z=2,A=4,B=5,C=6,D=0,E=1,F=2,G=-2,H=-3,I=-4,J=-5,K=8,L=1,M=2,N=3,O=4,P=5,Q=6,R=7,S=8,T=9,U=10,V=11,W=12,X=13,Y=14,Z=15,$=16,_=17,aa=18,ba=19,ca=20,da=21,ea=22,fa=23,ga=24,ha=25,ia=26,ja=27,ka=28,la=29,ma=30,na=31,oa=32,pa=852,qa=592,ra=15,sa=ra,ta=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateSetDictionary=p,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./inffast":89,"./inftrees":91}],91:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[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],l=[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],m=[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],n=[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];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;D<=e;D++)P[D]=0;for(E=0;E<o;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;F<G&&0===P[F];F++);for(H<F&&(H=F),K=1,D=1;D<=e;D++)if(K<<=1,K-=P[D],K<0)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;D<e;D++)Q[D+1]=Q[D]+P[D];for(E=0;E<o;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;I+J<G&&(K-=P[I+J],!(K<=0));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":82}],92:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],93:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return a<256?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;f<=W;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;c<V;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;d<=W;d++)f[d]=g=g+c[d-1]<<1;for(e=0;e<=b;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;d<Q-1;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;d<16;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;d<T;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;b<=W;b++)g[b]=0;for(a=0;a<=143;)ga[2*a+1]=8,a++,g[8]++;for(;a<=255;)ga[2*a+1]=9,a++,g[9]++;for(;a<=279;)ga[2*a+1]=7,a++,g[7]++;for(;a<=287;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;a<T;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;b<S;b++)a.dyn_ltree[2*b]=0;for(b=0;b<T;b++)a.dyn_dtree[2*b]=0;for(b=0;b<U;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;c<i;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=j<2?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;d<=c;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(h<j?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):h<=10?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;d<=c;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(h<l){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):h<=10?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;e<d;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;b<=31;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;b<R;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,f<=e&&(e=f)):e=f=c+5,c+4<=e&&b!==-1?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[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],ca=[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],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":82}],94:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],95:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(b){return void a.reject(b)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(a){h(a)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;a<c;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(a){if(d)return;d=!0,c(a)}}var g=a("asap");b.exports=d},{asap:37}],96:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(a){d(a)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(a){return new e(function(b,c){c(a)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(a){if(null===c||"undefined"==typeof c)return new e(function(b,c){c(a)});f(function(){c(a)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(a){c(a)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype.catch=function(a){return this.then(null,a)}},{"./core.js":95,asap:37}]},{},[1]);
src/Main/CastEfficiency.js
hasseboulen/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SpellLink from 'common/SpellLink'; import Abilities from 'Parser/Core/Modules/Abilities'; const CastEfficiency = ({ categories, abilities }) => { if (!abilities) { return <div>Loading...</div>; } return ( <div style={{ marginTop: -10, marginBottom: -10 }}> <table className="data-table" style={{ marginTop: 10, marginBottom: 10 }}> {Object.keys(categories) .filter(key => abilities.some(item => item.ability.category === categories[key])) // filters out categories without any abilities in it .filter(key => categories[key] !== Abilities.SPELL_CATEGORIES.HIDDEN) //filters out the hidden category .map(key => ( <tbody key={key}> <tr> <th><b>{categories[key]}</b></th> <th className="text-center"><dfn data-tip="Casts Per Minute">CPM</dfn></th> <th className="text-right"><dfn data-tip="Maximum possible casts are based on the ability's cooldown and the fight duration. For abilities that can have their cooldowns dynamically reduced or reset, it's based on the average actual time it took the ability to cooldown over the course of this encounter.">Cast efficiency</dfn></th> <th className="text-center"><dfn data-tip="The percentage of time the spell was kept on cooldown. Spells with multiple charges count as on cooldown as long as you have fewer than maximum charges. For spells with long cooldowns, it's possible to have well below 100% on cooldown and still achieve maximum casts.">Time on Cooldown</dfn></th> <th /> </tr> {abilities .filter(item => item.ability.category === categories[key]) .map(({ ability, cpm, maxCpm, casts, maxCasts, efficiency, canBeImproved }) => { const name = ability.castEfficiency.name || ability.name; return ( <tr key={name}> <td style={{ width: '35%' }}> <SpellLink id={ability.primarySpell.id} style={{ color: '#fff' }} icon iconStyle={{ height: undefined, marginTop: undefined }}> {name} </SpellLink> </td> <td className="text-center" style={{ minWidth: 80 }}> {cpm.toFixed(2)} </td> <td className="text-right" style={{ minWidth: 110 }}> {casts}{maxCasts === Infinity ? '' : `/${Math.floor(maxCasts)}`} casts </td> <td style={{ width: '20%' }}> {maxCasts === Infinity ? '' : ( <div className="flex performance-bar-container"> <div className="flex-sub performance-bar" style={{ width: `${efficiency * 100}%`, backgroundColor: canBeImproved ? '#ff8000' : '#70b570' }} /> </div> )} </td> <td className="text-left" style={{ minWidth: 50, paddingRight: 5 }}> {maxCpm !== null ? `${(efficiency * 100).toFixed(2)}%` : ''} </td> <td style={{ width: '25%', color: 'orange' }}> {canBeImproved && ability.castEfficiency && ability.castEfficiency.suggestion && 'Can be improved.'} </td> </tr> ); })} </tbody> ))} </table> </div> ); }; CastEfficiency.propTypes = { abilities: PropTypes.arrayOf(PropTypes.shape({ ability: PropTypes.shape({ name: PropTypes.string, category: PropTypes.string.isRequired, primarySpell: PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, }).isRequired, castEfficiency: PropTypes.shape({ name: PropTypes.string, }).isRequired, }), cpm: PropTypes.number.isRequired, maxCpm: PropTypes.number, casts: PropTypes.number.isRequired, maxCasts: PropTypes.number.isRequired, castEfficiency: PropTypes.number, canBeImproved: PropTypes.bool.isRequired, })).isRequired, categories: PropTypes.object, }; export default CastEfficiency;
react/templates/pure/MyComponent.spec.js
OceanCodes/generator-codeocean-component
import React from 'react'; import { shallow } from 'enzyme'; import <%= componentName %> from './<%= componentName %>'; describe('<%= componentName %>', () => { it('should have div element', () => { const wrapper = shallow(<<%= componentName %> />); expect(wrapper.find('div').length).toBe(1); }); });
src/components/native/PageTitle.js
Manuelandro/Universal-Commerce
import React from 'react' import styled from 'styled-components/native' const { View, Text } = { View: styled.View` flex: 1; flexDirection: row; alignSelf: stretch; justifyContent: center; marginTop: 20; marginBottom: 5; `, Text: styled.Text` alignSelf: center; fontSize: 18; fontWeight: 600; color: #000; ` } const PageTitle = ({ children }) => <View> <Text>{children}</Text> </View> export { PageTitle }
src/components/video_detail.js
JenPhD/ReactYouTubeSearch
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; //backtics and ${} same thing as concatenating return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
react-ui/src/components/Loader/Loader.js
morewines/refund-calculator-bigcommerce
import React from 'react'; // CSS import './Loader.css'; /** * Loader written by brunjo @ https://codepen.io/brunjo/details/wBKmbm/ */ const Loader = ({ extraClass }) => ( <div className={'loading ' + extraClass}> <div className="loading-bar" /> <div className="loading-bar" /> <div className="loading-bar" /> <div className="loading-bar" /> </div> ); export default Loader;
ajax/libs/react-widgets/4.0.0-beta.3/react-widgets-moment.js
jonobr1/cdnjs
/*! (c) 2014 - present: Jason Quense | https://github.com/jquense/react-widgets/blob/master/License.txt */ /******/ (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__) { /*** IMPORTS FROM imports-loader ***/ var createLocalizer = __webpack_require__(1); var args = [Moment]; 'use strict'; /*** IMPORTS FROM imports-loader ***/ var define = false; if (typeof createLocalizer === 'function') { createLocalizer.apply(null, args || []); } /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*** IMPORTS FROM imports-loader ***/ var define = false; 'use strict'; exports.__esModule = true; exports.default = globalizeLocalizers; var _react = __webpack_require__(2); var _configure = __webpack_require__(3); var _configure2 = _interopRequireDefault(_configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function endOfDecade(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 10); date.setMilliseconds(date.getMilliseconds() - 1); return date; } function endOfCentury(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 100); date.setMilliseconds(date.getMilliseconds() - 1); return date; } function globalizeLocalizers(globalize) { var localizers = globalize.locale && !globalize.cultures ? newGlobalize(globalize) : oldGlobalize(globalize); _configure2.default.setLocalizers(localizers); return localizers; } function newGlobalize(globalize) { var locale = function locale(culture) { return culture ? globalize(culture) : globalize; }; var date = { formats: { date: { date: 'short' }, time: { time: 'short' }, default: { datetime: 'medium' }, header: 'MMMM yyyy', footer: { date: 'full' }, weekday: 'eeeeee', dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: function decade(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture); }, century: function century(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture); } }, propType: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object, _react.PropTypes.func]), firstOfWeek: function firstOfWeek(culture) { var date = new Date(); //cldr-data doesn't seem to be zero based var localeDay = Math.max(parseInt(locale(culture).formatDate(date, { raw: 'e' }), 10) - 1, 0); return Math.abs(date.getDay() - localeDay); }, parse: function parse(value, format, culture) { format = typeof format === 'string' ? { raw: format } : format; return locale(culture).parseDate(value, format); }, format: function format(value, _format, culture) { _format = typeof _format === 'string' ? { raw: _format } : _format; return locale(culture).formatDate(value, _format); } }; var number = { formats: { default: { maximumFractionDigits: 0 } }, propType: _react.PropTypes.oneOfType([_react.PropTypes.object, _react.PropTypes.func]), // TODO major bump consistent ordering parse: function parse(value, culture) { return locale(culture).parseNumber(value); }, format: function format(value, _format2, culture) { if (value == null) return value; if (_format2 && _format2.currency) return locale(culture).formatCurrency(value, _format2.currency, _format2); return locale(culture).formatNumber(value, _format2); }, decimalChar: function decimalChar(format, culture) { var str = this.format(1.1, { raw: '0.0' }, culture); return str[str.length - 2] || '.'; }, precision: function precision(format) { return !format || format.maximumFractionDigits == null ? null : format.maximumFractionDigits; } }; return { date: date, number: number }; } function oldGlobalize(globalize) { var shortNames = Object.create(null); function getCulture(culture) { return culture ? globalize.findClosestCulture(culture) : globalize.culture(); } function firstOfWeek(culture) { culture = getCulture(culture); return culture && culture.calendar.firstDay || 0; } function shortDay(dayOfTheWeek) { var culture = getCulture(arguments[1]), name = culture.name, days = function days() { return culture.calendar.days.namesShort.slice(); }; var names = shortNames[name] || (shortNames[name] = days()); return names[dayOfTheWeek.getDay()]; } var date = { formats: { date: 'd', time: 't', default: 'f', header: 'MMMM yyyy', footer: 'D', weekday: shortDay, dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: function decade(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture); }, century: function century(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture); } }, firstOfWeek: firstOfWeek, parse: function parse(value, format, culture) { return globalize.parseDate(value, format, culture); }, format: function format(value, _format3, culture) { return globalize.format(value, _format3, culture); } }; function formatData(format, _culture) { var culture = getCulture(_culture), numFormat = culture.numberFormat; if (typeof format === 'string') { if (format.indexOf('p') !== -1) numFormat = numFormat.percent; if (format.indexOf('c') !== -1) numFormat = numFormat.curency; } return numFormat; } var number = { formats: { default: 'D' }, // TODO major bump consistent ordering parse: function parse(value, culture) { return globalize.parseFloat(value, 10, culture); }, format: function format(value, _format4, culture) { return globalize.format(value, _format4, culture); }, decimalChar: function decimalChar(format, culture) { var data = formatData(format, culture); return data['.'] || '.'; }, precision: function precision(format, _culture) { var data = formatData(format, _culture); if (typeof format === 'string' && format.length > 1) return parseFloat(format.substr(1)); return data ? data.decimals : null; } }; return { date: date, number: number }; } module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = window.React; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = window.ReactWidgets; /***/ } /******/ ]);
tests/fake/redux-app/ssr/react.js
koriym/Koriym.ReduxReactSsr
import React from 'react'; import ReactDOM from 'react-dom'; import ReactDOMServer from 'react-dom/server'; import { Provider } from 'react-redux'; global.React = React; global.ReactDOM = ReactDOM; global.ReactDOMServer = ReactDOMServer; global.Provider = Provider; global.configureStore = configureStore;